package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.ep;

import cn.estsh.i3plus.ext.mes.api.base.ep.IEpNumberRuleExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesNumberRuleExt;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesNumberRuleExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.mes.apiservice.util.GenSerialNoUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-27 15:00
 */
@Service
public class EpNumberRuleExtService  implements IEpNumberRuleExtService {

    @Autowired
    private MesNumberRuleExtRepository numberRuleExtRepository;

    @Override
    public MesNumberRuleExt insertNumberRule(MesNumberRuleExt numberRuleExt) {
        MesNumberRuleExt numberRuleDb = numberRuleExtRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.RULE_CODE},
                new Object[]{numberRuleExt.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), numberRuleExt.getRuleCode()});
        if (null != numberRuleDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("规则代码为[%s]的记录已存在", numberRuleExt.getRuleCode())
                    .build();
        }
        Map<String, String> checkMap = checkEpNumberRuleValid(numberRuleExt);
        if (checkMap.get(MesExtConstWords.success).equals(MesExtConstWords.FALSE)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.PARAMETER_EXCEPTION.getCode())
                    .setErrorDetail(checkMap.get(MesExtConstWords.MSG))
                    .build();
        }

        checkRuleLengthSpilt(numberRuleExt);

//        checkNumberRuleExtExist(numberRuleExt, null);
        ConvertBean.serviceModelInitialize(numberRuleExt, numberRuleExt.getCreateUser());
        new ConvertBeanExt(numberRuleExt).convertBean(numberRuleExt);
        return numberRuleExtRepository.insert(numberRuleExt);
    }

    private void checkRuleLengthSpilt(MesNumberRuleExt numberRuleExt) {
        if (!StringUtils.isEmpty(numberRuleExt.getRuleLengthSpilt())) {
            String[] ruleLengthSpiltArr = numberRuleExt.getRuleLengthSpilt().trim().split(",");
            String[] numberRuleArr = numberRuleExt.getNumberRule().replaceAll("\\{", "").split("}");
            if (ruleLengthSpiltArr.length != numberRuleArr.length) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("规则属性长度拼接验证错误,与编码规则属性数量不一致")
                        .build();
            }
            for (String length : ruleLengthSpiltArr) {
                try {
                    if(length.charAt(0) < 'A' || length.charAt(0) > 'Z'){
                        Integer len = Integer.parseInt(length);
                        if (len.compareTo(0) <= 0) {
                            throw ImppExceptionBuilder.newInstance()
                                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                                    .setErrorDetail("规则属性长度拼接验证错误,只能拼接正整数或大写字母代替未知数")
                                    .build();
                        }
                    }
                } catch (NumberFormatException e) {
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                            .setErrorDetail("规则属性长度拼接验证错误,只能拼接正整数")
                            .build();
                }
            }
        }
    }

    private void checkNumberRuleExtExist(MesNumberRuleExt numberRuleExt, Long id) {
        DdlPackBean packBean = new DdlPackBean();
        DdlPreparedPack.getNumEqualPack(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), MesExtConstWords.IS_DELETED, packBean);
        DdlPreparedPack.getStringEqualPack(numberRuleExt.getOrganizeCode(), MesExtConstWords.ORGANIZE_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(numberRuleExt.getPrefix(), MesExtConstWords.PREFIX, packBean);
        DdlPreparedPack.getStringEqualPack(numberRuleExt.getNumberRule(), MesExtConstWords.NUMBER_RULE, packBean);
        MesNumberRuleExt numberRuleDb = numberRuleExtRepository.getByProperty(packBean);
        if (null != numberRuleDb && (StringUtils.isEmpty(id) || id.compareTo(numberRuleDb.getId()) != 0)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("前缀为[%s],编码规则为[%s]的记录已存在", numberRuleExt.getPrefix(), numberRuleExt.getNumberRule())
                    .build();
        }
    }

    @Override
    public Map<String, String> checkEpNumberRuleValid(MesNumberRuleExt numberRuleExt){
        //校验规则
        Map<String, String> checkMap = new HashMap<>();
        if (!GenSerialNoUtil.isMatch(numberRuleExt.getNumberRule())) {
            checkMap.put("success", "false");
            checkMap.put("msg", "编码规则格式有误");
            return checkMap;
        }
        if (!numberRuleExt.getNumberRule().substring(0, 1).equals("{") ||
                !numberRuleExt.getNumberRule().substring(numberRuleExt.getNumberRule().length() - 1).equals("}")) {
            checkMap.put("success", "false");
            checkMap.put("msg", "编码规则格式有误");
            return checkMap;
        }
        String[] numberRuleArr = numberRuleExt.getNumberRule().replaceAll("\\{", "").split("}");
        String[] paramArr = {"PREFIX", "PARTNO", "CUSTPARTNO", "SERIALNUMBER", "PRODLOCATION", "CUSTCODE",
                "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND", "SERIALNO", "CATEGORYCODE3", "PARTNOAFTERFOUR",
                "CUSTPRODLINE", "PROCESS_CODE", "PRODCFGTYPECODE", "VERSIONNO", "COLORCODE", "COLORNAME", "SPILTRULE", "DYNAMICRULE", "SUPPLIERRULE", "L", "N", "P", "J", "SERIALNO2"};
        List<String> params = new ArrayList<>(Arrays.asList(paramArr));
        if (!StringUtils.isEmpty(numberRuleExt.getSpiltRule())) {
            List<String> spiltRules = new ArrayList<>(Arrays.asList(numberRuleExt.getSpiltRule().contains(",") ?
                    numberRuleExt.getSpiltRule().split(",") : new String[]{numberRuleExt.getSpiltRule()}));
            params.addAll(spiltRules);
        }
        for (int i = 0, len = numberRuleArr.length; i < len; i++) {
            if (!params.contains(numberRuleArr[i].toUpperCase())) {
                checkMap.put("success", "false");
                checkMap.put("msg", "编码规则格式有误");
                return checkMap;
            }
        }
        checkMap.put("success", "true");
        checkMap.put("msg", "有效");
        return checkMap;
    }

    @Override
    public MesNumberRuleExt updateNumberRule(MesNumberRuleExt numberRuleExt) {
        //对id做有效性校验
        MesNumberRuleExt numberRuleDb = numberRuleExtRepository.getById(numberRuleExt.getId());
        if (numberRuleDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("规则代码为[%s]的记录不存在", numberRuleExt.getRuleCode())
                    .build();
        }

        //校验条码规则
        Map<String, String> checkMap = checkEpNumberRuleValid(numberRuleExt);
        if (checkMap.get(MesExtConstWords.success).equals(MesExtConstWords.FALSE)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.PARAMETER_EXCEPTION.getCode())
                    .setErrorDetail(checkMap.get(MesExtConstWords.MSG))
                    .build();
        }

        checkRuleLengthSpilt(numberRuleExt);

