package com.xisc.pm.app.service.strategy.pdrule;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.compress.utils.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xisc.pm.api.dto.RuleParamDTO;
import com.xisc.pm.app.service.strategy.RuleExecStrategyFactory;
import com.xisc.pm.domain.entity.PmContMscTech;
import com.xisc.pm.domain.entity.PmProContProdTtr;
import com.xisc.pm.domain.repository.MmHtmrsltRepository;
import com.xisc.pm.domain.vo.MmPlateVO;
import com.xisc.pm.infra.constant.RuleSetConstants;
import com.xisc.pm.infra.enums.PdMatType;
import com.xisc.pm.infra.enums.PdRuleItemType;

import io.choerodon.core.exception.CommonException;

/**
 * 热处理材料与合同热处理模式匹配检查（P01）
 * 根据材料号MAT_NO等于输入材料号mat_no，获取热处理实绩表MM_HTMRSLT最大生产流水号HTM_SEQ对应的热处理方式代码HOT_TREAT_METHOD_CODE。
 * 若不存在，则根据材料号MAT_NO等于输入材料号mat_no截取第二位开始共7位加‘000’，查询热处理实绩表MM_HTMRSLT中最大生产流水号HTM_SEQ对应的热处理方式代码HOT_TREAT_METHOD_CODE。若依然不存在，则热处理方式代码HOT_TREAT_METHOD_CODE为0。
 */
@Component
public class HotTreatMthodRuleExecStrategy implements RuleExecStrategy {

    @Autowired
    private MmHtmrsltRepository mmHtmrsltRepository;

    @Override
    public void afterPropertiesSet() throws Exception {
        RuleExecStrategyFactory.register(PdRuleItemType.HOT_TREAT_METHOD, this);
    }

    /**
     * 获取热处理实绩代码
     *
     * @param matNo
     * @param tenantId
     * @return
     */
    private Set<String> getHotTreatMethodByMatNo(String matNo, Long tenantId) {
        Set<String> hotTreatMethodList = null;
        String key = PdRuleItemType.HOT_TREAT_METHOD.name() + "." + matNo;
        String value = CACHE.getIfPresent(key);
        if (value == null) {
            hotTreatMethodList = mmHtmrsltRepository.getHotTreatMethodByMatNo(matNo, tenantId);
            value = String.join(",", hotTreatMethodList);
            CACHE.put(key, value);
        } else {
            hotTreatMethodList = Sets.newHashSet(value.split(","));
        }
        return hotTreatMethodList;
    }

    @Override
    public boolean execRule(RuleParamDTO ruleParam) {
        Map<String, Object> bizData = ruleParam.getBizData();
        String orderNo = (String) bizData.get(RuleSetConstants.ORDER_NO);
        String mscLineNo = (String) bizData.get(RuleSetConstants.MSC_LINE_NO);
        String matDesignKind = (String) bizData.get(RuleSetConstants.MAT_DESIGN_KIND);

        PmContMscTech pmContMscTech = (PmContMscTech) bizData.get(RuleSetConstants.PM_CONT_MSC_TECH);
        MmPlateVO mmPlateVO = (MmPlateVO) bizData.get(RuleSetConstants.MM_PLATE);
        if (pmContMscTech == null) {
            // 读生产合同池没有找到记录，合同号【order_no】，产线号【msc_line_no】
            throw new CommonException("pm.pm_pd_rule_set_001", orderNo, mscLineNo);
        }
        if(!PdMatType.P.getCode().equals(matDesignKind)) {
            // 只有余材钢板匹配该规则集
            return true ;
        }
        if (mmPlateVO == null) {
            throw new CommonException("pm.pm_pd_plate_001");
        }
        Set<String> hotTreatMethodList = getHotTreatMethodByMatNo(mmPlateVO.getMatNo(), ruleParam.getTenantId());
        if(StringUtils.isBlank(pmContMscTech.getWholeHeatTreatmentType()) || "0".equals(pmContMscTech.getWholeHeatTreatmentType())) {
            if(hotTreatMethodList != null && hotTreatMethodList.size() == 1 &&
                    "0".equals(hotTreatMethodList.iterator().next())) {
                return true ;
            } else {
                String value = pmContMscTech.getWholeHeatTreatmentType() == null ? "":pmContMscTech.getWholeHeatTreatmentType();
                throw new CommonException("pm.pm_pd_rule_set_035", orderNo, value, String.join(",", hotTreatMethodList));
            }
        } else {
            Set<String> orderWholeHeatTreatment = new HashSet<>();
            for (int i = 0 ;i < pmContMscTech.getWholeHeatTreatmentType().length() ; i ++) {
                String value = String.valueOf(pmContMscTech.getWholeHeatTreatmentType().charAt(i));
                orderWholeHeatTreatment.add(value);
                if(!hotTreatMethodList.contains(value)) {
                    throw new CommonException("pm.pm_pd_rule_set_035", orderNo, pmContMscTech.getWholeHeatTreatmentType(), String.join(",", hotTreatMethodList));
                }
            }
            if(hotTreatMethodList.size() != orderWholeHeatTreatment.size()) {
                throw new CommonException("pm.pm_pd_rule_set_035", orderNo, pmContMscTech.getWholeHeatTreatmentType(), String.join(",", hotTreatMethodList));
            }
        }
        
        
//        String psc = pmProContProdTtr.getPsc();
//        if (PdMatType.P.getCode().equals(matDesignKind)) {
//            if (StringUtils.isBlank(psc) || psc.length() < 7) {
//                throw new CommonException("pm.pm_pd_rule_set_034", orderNo, StringUtils.isBlank(psc) ? "0" : psc.length());
//            }
//
//            char hotTreatMethodFirst = hotTreatMethod.charAt(0);
//            char psc0 = psc.charAt(6);
//            if (psc0 == '1' || psc0 == '2' || psc0 == '3') {
//                psc0 = '0';
//            }
//            if (psc0 != '0' && psc0 != hotTreatMethodFirst) {
//                // 材料与合同热处理方式不符，不能充当，合同【psc[6]】，材料【HOT_TREAT_METHOD_CODE[0]】。
//                throw new CommonException("pm.pm_pd_rule_set_035", orderNo, psc0, hotTreatMethodFirst);
//            }
//        }
        return true;
    }

}
