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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProduceSnPrintModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesCustSortInfo;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.MesCustSoftInfoRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
/**
 * @Description : 重庆-龙兴-排序工单自动打印
 * @Reference :
 * @Author : logic
 * @CreateDate : 2025/3/13 16:07
 * @Modify:
 **/
@Component
@Slf4j
public class CqLxAssemblyVisualListPrintStrategy implements IPrintTemplateStrategyService {

    @Autowired
    private MesCustSoftInfoRepository mesCustSoftInfoRepository;

    @Override
    public MesProduceSnPrintModel execute(GenSerialNoModel genSerialNoModel, MesProduceSnPrintModel model, MesNumberRule numberRule , StepResult stepResult, StationRequestBean reqBean, Boolean isStep) {

        Map<String, Object> modelMap = (Map<String, Object>) model.getSourceData();

        // 工单信息
        MesWorkOrder workOrder = (MesWorkOrder) modelMap.get("mesWorkOrder");
        // 零件生产组信息
        MesPartProdGroup partProdGroup = (MesPartProdGroup) modelMap.get("mesPartProdGroup");
        // 客户车型配置信息
        MesCustomerCarModel customerCarModel = modelMap.containsKey("mesCustomerCarModel") ? (MesCustomerCarModel) modelMap.get("mesCustomerCarModel") : null;
        // 工单装配件信息
        List<MesWorkOrderAssembly> workOrderAssemblyList = modelMap.containsKey("mesWorkOrderAssemblyList") ? (List<MesWorkOrderAssembly>) modelMap.get("mesWorkOrderAssemblyList") : null;

        workOrderAssemblyList = CollectionUtils.isEmpty(workOrderAssemblyList) ? null :
                workOrderAssemblyList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getDisplaySeq()) && o.getDisplaySeq().compareTo(MesPcnExtConstWords.ZERO) != 0)).collect(Collectors.toList());

        // 返回的结果集合
        List<Map<String, Object>> printDataMapList = new ArrayList<>();
        // 单个标签参数值
        Map<String, Object> resultMap = new HashMap<>();
        // 产线名称
        resultMap.put(MesPcnExtConstWords.WORK_CENTER_NAME, workOrder.getWorkCenterName());
        // 车型名称
        resultMap.put(MesPcnExtConstWords.CAR_MODEL_NAME, customerCarModel == null ? "" : customerCarModel.getCarModelName());
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(workOrder.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(workOrder.getVinCode(), "vinCode", ddlPackBean);
        DdlPreparedPack.getStringEqualPack(workOrder.getCustPartNo(), "custPartNo", ddlPackBean);
        MesCustSortInfo mesCustSortInfo = mesCustSoftInfoRepository.getByProperty(ddlPackBean);
        if (!Objects.isNull(mesCustSortInfo)) {
            // vinCode（取值修改-45623 PCN-龙兴装配目视单模板取值调整：mes_cust_sort_info 表的 info_point_code + cust_info_seq）
            resultMap.put(MesPcnExtConstWords.VIN_CODE, (mesCustSortInfo.getInfoPointCode() + mesCustSortInfo.getCustInfoSeq()));
            // vinCode 后四位（取值修改-45623 PCN-龙兴装配目视单模板取值调整：mes_cust_sort_info 的 cust_info_seq 的后四位，即工单表中的 workOrderSeq 字段）
            resultMap.put(MesPcnExtConstWords.VIN_CODE_AFTER_FOUR,
                    !StringUtils.isEmpty(mesCustSortInfo.getCustInfoSeq()) &&
                            mesCustSortInfo.getCustInfoSeq().toString().length() > MesPcnExtConstWords.FOUR ?
                            mesCustSortInfo.getCustInfoSeq().toString().substring(mesCustSortInfo.getCustInfoSeq().toString().length() - MesPcnExtConstWords.FOUR) :
                            mesCustSortInfo.getCustInfoSeq());
        }
        // 总成零件号
        resultMap.put(MesPcnExtConstWords.PART_NO, workOrder.getPartNo());
        // 工单标识
        resultMap.put(MesPcnExtConstWords.ORDER_FLAG, workOrder.getOrderFlag().equals(MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.PTR.getValue()) ? MesExtEnumUtil.ORDER_TYPE_IDENTIFICATION.P.getValue() : workOrder.getOrderFlag());
        // 客户订单号
        resultMap.put(MesPcnExtConstWords.CUST_ORDER_NO, workOrder.getCustOrderNo());
        // 客户零件号
        resultMap.put(MesPcnExtConstWords.CUST_PART_NO, workOrder.getCustPartNo());
        // 客户条码
        resultMap.put(MesPcnExtConstWords.SN, workOrder.getCustSn());
        // 加工单号
        resultMap.put(MesPcnExtConstWords.WORK_ORDER_NO, workOrder.getWorkOrderNo());
        // 工单备注（取值修改-45623 PCN-龙兴装配目视单模板取值调整：取工单表中的 remark）
        resultMap.put(MesPcnExtConstWords.REMARK, workOrder.getRemark());
        // 重打印
        resultMap.put(MesPcnExtConstWords.REPRINT, "");
        // EDI接口时间 取工单plan_start_time
        resultMap.put(MesPcnExtConstWords.EDI_REC_TIME, workOrder.getPlanStartTime());
        // 打印时间
        resultMap.put(MesPcnExtConstWords.PRINT_TIME, TimeTool.getNowTime("yyyy-MM-dd HH:mm:ss"));
        //替换总成SN
        resultMap.put(MesPcnExtConstWords.REPLACE_CSN,MesPcnExtConstWords.REPLACE_CSN_CP+workOrder.getCustPartNo().substring(workOrder.getCustPartNo().length() -4));

        Map<Integer, List<MesWorkOrderAssembly>> collect = CollectionUtils.isEmpty(workOrderAssemblyList) ? null : workOrderAssemblyList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkOrderAssembly::getDisplaySeq));
        // 为空时显示内容
        String isNullViewContent = StringUtils.isEmpty(partProdGroup.getIsNullViewContent()) ? "" : partProdGroup.getIsNullViewContent();
        for (int i = 1; i <= 9; i ++) {
            List<MesWorkOrderAssembly> orderAssemblyList = CollectionUtils.isEmpty(collect) ? null : collect.get(i);
            List<String> disPlayValues = CollectionUtils.isEmpty(orderAssemblyList) ? null :
                    (orderAssemblyList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getDisplayValue()))).map(MesWorkOrderAssembly::getDisplayValue).collect(Collectors.toList()))
                            .stream().filter(o -> !StringUtils.isEmpty(o)).distinct().collect(Collectors.toList());
            String displayValue = isNullViewContent;
            if(!CollectionUtils.isEmpty(disPlayValues)){
                displayValue = String.join("\r\n", disPlayValues);
            }
            resultMap.put(MesPcnExtConstWords.ASSEMBLY_PARAM + i, displayValue);
        }

        printDataMapList.add(resultMap);

        model.setPrintContextList(packResultMapList(model, printDataMapList));

        return model;
    }

    private List<Map<String, Object>> packResultMapList(MesProduceSnPrintModel printModel, List<Map<String, Object>> printTemplateDateList) {
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(MesPcnExtConstWords.LABEL_TEMPLATE, printModel.getMesLabelTemplate());
        resultMap.put(MesPcnExtConstWords.TEMPLATE_DATA, printTemplateDateList);
        resultMap.put(MesPcnExtConstWords.TEMPLATE_CODE, printModel.getMesLabelTemplate().getTemplateCode());
        resultMap.put(MesPcnExtConstWords.PRINTER, printModel.getPrinter());
        resultMapList.add(resultMap);
        return resultMapList;
    }

}