//        checkNumberRuleExtExist(numberRuleExt, numberRuleExt.getId());

        numberRuleDb.setRuleDesc(numberRuleExt.getRuleDesc());
        numberRuleDb.setPrefix(numberRuleExt.getPrefix());
        numberRuleDb.setNumberRule(numberRuleExt.getNumberRule());
        numberRuleDb.setSerialnoLength(numberRuleExt.getSerialnoLength());
        numberRuleDb.setSerialnoIncrement(numberRuleExt.getSerialnoIncrement());
        numberRuleDb.setIsCycle(numberRuleExt.getIsCycle());
        numberRuleDb.setSpiltRule(numberRuleExt.getSpiltRule());
        numberRuleDb.setBeginVal(numberRuleExt.getBeginVal());
        numberRuleDb.setEndVal(numberRuleExt.getEndVal());
        numberRuleDb.setImplClass(numberRuleExt.getImplClass());
        numberRuleDb.setMethodName(numberRuleExt.getMethodName());
        numberRuleDb.setRuleLengthSpilt(numberRuleExt.getRuleLengthSpilt());
        ConvertBean.serviceModelUpdate(numberRuleDb, numberRuleExt.getModifyUser());
        new ConvertBeanExt(numberRuleDb).convertBean(numberRuleDb);
        return numberRuleExtRepository.save(numberRuleDb);
    }
}
