package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.sortshipping.strategy;

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesSortShippingPrintForCqLxModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.seres.MesCimSeresSrmRunSheetJis;
import cn.estsh.i3plus.pojo.mes.bean.seres.MesCimSeresSrmRunSheetJisDetail;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesShippingOrderManagement;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesShippingOrderManagementDetail;
import cn.estsh.i3plus.pojo.mes.repository.seres.IMesCimSeresSrmRunSheetJisDetailRepository;
import cn.estsh.i3plus.pojo.mes.repository.seres.IMesCimSeresSrmRunSheetJisRepository;
import cn.estsh.impp.framework.boot.util.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @Description : 重庆龙兴发运单
 **/
@Service
@Slf4j
public class CqLxSortShippingPrintStrategyService extends SortShippingDispatchStrategyService implements IPrintTemplateStrategyService {

    @Autowired
    private IMesCimSeresSrmRunSheetJisRepository cimSeresSrmRunSheetJisRepository;

    @Autowired
    private IMesCimSeresSrmRunSheetJisDetailRepository cimSeresSrmRunSheetJisDetailRepository;

    @Override
    public List<MesShippingOrderManagement> getShippingOrderManagementList(MesShippingOrderManagement bean) {
        return super.getShippingOrderManagementList(bean);
    }

    @Override
    public List<MesShippingOrderManagementDetail> getShippingOrderManagementDetailList(String organizeCode, List<Long> idList, Object[] obj, String[] str) {
        return super.getShippingOrderManagementDetailList(organizeCode, idList, obj, str);
    }

    @Override
    public void saveShippingOrderManagementList(List<MesShippingOrderManagement> shippingOrderManagementList) {
        super.saveShippingOrderManagementList(shippingOrderManagementList);
    }

