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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesConfigService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
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.CommonEnumUtil;
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.MesConfig;
import cn.estsh.i3plus.pojo.mes.bean.edi.wuhu.MesCimCheryOrder;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesShippingOrderManagement;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesShippingOrderManagementDetail;
import cn.estsh.i3plus.pojo.mes.model.MesShippingOrderManagementDetailModel;
import cn.estsh.i3plus.pojo.mes.model.MesShippingOrderManagementModel;
import cn.estsh.i3plus.pojo.mes.repository.MesCimCheryOrderRepository;
import cn.estsh.impp.framework.boot.util.ResultBean;
import lombok.extern.slf4j.Slf4j;
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;
import java.util.stream.Stream;

/**
 * @Description : 芜湖发运单
 **/
@Service
@Slf4j
public class WuhuSortShippingPrintStrategyService extends SortShippingDispatchStrategyService implements IPrintTemplateStrategyService {

    @Autowired
    private IMesConfigService configService;

    @Autowired
    private MesCimCheryOrderRepository cimCheryOrderRepository;

    @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) {

        MesConfig config = configService.getMesConfigNoError(bean.getOrganizeCode(), "WU_HU_SUPPLIER");
        String supplierNo = (null == config || StringUtils.isEmpty(config.getCfgValue())) ? MesPcnExtConstWords.EMPTY : config.getCfgValue();

        List<MesShippingOrderManagementModel> modelList = new ArrayList<>();
        //把查出来的发运单打印并修改打印状态为已打印-
        for (MesShippingOrderManagement shippingOrderManagement : shippingOrderManagementList) {
            MesShippingOrderManagementModel model = new MesShippingOrderManagementModel();
            String shippingCodePrefix = shippingOrderManagement.getShippingCode().substring(0, shippingOrderManagement.getShippingCode().length() - 3);
            String shippingCodeSuffix = shippingOrderManagement.getShippingCode().substring(shippingOrderManagement.getShippingCode().length() - 3);
            model.setShippingCode(shippingCodePrefix);
            model.setShippingCodeAfter3(shippingCodeSuffix);
            model.setShippingCodeWhole(shippingOrderManagement.getShippingCode());

            //查询原始报文
            List<MesCimCheryOrder> cheryOrderList = getCheryOrder(shippingOrderManagement.getOrganizeCode(), shippingOrderManagement.getShippingCode());
            Map<String, List<MesCimCheryOrder>> cheryOrderMap = new HashMap<>();
            if (cheryOrderList != null && !cheryOrderList.isEmpty()) {
                MesCimCheryOrder cheryOrder = cheryOrderList.get(0);
                model.setPlantName(cheryOrder.getPlantName());
                model.setPartkitName(cheryOrder.getPartkitName());
                model.setDeliverySendSequence(cheryOrder.getDeliverySendSequence());
                model.setReceiveDockName(cheryOrder.getReceiveDockNo()+"--"+cheryOrder.getReceiveDockName());
                model.setLastRecRequireTime(cheryOrder.getLastRecRequireTime());
                //根据cheryOrder的workshopNo获取对应的车间名称
                String workshopName = getWorkshopName(cheryOrder.getOrganizeCode(), cheryOrder.getWorkshopNo());
                model.setWorkShop(workshopName);
                model.setCreateDateTime(cheryOrder.getCreateDatetime());
                model.setPrintDateTime(TimeTool.getNowTime(true));
                cheryOrderMap = cheryOrderList.stream().collect(Collectors.groupingBy(MesCimCheryOrder::getVin));
            }

            //查询发运单明细
            List<MesShippingOrderManagementDetail> shipOrderPartInfos = getShippingOrderManagementDetailList(
                    bean.getOrganizeCode(), Stream.of(shippingOrderManagement.getId()).collect(Collectors.toList()),
                    new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{"boxNum"});
            if (!CollectionUtils.isEmpty(shipOrderPartInfos)) {
                List<MesShippingOrderManagementDetailModel> detailList = new ArrayList<>();
                shipOrderPartInfos = shipOrderPartInfos.stream().sorted(Comparator.comparing(MesShippingOrderManagementDetail::getCustInfoSeq)).collect(Collectors.toList());
                for (MesShippingOrderManagementDetail shipOrderPartInfo : shipOrderPartInfos) {
                    MesShippingOrderManagementDetailModel detailModel = new MesShippingOrderManagementDetailModel();
                    detailModel.setPartNo(shipOrderPartInfo.getPartNo());
                    detailModel.setPartName(shipOrderPartInfo.getPartName());
                    detailModel.setQty(shipOrderPartInfo.getPlanQty());
                    detailModel.setBoxNo(shipOrderPartInfo.getCustInfoSeq());
                    detailModel.setSupplierNo(supplierNo);
                    detailModel.setVin(shipOrderPartInfo.getVin().substring(shipOrderPartInfo.getVin().length()-8));
                    MesCimCheryOrder order = cheryOrderMap.get(shipOrderPartInfo.getVin()).get(0);
                    if (order != null) {
                        detailModel.setWholePartNo(order.getMaterialNo());
                    }
                    detailList.add(detailModel);
                }
                model.setShipOrderPartInfos(detailList);
            }

            //查询原有报文 根据shippingCode;
            shippingOrderManagement.setPrintCount(StringUtil.isEmpty(shippingOrderManagement.getPrintCount())?1:shippingOrderManagement.getPrintCount()+1);
            shippingOrderManagement.setLastPrintTime(TimeTool.getNowTime(true));
            shippingOrderManagement.setLastPrintUser(bean.getUserInfo());
            ConvertBean.serviceModelUpdate(shippingOrderManagement, bean.getUserInfo());
            modelList.add(model);
        }

        saveShippingOrderManagementList(shippingOrderManagementList);

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

    private List<MesCimCheryOrder> getCheryOrder(String organizeCode, String sheetNo) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(sheetNo)) return null;
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(sheetNo, "sheetNo", ddlPackBean);
        return cimCheryOrderRepository.findByHqlWhere(ddlPackBean);
    }

    private String getWorkshopName(String organizeCode, String workshopNo) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(workshopNo)) return null;
        MesConfig config = configService.getMesConfigNoError(organizeCode, workshopNo);
        return (null == config || StringUtils.isEmpty(config.getCfgValue())) ? MesPcnExtConstWords.EMPTY : config.getCfgValue();
    }
}
