package com.hzs.system.config.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.domain.system.config.BdDelivery;
import com.hzs.system.config.mapper.BdDeliveryMapper;
import com.hzs.system.config.service.IBdDeliveryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 发货方式表 服务实现类
 *
 * @author hzs
 * @since 2022-10-10
 */
@Service
public class BdDeliveryServiceImpl extends ServiceImpl<BdDeliveryMapper, BdDelivery> implements IBdDeliveryService {

    @Override
    public List<BdDelivery> queryList(Integer pkCountry) {
        QueryWrapper<BdDelivery> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.orderByAsc("VALUE");
        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveData(List<Integer> deliveryValueList, Long userId, Integer pkCountry) {
        Date nowDate = new Date();

        // 删除旧发货方式
        UpdateWrapper<BdDelivery> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        baseMapper.update(null, updateWrapper);

        // 插入新发货方式
        for (Integer deliveryValue : deliveryValueList) {
            BdDelivery bdDelivery = new BdDelivery();
            bdDelivery.setValue(deliveryValue);
            bdDelivery.setPkCountry(pkCountry);
            bdDelivery.setPkCreator(userId);
            bdDelivery.setCreationTime(nowDate);
            baseMapper.insert(bdDelivery);
        }
    }

}
