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

import bsh.StringUtil;
import cn.estsh.i3plus.ext.mes.api.base.IOrderRuleService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesOrderRule;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesOrderRuleRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
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.platform.common.util.MesConstWords;
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.i3plus.pojo.mes.sqlpack.MesHqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/01/15 9:34 上午
 * @Description:
 **/
@Service
public class OrderRuleService implements IOrderRuleService {
    public static final Logger logger = LoggerFactory.getLogger(OrderRuleService.class);

    @Autowired
    private MesOrderRuleRepository mesOrderRuleRDao;
    @Override
    public MesOrderRule insertOrderRule(MesOrderRule orderRule) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(orderRule.getCreateRule(), MesExtConstWords.CREATE_RULE, packBean);
        //校验唯一
        Integer createRule = orderRule.getCreateRule();
        if (createRule != MesExtEnumUtil.MES_OR_CREATE_RULE.TIME_TO_CREATE.getValue()) {
            checkUniqueOrderRule(orderRule, packBean);
        }
        orderRule.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
        ConvertBean.saveOrUpdate(orderRule, AuthUtil.getSessionUser().getUserName());
        return mesOrderRuleRDao.insert(orderRule);
    }
    @Override
    public MesOrderRule updateOrderRule(MesOrderRule orderRule) {
        //1、判断单据是否存在
        DdlPackBean packBeanValidateId= MesHqlPack.getMesAllData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(orderRule.getId(),MesExtConstWords.ID,packBeanValidateId);
        List<MesOrderRule> mesOrderRules= mesOrderRuleRDao.findByHqlWhere(packBeanValidateId);
        if(CollectionUtils.isEmpty(mesOrderRules)){
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "单据规则不存在");
        }

        ConvertBean.serviceModelUpdate(orderRule, AuthUtil.getSessionUser().getUserName());
        DdlPackBean packBean= MesHqlPack.getMesAllData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNotInPack(orderRule.getId(),MesExtConstWords.ID,packBean);
        DdlPreparedPack.getNumEqualPack(orderRule.getCreateRule(),MesExtConstWords.CREATE_RULE,packBean);
        checkUniqueOrderRule(orderRule,packBean);
        ConvertBean.saveOrUpdate(orderRule, AuthUtil.getSessionUser().getUserName());
        return mesOrderRuleRDao.save(orderRule);
    }

    @Override
    public ListPager<MesOrderRule> queryOrderRuleByPager(MesOrderRule orderRule, Pager pager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(orderRule.getIsValid(),MesExtConstWords.IS_VALID,packBean);
        DdlPreparedPack.getNumEqualPack(orderRule.getTaskType(),MesExtConstWords.TASK_TYPE,packBean);
        DdlPreparedPack.getNumEqualPack(orderRule.getOrderType(),MesExtConstWords.ORDER_TYPE,packBean);
        DdlPreparedPack.getNumEqualPack(orderRule.getCreateRule(),MesExtConstWords.CREATE_RULE,packBean);
        DdlPreparedPack.getStringEqualPack(orderRule.getWorkCenterCode(),MesExtConstWords.WORK_CENTER_CODE,packBean);
        DdlPreparedPack.getStringEqualPack(orderRule.getShiftCode(),MesExtConstWords.SHIFT_CODE,packBean);
        pager = PagerHelper.getPager(pager, mesOrderRuleRDao.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(orderRule.orderBy());
        return new ListPager(mesOrderRuleRDao.findByHqlWherePage(packBean, pager), pager);
    }

    @Override
    public int updateOrderRuleIsValidById(long id, Integer isValid) {
        //1、判断单据是否存在
        DdlPackBean packBeanValidateId= MesHqlPack.getAllBaseData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(id,MesExtConstWords.ID,packBeanValidateId);
        List<MesOrderRule> mesOrderRules= mesOrderRuleRDao.findByHqlWhere(packBeanValidateId);
        if(CollectionUtils.isEmpty(mesOrderRules)){
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "单据规则不存在");
        }
        return mesOrderRuleRDao.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{isValid, AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true)});
    }

    /**
     * 校验唯一性
     * @param orderRule
     * @param packBean
     */
    private void checkUniqueOrderRule(MesOrderRule orderRule,DdlPackBean packBean){
        //1、拼接查询条件
        if (orderRule.getWorkCenterCode() == null) {
            DdlPreparedPack.getIsNull(MesExtConstWords.WORK_CENTER_CODE, packBean);
        } else {
            DdlPreparedPack.getStringEqualPack(orderRule.getWorkCenterCode(), MesExtConstWords.WORK_CENTER_CODE, packBean);
        }
        if(orderRule.getShiftCode()==null){
            DdlPreparedPack.getIsNull(MesExtConstWords.SHIFT_CODE,packBean);
        }else{
            DdlPreparedPack.getStringEqualPack(orderRule.getShiftCode(),MesExtConstWords.SHIFT_CODE,packBean);
        }

        //如果单据类型为设备点检，增加点检类型的唯一性校验字段
        if (orderRule.getOrderType() == MesExtEnumUtil.MES_OR_ORDER_TYPE.EQU_CHECK.getValue()) {
            DdlPreparedPack.getStringEqualPack(orderRule.getCheckType(),MesExtConstWords.CHECK_TYPE,packBean);
        }

        //2、判断是否已存在
        List<MesOrderRule> mesOrderRules = mesOrderRuleRDao.findByHqlWhere(packBean);
        if (!CollectionUtils.isEmpty(mesOrderRules)){
            mesOrderRules.forEach(m->{
                if (m.getOrderType().equals(orderRule.getOrderType())) {
                    if(orderRule.getProduceTime().equals(m.getProduceTime())){
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode(), "该单据规则已存在");
                    }
                }
            });
        }
    }

    /**
     * 异常
     * @param softTypeCode
     * @param errorDetailString 错误消息字符串
     * @param imppExceptionEnumCode 异常代码
     * @param args 参数
     */
    private void throwImppException(String softTypeCode, String errorDetailString, String imppExceptionEnumCode, Object... args) {
        throw ImppExceptionBuilder.newInstance()
                .setSystemID(softTypeCode)
                .setErrorCode(imppExceptionEnumCode)
                .setErrorDetail(errorDetailString,args)
                .build();
    }
}
