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

import cn.estsh.i3plus.ext.mes.api.base.INumberRuleExtService;
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.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.mes.apiservice.serviceimpl.base.NumberRuleService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class NumberRuleExtService implements INumberRuleExtService {

    @Autowired
    private MesNumberRuleExtRepository numberRuleExtRepository;

    @Autowired
    private NumberRuleService numberRuleService;

    @Override
    public ListPager<MesNumberRuleExt> queryNumberRuleByPager(MesNumberRuleExt numberRuleExt, Pager pager) {
        DdlPackBean hqlPack = MesExtHqlPack.getMesNumberRuleExt(numberRuleExt);
        pager = PagerHelper.getPager(pager, numberRuleExtRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(numberRuleExt.orderBy());
        return new ListPager(numberRuleExtRepository.findByHqlWherePage(hqlPack, pager), pager);
    }

    @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 = numberRuleService.checkNumberRuleValid(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 {
                    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);
        DdlPreparedPack.getStringEqualPack(numberRuleExt.getSpiltRule(), MesExtConstWords.SPILT_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 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 = numberRuleService.checkNumberRuleValid(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);
    }


    @Override
    public int updateNumberRuleValidById(Long id, Integer status, String userName) {
        if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("启用，禁用枚举状态值[%s]未被定义", status)
                    .build();
        }
        return numberRuleExtRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, userName, TimeTool.getNowTime(true)});
    }

    @Override
    public List<MesNumberRuleExt> queryNumberRuleAll(MesNumberRuleExt numberRuleExt) {
        return numberRuleExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{numberRuleExt.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
    }

    @Override
    public MesNumberRuleExt getNumberRule(MesNumberRuleExt numberRuleExt) {
        return numberRuleExtRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.RULE_CODE },
                new Object[]{numberRuleExt.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), numberRuleExt.getRuleCode()});
    }
}