    @Override
    public ResultBean execute(MesShippingOrderManagement bean, List<MesShippingOrderManagement> shippingOrderManagementList) {

        List<MesSortShippingPrintForCqLxModel> resultList = new ArrayList<>();

        List<String> shippingCodeList = shippingOrderManagementList.stream().map(MesShippingOrderManagement::getShippingCode).collect(Collectors.toList());
        List<MesCimSeresSrmRunSheetJis> cimSeresSrmRunSheetJisList = getCimSeresSrmRunSheetJisList(bean.getOrganizeCode(), shippingCodeList);
        Map<String, List<MesCimSeresSrmRunSheetJis>> jisByScMap = CollectionUtils.isEmpty(cimSeresSrmRunSheetJisList) ? null :
                cimSeresSrmRunSheetJisList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getDocNo()))).collect(Collectors.groupingBy(MesCimSeresSrmRunSheetJis::getDocNo));
        log.info("工厂{}排序发运打印 --- 查询JIS单信息:{}条 --- {}", bean.getOrganizeCode(),
                CollectionUtils.isEmpty(cimSeresSrmRunSheetJisList) ? MesPcnExtConstWords.ZERO : cimSeresSrmRunSheetJisList.size(), Thread.currentThread().getName());

        List<Long> jisIdList = CollectionUtils.isEmpty(cimSeresSrmRunSheetJisList) ? null :
                cimSeresSrmRunSheetJisList.stream().map(MesCimSeresSrmRunSheetJis::getId).collect(Collectors.toList());
        List<MesCimSeresSrmRunSheetJisDetail> cimSeresSrmRunSheetJisDetailList = getCimSeresSrmRunSheetJisDetailList(bean.getOrganizeCode(), jisIdList);
        Map<Long, List<MesCimSeresSrmRunSheetJisDetail>> jisDetailByPidMap = CollectionUtils.isEmpty(cimSeresSrmRunSheetJisDetailList) ? null :
                cimSeresSrmRunSheetJisDetailList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPid()))).collect(Collectors.groupingBy(MesCimSeresSrmRunSheetJisDetail::getPid));
        log.info("工厂{}排序发运打印 --- 查询JIS单详情信息:{}条 --- {}", bean.getOrganizeCode(),
                CollectionUtils.isEmpty(cimSeresSrmRunSheetJisDetailList) ? MesPcnExtConstWords.ZERO : cimSeresSrmRunSheetJisDetailList.size(), Thread.currentThread().getName());

        //遍历处理每个发运单主表
        for (MesShippingOrderManagement shippingOrderManagement : shippingOrderManagementList) {
            if (null == shippingOrderManagement) continue;

            List<MesCimSeresSrmRunSheetJis> sheetJis = CollectionUtils.isEmpty(jisByScMap) ? null : jisByScMap.get(shippingOrderManagement.getShippingCode());
            if (CollectionUtils.isEmpty(sheetJis)) continue;

            MesSortShippingPrintForCqLxModel result = new MesSortShippingPrintForCqLxModel();
            BeanUtils.copyProperties(sheetJis.get(0), result);
            result.setTitleName(shippingOrderManagement.getShippingGroupName());
            result.setShippingCode(shippingOrderManagement.getShippingCode());
            if (shippingOrderManagement.getShippingCode().length() >= 4) {
                result.setCarsNo(shippingOrderManagement.getShippingCode().substring(shippingOrderManagement.getShippingCode().length() - 4));
                result.setDocNoOther(shippingOrderManagement.getShippingCode().substring(0, shippingOrderManagement.getShippingCode().length() - 4));
            }
            List<MesCimSeresSrmRunSheetJisDetail> sheetJisDetailList = CollectionUtils.isEmpty(jisDetailByPidMap) ? new ArrayList<>() : jisDetailByPidMap.get(sheetJis.get(0).getId());
            if (!CollectionUtils.isEmpty(sheetJisDetailList)) sheetJisDetailList = sheetJisDetailList.stream().filter(o ->
                    (null != o && !StringUtils.isEmpty(o.getSerialNumber()))).sorted(Comparator.comparing(MesCimSeresSrmRunSheetJisDetail::getSerialNumber)).collect(Collectors.toList());

            Integer index = MesPcnExtConstWords.ONE;
            for (MesCimSeresSrmRunSheetJisDetail cimSeresSrmRunSheetJisDetail : sheetJisDetailList) {
                if (null == cimSeresSrmRunSheetJisDetail) continue;
                MesSortShippingPrintForCqLxModel jisDetail = new MesSortShippingPrintForCqLxModel();
                BeanUtils.copyProperties(cimSeresSrmRunSheetJisDetail, jisDetail);
                //跟cc确认过可以直接写死
                jisDetail.setFactoryCode("000003263");
                jisDetail.setXh(index);
                index ++;
                result.addJisDetail(jisDetail);
            }

            Map<String, List<MesSortShippingPrintForCqLxModel>> sheetJisDetailMap = CollectionUtils.isEmpty(result.getJisDetailList()) ? new HashMap<>() :
                    result.getJisDetailList().stream().filter(o -> null != o).collect(Collectors.groupingBy(MesSortShippingPrintForCqLxModel::getMaterielCode));

            for (Map.Entry<String, List<MesSortShippingPrintForCqLxModel>> entry : sheetJisDetailMap.entrySet()) {
                if (null == entry) continue;

                List<MesSortShippingPrintForCqLxModel> amountList = entry.getValue();
                if (CollectionUtils.isEmpty(amountList)) continue;

                MesSortShippingPrintForCqLxModel amount = new MesSortShippingPrintForCqLxModel();
                amount.setPartNo(amountList.get(0).getMaterielCode());
                amount.setAmountQty(amountList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getUseQty()))).mapToDouble(MesSortShippingPrintForCqLxModel::getUseQty).sum());
                StringJoiner appendRows = new StringJoiner(MesPcnExtConstWords.COMMA);
                amountList.forEach(o -> appendRows.add(o.getXh().toString()));
                amount.setAppendRows(appendRows.toString());
                amount.setMaterielNames(amountList.get(0).getMaterielNames());
                result.addAmount(amount);
            }

            resultList.add(result);

            shippingOrderManagement.setPrintCount(StringUtil.isEmpty(shippingOrderManagement.getPrintCount()) ? MesPcnExtConstWords.ONE : shippingOrderManagement.getPrintCount() + MesPcnExtConstWords.ONE);
            shippingOrderManagement.setLastPrintTime(TimeTool.getNowTime(true));
            shippingOrderManagement.setLastPrintUser(bean.getUserInfo());
            ConvertBean.serviceModelUpdate(shippingOrderManagement, bean.getUserInfo());
        }

        saveShippingOrderManagementList(shippingOrderManagementList);

        return ResultBean.success("发运单打印成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(resultList);

    }

    private List<MesCimSeresSrmRunSheetJis> getCimSeresSrmRunSheetJisList(String organizeCode, List<String> shippingCodeList) {
        if (StringUtils.isEmpty(organizeCode) || CollectionUtils.isEmpty(shippingCodeList)) return null;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (shippingCodeList.size() == 1) DdlPreparedPack.getStringEqualPack(shippingCodeList.get(0), "docNo", packBean);
        else DdlPreparedPack.getInPackList(shippingCodeList, "docNo", packBean);
        return cimSeresSrmRunSheetJisRepository.findByHqlWhere(packBean);
    }

    private List<MesCimSeresSrmRunSheetJisDetail> getCimSeresSrmRunSheetJisDetailList(String organizeCode, List<Long> jisIdList) {
        if (StringUtils.isEmpty(organizeCode) || CollectionUtils.isEmpty(jisIdList)) return null;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (jisIdList.size() == 1) DdlPreparedPack.getNumEqualPack(jisIdList.get(0), MesPcnExtConstWords.PID, packBean);
        else DdlPreparedPack.getInPackList(jisIdList, MesPcnExtConstWords.PID, packBean);
        return cimSeresSrmRunSheetJisDetailRepository.findByHqlWhere(packBean);
    }

}
