package com.xisc.pm.app.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.hzero.boot.platform.code.builder.CodeRuleBuilder;
import org.hzero.boot.platform.code.constant.CodeConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xisc.pm.app.service.PmRequestInfoService;
import com.xisc.pm.app.service.autoboard.dto.PmAutoBoardMoldDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoBoardPolicyDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoBoardPolicyGroupDTO;
import com.xisc.pm.app.service.autoboard.dto.PmOrderGroupDTO;
import com.xisc.pm.domain.entity.PmPolicyGrKpi;
import com.xisc.pm.domain.entity.PmPolicyGroup;
import com.xisc.pm.domain.entity.PmPolicyGroupAttr;
import com.xisc.pm.domain.entity.PmRePolicyOrderRel;
import com.xisc.pm.domain.entity.PmRePolicySection;
import com.xisc.pm.domain.entity.PmRePolicySlbMethod;
import com.xisc.pm.domain.entity.PmRequestInfo;
import com.xisc.pm.domain.entity.PmRequestPolicy;
import com.xisc.pm.domain.entity.PmRequestPolicyKpi;
import com.xisc.pm.domain.entity.PmRequestPolicyVip;
import com.xisc.pm.domain.repository.PmRePolicyOrderRelRepository;
import com.xisc.pm.domain.repository.PmRePolicySectionRepository;
import com.xisc.pm.domain.repository.PmRePolicySlbMethodRepository;
import com.xisc.pm.domain.repository.PmRequestInfoRepository;
import com.xisc.pm.domain.repository.PmRequestPolicyKpiRepository;
import com.xisc.pm.domain.repository.PmRequestPolicyRepository;
import com.xisc.pm.domain.repository.PmRequestPolicyVipRepository;
import com.xisc.pm.infra.constant.Constants;
import com.xisc.pm.infra.enums.AutoPdRequestStatus;

import io.choerodon.core.domain.Page;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;

/**
 * 请求信息表应用服务默认实现
 *
 * @author jun.zeng 2024-11-25 14:51:07
 */
@Service
public class PmRequestInfoServiceImpl implements PmRequestInfoService {

    @Autowired
    private PmRequestInfoRepository pmRequestInfoRepository;

    @Autowired
    private PmRequestPolicyRepository pmRequestPolicyRepository;

    @Autowired
    private PmRePolicyOrderRelRepository pmRePolicyOrderRelRepository;

    @Autowired
    private PmRePolicySlbMethodRepository pmRePolicySlbMethodRepository;

    @Autowired
    private PmRePolicySectionRepository pmRePolicySectionRepository;

    @Autowired
    private PmRequestPolicyVipRepository pmRequestPolicyVipRepository;

    @Autowired
    private PmRequestPolicyKpiRepository pmRequestPolicyKpiRepository;

    @Autowired
    private CodeRuleBuilder codeRuleBuilder;

    private final static String PM_REQUEST_NO = "PM.REQUEST_NO";

