package com.hzs.sale.deliver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
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.constant.msg.SaOrderMsgConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.domain.sale.deliver.SaDeliverBarCode;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.sale.deliver.mapper.SaDeliverBarCodeMapper;
import com.hzs.sale.deliver.param.BindCodeParam;
import com.hzs.sale.deliver.service.ISaDeliverBarCodeService;
import com.hzs.system.base.IBarCodeServiceApi;
import com.hzs.system.base.dto.BarCodeUseDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 发货条码表 服务实现类
 *
 * @author hzs
 * @since 2022-11-02
 */
@Service
public class SaDeliverBarCodeServiceImpl extends ServiceImpl<SaDeliverBarCodeMapper, SaDeliverBarCode> implements ISaDeliverBarCodeService {

    @DubboReference
    private IBarCodeServiceApi iBarCodeServiceApi;


    @Override
    public List<SaDeliverBarCode> queryBarCodeList(List<BindCodeParam> paramList, Integer pkCountry) {
        return baseMapper.queryBarCodeList(paramList, pkCountry);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void codeReset(Long id, Integer pkCountry, Long userId) {
        SaDeliverBarCode saDeliverBarCode = baseMapper.selectById(id);

        if (null != saDeliverBarCode) {
            // 清除发货单条码表
            UpdateWrapper<SaDeliverBarCode> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
            updateWrapper.eq(SystemFieldConstants.PK_ID, id);
            updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
            updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
            updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
            baseMapper.update(null, updateWrapper);

            // 调用条码服务，解绑条码
            if (!iBarCodeServiceApi.clearBarCode(Collections.singletonList(saDeliverBarCode.getPkBarCodeItems()), pkCountry, userId).isSuccess()) {
                // 重置条码失败
                throw new ServiceException(TransactionUtils.getContent(SaOrderMsgConstants.DELIVER_CLEAR_CODE));
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void codeClear(List<Integer> idList, Integer pkCountry, Long userId) {
        QueryWrapper<SaDeliverBarCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.in(SystemFieldConstants.PK_ID, idList);
        List<SaDeliverBarCode> deliverBarCodeList = baseMapper.selectList(queryWrapper);

        // 清除发货单条码表
        UpdateWrapper<SaDeliverBarCode> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        updateWrapper.in(SystemFieldConstants.PK_ID, idList);
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
        baseMapper.update(null, updateWrapper);

        if (deliverBarCodeList.size() > 0) {
            List<Integer> barCodeIdList = deliverBarCodeList.stream().map(SaDeliverBarCode::getPkBarCodeItems).collect(Collectors.toList());
            // 调用条码服务，解绑条码
            if (!iBarCodeServiceApi.clearBarCode(barCodeIdList, pkCountry, userId).isSuccess()) {
                // 重置条码失败
                throw new ServiceException(TransactionUtils.getContent(SaOrderMsgConstants.DELIVER_CLEAR_CODE));
            }
        }

    }


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

        // 新增发货单条码数据
        List<SaDeliverBarCode> list = new ArrayList<>(paramList.size());
        // 新增条码列表
        List<BarCodeUseDTO> barCodeUseList = new ArrayList<>(paramList.size());

        // 封装插入新条码数据
        for (BindCodeParam bindCodeParam : paramList) {
            SaDeliverBarCode saDeliverBarCode = new SaDeliverBarCode();
            saDeliverBarCode.setPkDeliver(bindCodeParam.getPkDeliver());
            saDeliverBarCode.setPkDeliverItems(bindCodeParam.getPkId());
            saDeliverBarCode.setPkProduct(bindCodeParam.getPkProduct());
            saDeliverBarCode.setPkBarCodeItems(bindCodeParam.getDeliverBarCodeId());
            saDeliverBarCode.setBarCode(bindCodeParam.getBarCode());
            saDeliverBarCode.setPkCountry(pkCountry);
            saDeliverBarCode.setPkCreator(userId);
            saDeliverBarCode.setCreationTime(nowDate);
            saDeliverBarCode.setPkModified(userId);
            saDeliverBarCode.setModifiedTime(nowDate);
            list.add(saDeliverBarCode);

            barCodeUseList.add(BarCodeUseDTO.builder()
                    .barCodeItemsId(bindCodeParam.getDeliverBarCodeId())
                    .build());
        }
        // 插入发货单条码
        baseMapper.insertBatch(list);

        // 调用条码服务标记使用状态
        if (!iBarCodeServiceApi.useBarCode(barCodeUseList, pkCountry, userId).isSuccess()) {
            // 绑定条码失败
            throw new ServiceException(TransactionUtils.getContent(SaOrderMsgConstants.DELIVER_BIND_CODE));
        }
    }

    @Override
    public Map<Long, SaDeliverBarCode> queryListByDeliverItems(List<Long> deliverItemsIdList, Integer pkCountry) {
        Map<Long, SaDeliverBarCode> resultMap = new HashMap<>();
        List<SaDeliverBarCode> list = baseMapper.queryListByDeliverItems(deliverItemsIdList, pkCountry);
        if (CollectionUtil.isNotEmpty(list)) {
            for (SaDeliverBarCode saDeliverBarCode : list) {
                resultMap.put(saDeliverBarCode.getPkDeliverItems(), saDeliverBarCode);
            }
        }
        return resultMap;
    }

    @Override
    public int insertBatch(List<SaDeliverBarCode> list) {
        return baseMapper.insertBatch(list);
    }

}
