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

import cn.estsh.i3plus.ext.mes.api.base.IFailCaseCheckService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesFailCaseCheck;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelFailCaseCheck;
import cn.estsh.i3plus.ext.mes.pojo.model.FailCaseCheckModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesFailCaseCheckRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.BaseImppException;
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.bean.MesProcess;
import cn.estsh.i3plus.pojo.mes.repository.MesProcessRepository;
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.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

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

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/2/2 15:19
 **/
@Service
public class FailCaseCheckService implements IFailCaseCheckService {

    @Autowired
    private MesFailCaseCheckRepository failCaseCheckRepository;
    @Autowired
    private MesPartExtRepository partExtRepository;
    @Autowired
    private MesProcessRepository processRepository;

    /**
     * 新增
     *
     * @param failCaseCheck
     * @return
     */
    @Override
    public MesFailCaseCheck insert(MesFailCaseCheck failCaseCheck) {
        ConvertBean.modelInitialize(failCaseCheck, AuthUtil.getSessionUser());
        failCaseCheck.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());

        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(AuthUtil.getOrganizeCode());
        if(failCaseCheck.getOrganizeCode().contains(MesExtConstWords.CK)){
            DdlPreparedPack.getStringEqualPack(failCaseCheck.getPartNo(), "partNo", ddlPackBean);
            DdlPreparedPack.getStringEqualPack(failCaseCheck.getProcessCode(), "processCode", ddlPackBean);
        }else{
            if(StringUtils.isEmpty(failCaseCheck.getBadContent()) || StringUtils.isEmpty(failCaseCheck.getStrategies())){
                throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "不良内容 或 对策数据为空");
            }
            DdlPreparedPack.getStringEqualPack(failCaseCheck.getPartNo(), "partNo", ddlPackBean);
            DdlPreparedPack.getStringEqualPack(failCaseCheck.getProcessCode(), "processCode", ddlPackBean);
            DdlPreparedPack.getStringEqualPack(failCaseCheck.getBadContent(), "badContent", ddlPackBean);
            DdlPreparedPack.getStringEqualPack(failCaseCheck.getStrategies(), "strategies", ddlPackBean);
        }

        MesFailCaseCheck MesFailCaseCheck = failCaseCheckRepository.getByProperty(ddlPackBean);
        if (!ObjectUtils.isEmpty(MesFailCaseCheck)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode(), "数据已存在");
        }

        return failCaseCheckRepository.insert(failCaseCheck);
    }

    /**
     * 修改
     *
     * @param failCaseCheck
     * @return
     */
    @Override
    public MesFailCaseCheck update(MesFailCaseCheck failCaseCheck) {
        //1、判断单据是否存在
        Long id = failCaseCheck.getId();
        MesFailCaseCheck failCaseCheck2 = failCaseCheckRepository.getById(id);
        if (ObjectUtils.isEmpty(failCaseCheck2)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "自动配置不存在");
        }

        BeanUtils.copyProperties(failCaseCheck, failCaseCheck2);
        ConvertBean.serviceModelUpdate(failCaseCheck2, AuthUtil.getSessionUser().getUserName());
        return failCaseCheckRepository.save(failCaseCheck2);
    }

    /**
     * 查询
     *
     * @param failCaseCheck
     * @param pager
     * @return
     */
    @Override
    public ListPager<FailCaseCheckModel> queryByPager(MesFailCaseCheck failCaseCheck, Pager pager) {
        List<FailCaseCheckModel> resultList = new ArrayList<>();
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(failCaseCheck.getIsValid(), MesExtConstWords.IS_VALID, packBean);
        DdlPreparedPack.getStringEqualPack(failCaseCheck.getPartNo(), MesExtConstWords.PART_NO, packBean);
        DdlPreparedPack.getStringLikerPack(failCaseCheck.getProcessCode(), MesExtConstWords.PROCESS_CODE, packBean);
        pager = PagerHelper.getPager(pager, failCaseCheckRepository.findByHqlWhereCount(packBean));
        List<MesFailCaseCheck> failCaseCheckList = failCaseCheckRepository.findByHqlWherePage(packBean, pager);
        if (!CollectionUtils.isEmpty(failCaseCheckList)) {
            for (MesFailCaseCheck item : failCaseCheckList) {
                if (null != item) {
                    FailCaseCheckModel result = new FailCaseCheckModel();
                    BeanUtils.copyProperties(item, result);
                    resultList.add(result);
                }
            }
        }
        return new ListPager(resultList, pager);
    }

    /**
     * 根据
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public int updateIsValidById(long id, Integer status) {
        //1、判断单据是否存在
        MesFailCaseCheck failCaseCheck = failCaseCheckRepository.getById(id);
        if (ObjectUtils.isEmpty(failCaseCheck)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "数据不存在");
        }

        return failCaseCheckRepository.updateByProperties(new String[]{"id"}, new Object[]{id},
                new String[]{MesConstWords.IS_VALID, "modifyUser", "modifyDatetime"},
                new Object[]{status, AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true)});
    }

    /**
     * 导入数据
     *
     * @param excelfailCaseChecks excel部分自动降落
     */
    @Override
    public void importData(List<ExcelFailCaseCheck> excelfailCaseChecks) {
        if (CollectionUtils.isEmpty(excelfailCaseChecks)) {
            throw new BaseImppException("导入数据为空");
        }
        Integer i = 2;
        for (ExcelFailCaseCheck excelfailCaseCheck : excelfailCaseChecks) {
            MesFailCaseCheck mesFailCaseCheck = new MesFailCaseCheck();
            BeanUtils.copyProperties(excelfailCaseCheck, mesFailCaseCheck);
            String organizeCode = AuthUtil.getOrganizeCode();
            //根据零件号查询零件信息
            MesPartExt mesPart = partExtRepository.getByProperty(
                    new String[]{"partNo", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{excelfailCaseCheck.getPartNo(), organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});

            if (mesPart == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的零件号【%s】在零件信息中不存在数据", i, excelfailCaseCheck.getPartNo())
                        .build();
            }

            //根据零件号查询零件信息
            MesProcess mesProcess = processRepository.getByProperty(
                    new String[]{"processCode", "organizeCode", "isValid", "isDeleted"},
                    new Object[]{excelfailCaseCheck.getProcessCode(), organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});

            if (mesProcess == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("第【%s】行的工序代码【%s】在工序信息中不存在数据", i, excelfailCaseCheck.getProcessCode())
                        .build();
            }
            ConvertBean.modelInitialize(mesFailCaseCheck, AuthUtil.getSessionUser());
            mesFailCaseCheck.setProcessName(mesProcess.getProcessName());
            failCaseCheckRepository.save(mesFailCaseCheck);
            i++;
        }
    }

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