    @Override
    public Page<PmRequestInfo> list(Long tenantId, PmRequestInfo pmRequestInfo, PageRequest pageRequest) {
        return pmRequestInfoRepository.pageAndSort(pageRequest, pmRequestInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PmRequestInfo createAutoBoardReqeust(PmAutoBoardPolicyGroupDTO policyGroup, String requestType,
            PmPolicyGroup pmPolicyGroup, PmPolicyGroupAttr pmPolicyGroupAttr, Long tenantId) {
        PmRequestInfo pmRequestInfo = new PmRequestInfo();
        String requestCode = codeRuleBuilder.generateCode(tenantId, PM_REQUEST_NO,
                CodeConstants.CodeRuleLevelCode.GLOBAL, Constants.CodeRule.GLOBAL_LEVEL_VALUE, new HashMap<>(1));
        pmRequestInfo.setRequestCode(requestCode);
        pmRequestInfo.setRequestStatus(AutoPdRequestStatus.EXECUTION.name());
        pmRequestInfo.setPolicyGroupId(pmPolicyGroup.getPolicyGroupId());
        pmRequestInfo.setBetterToWorseFlag(pmPolicyGroup.getBetterToWorseFlag());
        pmRequestInfo.setDelivyDateFrom(pmPolicyGroup.getDelivyDateFrom());
        pmRequestInfo.setDelivyDateTo(pmPolicyGroup.getDelivyDateTo());
        pmRequestInfo.setDesignLengthMax(pmPolicyGroup.getDesignLengthMax());
        pmRequestInfo.setInvertedFlag(pmPolicyGroup.getInvertedFlag());
        pmRequestInfo.setOvercastDelivyDateTo(pmPolicyGroup.getOvercastDelivyDateTo());
        pmRequestInfo.setOvercastQty(pmPolicyGroup.getOvercastQty());
        pmRequestInfo.setRequestType(requestType);
        if(policyGroup.getContractNumList() != null && !policyGroup.getContractNumList().isEmpty()) {
            pmRequestInfo.setContractNums(String.join(",", policyGroup.getContractNumList()));
        }
        pmRequestInfo.setYieldLower(pmPolicyGroup.getYieldLower());
        pmRequestInfo.setExecStartDate(new Date());
        pmRequestInfo.setTenantId(tenantId);
        if (pmPolicyGroupAttr != null) {
            pmRequestInfo.setClearA2WidDeviation(pmPolicyGroupAttr.getA2WidDeviation());
            pmRequestInfo.setClearContractAllowance(pmPolicyGroupAttr.getClearContractAllowance());
            pmRequestInfo.setClearDelivyDateTo(pmPolicyGroupAttr.getClearDelivyDateTo());
            pmRequestInfo.setClearDesignLengthMax(pmPolicyGroupAttr.getDesignLengthMax());
            pmRequestInfo.setClearOvercastDelivyDateTo(pmPolicyGroupAttr.getOvercastDelivyDateTo());
            pmRequestInfo.setClearOvercastQty(pmPolicyGroupAttr.getOvercastQty());
            pmRequestInfo.setClearSingleYield(pmPolicyGroupAttr.getSingleYield());
            pmRequestInfo.setPriorityContractAllowance(pmPolicyGroupAttr.getPriorityContractAllowance());
            pmRequestInfo.setPriorityDelivyDateTo(pmPolicyGroupAttr.getPriorityDelivyDateTo());
        }
        this.pmRequestInfoRepository.insertSelective(pmRequestInfo);
        // 策略信息
        List<PmRequestPolicy> policyList = new ArrayList<PmRequestPolicy>();
        Map<Long, PmRequestPolicy> policyMap = new HashMap<>();
        long i = 1L;
        for (PmAutoBoardPolicyDTO policy : policyGroup.getPolicyList()) {
            PmRequestPolicy pmRequestPolicy = new PmRequestPolicy();
            pmRequestPolicy.setA2WidDeviation(policy.getA2WidDeviation());
            pmRequestPolicy.setConsignCust(policy.getConsignCust());
            pmRequestPolicy.setCustLowerEconomicLots(policy.getCustLowerEconomicLots());
            pmRequestPolicy.setPolicyId(policy.getPolicyId());
            pmRequestPolicy.setPolicySeq(i++);
            pmRequestPolicy.setRequestId(pmRequestInfo.getRequestId());
            pmRequestPolicy.setPolicyCode(policy.getPolicyCode());
            pmRequestPolicy.setStLowerEconomicLots(policy.getStLowerEconomicLots());
            pmRequestPolicy.setTenantId(tenantId);
            pmRequestPolicy.setMscLineNo(policy.getMscLineNo());
            if (policyGroup.getStGroupMap().containsKey(policy.getPolicyId())) {
                // 钢种组
                String stGroupCode = policyGroup.getStGroupMap().get(policy.getPolicyId());
                pmRequestPolicy.setStGroupCode(stGroupCode);
            }
            if (policyGroup.getStMap() != null && !policyGroup.getStMap().isEmpty()
                    && policyGroup.getStMap().containsKey(policy.getPolicyId())) {
                pmRequestPolicy.setStNo(String.join(",", policyGroup.getStMap().get(policy.getPolicyId())));
            }
            policyMap.put(pmRequestPolicy.getPolicyId(), pmRequestPolicy);
            policyList.add(pmRequestPolicy);
        }
        pmRequestPolicyRepository.batchInsertSelective(policyList);
        // 评价指标
        if (policyGroup.getKpis() != null && !policyGroup.getKpis().isEmpty()) {
            List<PmRequestPolicyKpi> pmRequestPolicyKpis = new ArrayList<>();
            for (PmPolicyGrKpi kpi : policyGroup.getKpis()) {
                PmRequestPolicyKpi pmRequestPolicyKpi = new PmRequestPolicyKpi();
                pmRequestPolicyKpi.setRequestId(pmRequestInfo.getRequestId());
                pmRequestPolicyKpi.setKpiType(kpi.getKpiType());
                pmRequestPolicyKpi.setKpiPercent(kpi.getKpiPercent());
                pmRequestPolicyKpis.add(pmRequestPolicyKpi);
            }
            pmRequestPolicyKpiRepository.batchInsertSelective(pmRequestPolicyKpis);
        }

        // 合同分组
        List<PmRePolicyOrderRel> pmRePolicyOrderRels = new ArrayList<>();
        for (PmOrderGroupDTO pmOrderGroup : policyGroup.getOrderGroup()) {
            PmRePolicyOrderRel pmRePolicyOrderRel = new PmRePolicyOrderRel();
            pmRePolicyOrderRel.setGroupDimension(String.join(",", pmOrderGroup.getGroupDimenSion()));
            pmRePolicyOrderRel.setRequestId(pmRequestInfo.getRequestId());
            if(pmOrderGroup.getGroupSeq() != null || !pmOrderGroup.getGroupSeq().isEmpty()) {
                pmRePolicyOrderRel.setGroupSeq(String.join(",", pmOrderGroup.getGroupSeq()));
            }
            pmRePolicyOrderRel.setPriority(pmOrderGroup.getPriority());
            pmRePolicyOrderRel.setTenantId(tenantId);
            pmRePolicyOrderRels.add(pmRePolicyOrderRel);
        }
        pmRePolicyOrderRelRepository.batchInsertSelective(pmRePolicyOrderRels);

        List<PmRePolicySlbMethod> pmRePolicySlbMethods = new ArrayList<>();
        List<PmRePolicySection> pmRePolicySections = new ArrayList<>();
        List<PmRequestPolicyVip> vips = new ArrayList<>();
        for (PmAutoBoardPolicyDTO policy : policyGroup.getPolicyList()) {
            // 指定断面
            Long moldIndex = 1L;
            PmRequestPolicy pmRequestPolicy = policyMap.get(policy.getPolicyId());
            for (PmAutoBoardMoldDTO boardMold : policy.getMoldList()) {
                PmRePolicySection pmRePolicySection = new PmRePolicySection();
                pmRePolicySection.setRequestPolicyId(pmRequestPolicy.getRequestPolicyId());
                pmRePolicySection.setMoldThick(boardMold.getMoldThick());
                pmRePolicySection.setMoldWid(boardMold.getMoldWidth());
                pmRePolicySection.setPriority(moldIndex++);
                pmRePolicySections.add(pmRePolicySection);
            }
            // 组板方式
            Long modeIndex = 1L;
            for (String fromPlateMode : policy.getFormModeCodeList()) {
                PmRePolicySlbMethod pmRePolicySlbMethod = new PmRePolicySlbMethod();
                pmRePolicySlbMethod.setRequestPolicyId(pmRequestPolicy.getRequestPolicyId());
                pmRePolicySlbMethod.setComboSlabMethod(fromPlateMode);
                pmRePolicySlbMethod.setPriority(modeIndex++);
                pmRePolicySlbMethods.add(pmRePolicySlbMethod);
            }
            // 重要客户
            if (policy.getCustomerVip() != null) {
                for (Entry<String, Long> entry : policy.getCustomerVip().entrySet()) {
                    PmRequestPolicyVip pmRequestPolicyVip = new PmRequestPolicyVip();
                    pmRequestPolicyVip.setCustomerCode(entry.getKey());
                    pmRequestPolicyVip.setPriority(entry.getValue());
                    pmRequestPolicyVip.setRequestPolicyId(pmRequestPolicy.getRequestPolicyId());
                    vips.add(pmRequestPolicyVip);
                }
            }
        }
        if (!vips.isEmpty()) {
            pmRequestPolicyVipRepository.batchInsertSelective(vips);
        }
        if (!pmRePolicySections.isEmpty()) {
            pmRePolicySectionRepository.batchInsertSelective(pmRePolicySections);
        }
        if (!pmRePolicySlbMethods.isEmpty()) {
            pmRePolicySlbMethodRepository.batchInsertSelective(pmRePolicySlbMethods);
        }
        return pmRequestInfo;
    }

}
