package cn.iocoder.yudao.module.identity.service.diversionrecord;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.basic.api.dealergoods.DealerGoodsApi;
import cn.iocoder.yudao.module.basic.api.dealergoods.dto.DealerGoodsRespDTO;
import cn.iocoder.yudao.module.identity.controller.admin.diversionrecord.vo.DiversionRecordExportReqVO;
import cn.iocoder.yudao.module.identity.controller.admin.diversionrecord.vo.DiversionRecordPageReqVO;
import cn.iocoder.yudao.module.identity.controller.admin.diversionrecord.vo.DiversionRecordUpdateReqVO;
import cn.iocoder.yudao.module.identity.convert.diversionrecord.DiversionRecordConvert;
import cn.iocoder.yudao.module.identity.dal.dataobject.code.CodeDO;
import cn.iocoder.yudao.module.identity.dal.dataobject.diversionrecord.DiversionRecordDO;
import cn.iocoder.yudao.module.identity.dal.dataobject.diversionstats.DiversionStatsDO;
import cn.iocoder.yudao.module.identity.dal.mysql.diversionrecord.DiversionRecordMapper;
import cn.iocoder.yudao.module.identity.dal.mysql.diversionstats.DiversionStatsMapper;
import cn.iocoder.yudao.module.identity.enums.ErrorCodeConstants;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 疑似窜货记录 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DiversionRecordServiceImpl implements DiversionRecordService {

    @Resource
    private DiversionRecordMapper diversionRecordMapper;

    @Resource
    private DiversionStatsMapper diversionStatsMapper;

    @Resource
    private DealerGoodsApi dealerGoodsApi;


    /**
     * 更新疑似窜货记录如果是窜货那就新增窜货数据
     *
     * @param updateReqVO 更新信息
     */

    @Override
    public void updateDiversionRecord(DiversionRecordUpdateReqVO updateReqVO) {
        // 校验存在
        DiversionRecordDO selectById = diversionRecordMapper.selectById(updateReqVO.getId());
        if (selectById == null) {
            // 根据selectById未找到对应的记录
            throw exception(ErrorCodeConstants.DIVERSION_RECORD_NOT_EXISTS);
        }
        // 更新
        DiversionRecordDO updateObj = DiversionRecordConvert.INSTANCE.convert(updateReqVO);
        //根据需求  只需要跟新该字段数据
        updateObj.setDiversionState(updateReqVO.getDiversionState());
        updateObj.setRemarks(updateReqVO.getRemarks());
        updateObj.setDiversionLevel(updateReqVO.getDiversionLevel());
        updateObj.setStatus(1);
        if (updateReqVO.getDiversionState() == 1) {
            // 如果是串货，则新增DiversionStatsDO数据
            DiversionStatsDO diversionStats = new DiversionStatsDO();
            diversionStats.setId(null);
            diversionStats.setDealerId(updateObj.getDealerId());
            diversionStats.setDealerName(updateObj.getDealerName());
            diversionStats.setBatchId(updateObj.getBatchId());
            diversionStats.setGoodsId(updateObj.getGoodsId());
            diversionStats.setGoodsName(updateObj.getGoodsName());
            diversionStats.setNum(1); // 设置窜货数为0
            diversionStats.setBelongBusinessId(updateObj.getBelongBusinessId());
            diversionStats.setBelongBusinessName(updateObj.getBelongBusinessName());
            diversionStatsMapper.insert(diversionStats);
        }
        // 更新记录
        diversionRecordMapper.updateById(updateObj);
    }

    /**
     * 删除疑似窜货记录实现
     *
     * @param id 编号
     */
    @Override
    public void deleteDiversionRecord(Long id) {
        // 校验存在
        validateDiversionRecordExists(id);
        // 删除
        diversionRecordMapper.deleteById(id);
    }

    private void validateDiversionRecordExists(Long id) {
        if (diversionRecordMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.DIVERSION_RECORD_NOT_EXISTS);
        }
    }

    /**
     * 获得疑似窜货记录实现
     *
     * @param id 编号
     * @return 疑似窜货记录
     */
    @Override
    public DiversionRecordDO getDiversionRecord(Long id) {
        return diversionRecordMapper.selectById(id);
    }

    /**
     * 获得疑似窜货记录列表实现
     *
     * @param ids 编号
     * @return 疑似窜货记录列表
     */
    @Override
    public List<DiversionRecordDO> getDiversionRecordList(Collection<Long> ids) {
        return diversionRecordMapper.selectBatchIds(ids);
    }

    /**
     * 获得疑似窜货记录分页实现
     *
     * @param pageReqVO 分页查询
     * @return 疑似窜货记录分页
     */
    @Override
    public PageResult<DiversionRecordDO> getDiversionRecordPage(DiversionRecordPageReqVO pageReqVO) {
        return diversionRecordMapper.selectPage(pageReqVO);
    }

    /**
     * 获得疑似窜货记录列表, 用于 Excel 导出实现
     *
     * @param exportReqVO 查询条件
     * @return 疑似窜货记录列表
     */
    @Override
    public List<DiversionRecordDO> getDiversionRecordList(DiversionRecordExportReqVO exportReqVO) {
        List<DiversionRecordDO> diversionRecordList = diversionRecordMapper.selectList(exportReqVO);
        for (DiversionRecordDO record : diversionRecordList) {
            Integer diversionLevel = record.getDiversionLevel();
            if (diversionLevel != null) {
                switch (diversionLevel) {
                    case 0:
                        record.setDiversionLevelText("1级");
                        break;
                    case 1:
                        record.setDiversionLevelText("2级");
                        break;
                    case 2:
                        record.setDiversionLevelText("3级");
                        break;
                    default:
                        break;
                }
            }
            Integer diversionState = record.getDiversionState();
            if (diversionState != null) {
                switch (diversionState) {
                    case 0:
                        record.setDiversionStateText("疑似窜货");
                        break;
                    case 1:
                        record.setDiversionStateText("是窜货");
                        break;
                    case 2:
                        record.setDiversionStateText("不是窜货");
                        break;
                    default:
                        break;
                }
            }
            Integer status = record.getStatus();
            if (status != null) {
                switch (status) {
                    case 0:
                        record.setStatusText("未处理");
                        break;
                    case 1:
                        record.setStatusText("已处理");
                        break;
                    default:
                        break;
                }
            }
        }

        return diversionRecordList;
    }

    /**
     * 根据消费者扫码地区和经销商销售区域的对比结果自动生成
     *
     * @param scanLocation
     */
    @Override
    public void generateDiversionRecord(CodeDO codeDO, String scanLocation) {
        //查询所有对应的经销商区域
        CommonResult<List<DealerGoodsRespDTO>> saleAreas = dealerGoodsApi.getSaleAreasByGoodsAndDealer(codeDO.getGoodsId(), codeDO.getDealerId());
        // 遍历销售区域信息，检查是否有与扫码地区匹配的地区
        boolean isMatchingRegion = false;
        for (DealerGoodsRespDTO saleArea : saleAreas.getData()) {
            if (saleArea.getSaleArea().equals(scanLocation)) {
                isMatchingRegion = true;
                break;
            }
        }
        // 判断是否有匹配的销售区域
        if (!isMatchingRegion) {
            // 没有找到对应的经销商区域，执行新增操作
            DiversionRecordDO diversionRecord = new DiversionRecordDO();
            diversionRecord.setDealerId(codeDO.getDealerId());
            diversionRecord.setDealerName(codeDO.getDealerName());
            diversionRecord.setBatchId(codeDO.getBatchId());
            diversionRecord.setGoodsId(codeDO.getGoodsId());
            diversionRecord.setGoodsName(codeDO.getGoodsName());
            diversionRecord.setScanLocation(scanLocation);
            diversionRecord.setScanTime(new Date());
            diversionRecord.setDiversionState(0);
            diversionRecord.setDiversionLevel(0);
            diversionRecord.setStatus(0); // 未处理状态
            diversionRecord.setBelongBusinessId(codeDO.getBelongBusinessId());
            diversionRecord.setBelongBusinessName(codeDO.getBelongBusinessName());
            //插入数据
            diversionRecordMapper.insert(diversionRecord);
        }
    }

    /**
     * 根据商品编码查询所有数据 然后在查询出所有的数据的同时再过滤出所有相对应的扫码地区
     *
     * @param goodsId
     * @return
     */
    @Override
    public List<DiversionRecordDO> getScanLocationsAndTimesByGoodsId(String goodsId, String batchId, String scanLocation) {
         return diversionRecordMapper.selectByGoodsIdAndBatchIdAndScanLocation(goodsId,batchId,scanLocation);
    }

    @Override
    public List<String> getConsistentGoodsIdAndScanLocations(List<DiversionRecordDO> records, String batchId, String goodsId) {
        return records.stream()
                .filter(record -> record.getBatchId().equals(batchId) && record.getGoodsId().equals(goodsId))
                .map(DiversionRecordDO::getScanLocation)
                .distinct()
                .collect(Collectors.toList());
    }
}
