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

import cn.estsh.i3plus.ext.mes.api.base.ep.IEpEquipmentCheckService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEpEquipmentCheck;
import cn.estsh.i3plus.ext.mes.pojo.model.ep.EpEquipmentCheckModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesEpEquipmentCheckRepository;
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.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-13 10:16
 */
@Service
public class EpEquipmentCheckService implements IEpEquipmentCheckService {

    @Autowired
    private MesEpEquipmentCheckRepository epEquipmentCheckRepository;

    private static final String ONE =  "1";
    private static final String TWO =  "2";
    private static final String THREE =  "3";
    private static final String FOUR =  "4";

    @Override
    public MesEpEquipmentCheck insert(MesEpEquipmentCheck epEquipmentCheck) {
        if(epEquipmentCheck.getResultType() == MesExtEnumUtil.EP_EQUIPMENT_CHECK_RESULT_TYPE.COMPARE_TYPE.getValue()){
            try{
                //标准值
                Double standardValue = null;

                //上限值
                Double upLimit = null;

                //下限值
                Double downLimit = null;
                if(!StringUtils.isEmpty(epEquipmentCheck.getStandardValue())){
                    standardValue =  Double.valueOf(epEquipmentCheck.getStandardValue());
                    String[] standard = epEquipmentCheck.getStandardValue().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 2) {
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "最多两位小数");
                    }
                }

                if(!StringUtils.isEmpty(epEquipmentCheck.getUpLimit())){
                    upLimit =  Double.valueOf(epEquipmentCheck.getUpLimit());
                    String[] standard = epEquipmentCheck.getUpLimit().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 2) {
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "最多两位小数");
                    }
                }

                if(!StringUtils.isEmpty(epEquipmentCheck.getDownLimit())){
                    downLimit =  Double.valueOf(epEquipmentCheck.getDownLimit());
                    String[] standard = epEquipmentCheck.getDownLimit().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 2) {
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "最多两位小数");
                    }
                }

                String computeType = null;
                if( downLimit != null && upLimit != null && standardValue != null){
                    computeType = ONE;
                }else if(downLimit != null && standardValue != null){
                    computeType = TWO;
                }else if(upLimit != null && standardValue != null){
                    computeType = THREE;
                }else if(downLimit != null && upLimit != null){
                    computeType = FOUR;
                }

                switch (computeType){
                    case ONE:
                        if(downLimit > standardValue || standardValue > upLimit || downLimit > upLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "比值范围输入不合理");
                        }
                        break;
                    case TWO:
                        if(standardValue < downLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "标准值小于下限值");
                        }
                        break;
                    case THREE:
                        if(standardValue > upLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "标准值大于上限值");
                        }
                        break;
                    case FOUR:
                        if(downLimit > upLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "上限值小于下限值");
                        }
                }

            }catch (Exception e){
                throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "不符合结果类型对应的请求参数类型");
            }
        }

        MesEpEquipmentCheck epEquipmentCheckTemp = epEquipmentCheckRepository.getByProperty(
                new String[]{MesExtConstWords.WORK_CENTER_CODE, MesExtConstWords.WORK_CELL_CODE, MesExtConstWords.EQU_NO, MesExtConstWords.PROJECT_CONTENT, MesExtConstWords.CHECK_METHOD, MesExtConstWords.CHECK_TYPE},
                new Object[]{epEquipmentCheck.getWorkCenterCode(), epEquipmentCheck.getWorkCellCode(), epEquipmentCheck.getEquNo(), epEquipmentCheck.getProjectContent(), epEquipmentCheck.getCheckMethod(), epEquipmentCheck.getCheckType()});
        if(epEquipmentCheckTemp != null){
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode(), "数据已存在");
        }

        ConvertBean.modelInitialize(epEquipmentCheck, AuthUtil.getSessionUser());
        epEquipmentCheck.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
        epEquipmentCheck.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        return epEquipmentCheckRepository.insert(epEquipmentCheck);
    }

    @Override
    public MesEpEquipmentCheck update(MesEpEquipmentCheck epEquipmentCheck) {
        //1、判断设备点检项目是否存在
        Long id = epEquipmentCheck.getId();
        MesEpEquipmentCheck equipmentCheck = epEquipmentCheckRepository.getById(id);
        if(ObjectUtils.isEmpty(equipmentCheck)){
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "自动配置不存在");
        }

        if(epEquipmentCheck.getResultType() == MesExtEnumUtil.EP_EQUIPMENT_CHECK_RESULT_TYPE.COMPARE_TYPE.getValue()){
            try{
                //标准值
                Double standardValue = null;

                //上限值
                Double upLimit = null;

                //下限值
                Double downLimit = null;
                if(!StringUtils.isEmpty(epEquipmentCheck.getStandardValue())){
                    standardValue =  Double.valueOf(epEquipmentCheck.getStandardValue());
                    String[] standard = epEquipmentCheck.getStandardValue().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 2) {
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "最多两位小数");
                    }
                }

                if(!StringUtils.isEmpty(epEquipmentCheck.getUpLimit())){
                    upLimit = Double.valueOf(epEquipmentCheck.getUpLimit());
                    String[] standard = epEquipmentCheck.getUpLimit().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 2) {
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "最多两位小数");
                    }
                }

                if(!StringUtils.isEmpty(epEquipmentCheck.getDownLimit())){
                    downLimit = Double.valueOf(epEquipmentCheck.getDownLimit());
                    String[] standard = epEquipmentCheck.getDownLimit().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != standard && standard.length == 2 && standard[1].length() > 2) {
                        throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "最多两位小数");
                    }
                }

                String computeType = null;
                if( downLimit != null && upLimit != null && standardValue != null){
                    computeType = ONE;
                }else if(downLimit != null && standardValue != null){
                    computeType = TWO;
                }else if(upLimit != null && standardValue != null){
                    computeType = THREE;
                }else if(downLimit != null && upLimit != null){
                    computeType = FOUR;
                }

                switch (computeType){
                    case ONE:
                        if(downLimit > standardValue || standardValue > upLimit || downLimit > upLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "比值范围输入不合理");
                        }
                        break;
                    case TWO:
                        if(standardValue < downLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "标准值小于下限值");
                        }
                        break;
                    case THREE:
                        if(standardValue > upLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "标准值大于上限值");
                        }
                        break;
                    case FOUR:
                        if(downLimit > upLimit){
                            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION.getCode(), "上限值小于下限值");
                        }
                }

            }catch (Exception e){
                throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.PARAMETER_EXCEPTION.getCode(), "不符合结果类型对应的请求参数类型");
            }
        }

        //2、复制Bean
        BeanUtils.copyProperties(epEquipmentCheck,equipmentCheck,MesExtConstWords.ID,MesExtConstWords.MODIFY_DATE_TIME);
        ConvertBean.modelUpdate(epEquipmentCheck,AuthUtil.getSessionUser());
        equipmentCheck.setOrganizeCode(AuthUtil.getOrganizeCode());
        equipmentCheck.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        return epEquipmentCheckRepository.save(equipmentCheck);
    }

    @Override
    public ListPager queryByPager(MesEpEquipmentCheck epEquipmentCheck, Pager pager) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(epEquipmentCheck.getWorkCenterCode(),MesExtConstWords.WORK_CENTER_CODE,packBean);
        DdlPreparedPack.getStringEqualPack(epEquipmentCheck.getEquNo(),MesExtConstWords.EQU_NO,packBean);
        DdlPreparedPack.getNumEqualPack(epEquipmentCheck.getIsValid(),MesExtConstWords.IS_VALID,packBean);
        DdlPreparedPack.getStringEqualPack(epEquipmentCheck.getWorkCellCode(),MesExtConstWords.WORK_CELL_CODE,packBean);
        pager = PagerHelper.getPager(pager, epEquipmentCheckRepository.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(" order by modifyDatetime desc  ");
        List<MesEpEquipmentCheck> epEquipmentChecks = epEquipmentCheckRepository.findByHqlWherePage(packBean, pager);
        List<EpEquipmentCheckModel> epEquipmentCheckModels = new ArrayList<>();
        Iterator<MesEpEquipmentCheck> checkIterator = epEquipmentChecks.iterator();

        while (checkIterator.hasNext()){
            EpEquipmentCheckModel epEquipmentCheckModel = new EpEquipmentCheckModel();
            MesEpEquipmentCheck equipmentCheck = checkIterator.next();
            BeanUtils.copyProperties(equipmentCheck,epEquipmentCheckModel);

            if(StringUtils.isEmpty(epEquipmentCheckModel.getResultType())){
                throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "结果类型输入不正确");
            }
            epEquipmentCheckModel.setResultTypeName(MesExtEnumUtil.EP_EQUIPMENT_CHECK_RESULT_TYPE.valueOfDescription(equipmentCheck.getResultType()));

            if(StringUtils.isEmpty(epEquipmentCheckModel.getCheckType())){
                throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "点检类型输入不正确");
            }
            epEquipmentCheckModel.setCheckTypeName(MesExtEnumUtil.MES_EQUIPMENT_CHECK_TYPE.valueOfDescription(equipmentCheck.getCheckType()));
            epEquipmentCheckModels.add(epEquipmentCheckModel);
        }

        return new ListPager(epEquipmentCheckModels, pager);
    }

    @Override
    public int updateIsValidById(long id, Integer status) {
        //1、判断单据是否存在
        MesEpEquipmentCheck epEquipmentCheck = epEquipmentCheckRepository.getById(id);
        if(ObjectUtils.isEmpty(epEquipmentCheck)){
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "设备点检项目不存在");
        }

        return epEquipmentCheckRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.SYSTEM_SYNC_STATUS },
                new Object[]{status, AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true), MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue()});
    }

    /**
     * 异常
     * @param softTypeCode 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();
    }
}
