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

import cn.estsh.i3plus.ext.mes.api.base.IFirstManageService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.IFirstOrderDetailDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesFirstOrderDetail;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesProcessFirstItem;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesFirstOrderDetailRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesProcessFirstItemRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
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.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.base.tool.HqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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.ArrayList;
import java.util.List;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/01/18 11:41 上午
 * @Description:
 **/
@Service
public class FirstManageService implements IFirstManageService {

    @Autowired
    private MesProcessFirstItemRepository mesProcessFirstItemRDao;

    @Autowired
    private IFirstOrderDetailDao firstOrderDetailDao;

    @Autowired
    private MesFirstOrderDetailRepository mesFirstOrderDetailRDao;

    @Override
    public MesProcessFirstItem insertMesProcessFirstItem(MesProcessFirstItem mesProcessFirstItem) {
        StringBuffer whereStr = new StringBuffer();
        HqlPack.getStringEqualPack(mesProcessFirstItem.getOrganizeCode(), MesExtConstWords.ORGANIZE_CODE, whereStr);
        HqlPack.getStringEqualPack(mesProcessFirstItem.getProcessCode(), MesExtConstWords.PROCESS_CODE, whereStr);
        HqlPack.getStringEqualPack(mesProcessFirstItem.getPartNo(), MesExtConstWords.PART_NO, whereStr);
        HqlPack.getStringEqualPack(mesProcessFirstItem.getCheckMessage(), MesExtConstWords.CHECK_MESSAGE, whereStr);
        if(!mesProcessFirstItem.getOrganizeCode().contains(MesExtConstWords.CK)){
            HqlPack.getStringEqualPack(mesProcessFirstItem.getCheckStand(), MesExtConstWords.CHECK_STAND, whereStr);
        }
        HqlPack.getNumEqualPack(CommonEnumUtil.IS_VAILD.VAILD.getValue(), MesExtConstWords.IS_VALID, whereStr);
        if (mesProcessFirstItemRDao.isExitByHqlWhere(whereStr.toString())) {
            if(!mesProcessFirstItem.getOrganizeCode().contains(MesExtConstWords.CK)){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("工序编号【%s】、物料编码【%s】和检测信息【%s】和检测标准【%s】在工序首检项目信息中已存在"
                                ,mesProcessFirstItem.getProcessCode(), mesProcessFirstItem.getPartNo(), mesProcessFirstItem.getCheckMessage(), mesProcessFirstItem.getCheckStand())
                        .setErrorSolution("请更换新增参数")
                        .build();
            }else{
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("工序编号【%s】、物料编码【%s】和检测信息【%s】和检测标准【%s】在工序首检项目信息中已存在"
                                ,mesProcessFirstItem.getProcessCode(), mesProcessFirstItem.getPartNo(), mesProcessFirstItem.getCheckMessage(), mesProcessFirstItem.getCheckStand())
                        .setErrorSolution("请更换新增参数")
                        .build();
            }
        }

        //上下限值校验
        if ((!StringUtils.isEmpty(mesProcessFirstItem.getUpLimit()) && StringUtils.isEmpty(mesProcessFirstItem.getDownLimit())) ||
                (StringUtils.isEmpty(mesProcessFirstItem.getUpLimit()) && !StringUtils.isEmpty(mesProcessFirstItem.getDownLimit()))){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("缺少上下限值,上下限值需同时填写")
                    .build();
        }

        //上限值
        Double upLimit = null;
        //下限值
        Double downLimit = null;

        if(!StringUtils.isEmpty(mesProcessFirstItem.getUpLimit())){
            upLimit =  Double.valueOf(mesProcessFirstItem.getUpLimit());
            String[] standard = mesProcessFirstItem.getUpLimit().split(MesExtConstWords.DECIMAL_POINT);
            if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("最多四位小数")
                        .build();
            }
        }

        if(!StringUtils.isEmpty(mesProcessFirstItem.getDownLimit())){
            downLimit =  Double.valueOf(mesProcessFirstItem.getDownLimit());
            String[] standard = mesProcessFirstItem.getDownLimit().split(MesExtConstWords.DECIMAL_POINT);
            if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("最多四位小数")
                        .build();
            }
        }

        if (!StringUtils.isEmpty(mesProcessFirstItem.getUpLimit()) && !StringUtils.isEmpty(mesProcessFirstItem.getDownLimit())){
            if (upLimit < downLimit){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("上限值不能小于下限值")
                        .build();
            }
        }

        ConvertBean.serviceModelInitialize(mesProcessFirstItem, AuthUtil.getSessionUser().getUserName());
        return mesProcessFirstItemRDao.insert(mesProcessFirstItem);
    }

    @Override
    public void updateMesProcessFirstItem(MesProcessFirstItem mesProcessFirstItem, String userName) {

        MesProcessFirstItem processFirstItemDb = mesProcessFirstItemRDao.getById(mesProcessFirstItem.getId());

        if(processFirstItemDb == null){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("数据不存在")
                    .build();
        }

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesProcessFirstItem.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesProcessFirstItem.getProcessCode(), MesExtConstWords.PROCESS_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(mesProcessFirstItem.getPartNo(), MesExtConstWords.PART_NO, packBean);
        DdlPreparedPack.getStringEqualPack(mesProcessFirstItem.getCheckMessage(), MesExtConstWords.CHECK_MESSAGE, packBean);
        DdlPreparedPack.getStringEqualPack(mesProcessFirstItem.getCheckStand(), MesExtConstWords.CHECK_STAND, packBean);
        MesProcessFirstItem processFirstItemExist = mesProcessFirstItemRDao.getByProperty(packBean);

        if (processFirstItemExist != null && processFirstItemExist.getId().compareTo(processFirstItemDb.getId()) != 0) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("工序编号【%s】、物料编码【%s】和检测信息【%s】和检测标准【%s】在工序首检项目信息中已存在"
                                ,mesProcessFirstItem.getProcessCode(), mesProcessFirstItem.getPartNo(), mesProcessFirstItem.getCheckMessage(), mesProcessFirstItem.getCheckStand())
                        .setErrorSolution("请更换修改参数")
                        .build();
        }

        //上下限值校验
        if ((!StringUtils.isEmpty(mesProcessFirstItem.getUpLimit()) && StringUtils.isEmpty(mesProcessFirstItem.getDownLimit())) ||
                (StringUtils.isEmpty(mesProcessFirstItem.getUpLimit()) && !StringUtils.isEmpty(mesProcessFirstItem.getDownLimit()))){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("缺少上下限值,上下限值需同时填写")
                    .build();
        }

        //上限值
        Double upLimit = null;
        //下限值
        Double downLimit = null;

        if(!StringUtils.isEmpty(mesProcessFirstItem.getUpLimit())){
            upLimit =  Double.valueOf(mesProcessFirstItem.getUpLimit());
            String[] standard = mesProcessFirstItem.getUpLimit().split(MesExtConstWords.DECIMAL_POINT);
            if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("最多四位小数")
                        .build();
            }
        }

        if(!StringUtils.isEmpty(mesProcessFirstItem.getDownLimit())){
            downLimit =  Double.valueOf(mesProcessFirstItem.getDownLimit());
            String[] standard = mesProcessFirstItem.getDownLimit().split(MesExtConstWords.DECIMAL_POINT);
            if (null != standard && standard.length == 2 && standard[1].length() > 4) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("最多四位小数")
                        .build();
            }
        }

        if (!StringUtils.isEmpty(mesProcessFirstItem.getUpLimit()) && !StringUtils.isEmpty(mesProcessFirstItem.getDownLimit())){
            if (upLimit < downLimit){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("上限值不能小于下限值")
                        .build();
            }
        }

        ConvertBean.serviceModelUpdate(mesProcessFirstItem, userName);
        mesProcessFirstItemRDao.save(mesProcessFirstItem);
    }

    @Override
    public ListPager<MesProcessFirstItem> queryMesProcessFirstItemByPager(MesProcessFirstItem mesProcessFirstItem, Pager pager) {
        if (mesProcessFirstItem == null) {
            pager = PagerHelper.getPager(pager, mesProcessFirstItemRDao.listCount());
            return new ListPager(mesProcessFirstItemRDao.listPager(pager), pager);
        } else {
            DdlPackBean hqlPack = MesExtHqlPack.getMesProcessFirstItem(mesProcessFirstItem);
            hqlPack.setOrderByStr(mesProcessFirstItem.orderBy());
            pager = PagerHelper.getPager(pager, mesProcessFirstItemRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(mesProcessFirstItemRDao.findByHqlWherePage(hqlPack , pager), pager);
        }
    }

    @Override
    public int updateMesProcessFirstItemStatus(String[] ids, int status, String userName) {
        StringBuffer wheres = new StringBuffer();
        HqlPack.getInPack(String.join(",", ids), MesExtConstWords.ID, wheres);

        int num = mesProcessFirstItemRDao.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, userName, TimeTool.getNowTime(true)}
        );
        return num;
    }

    @Override
    public ListPager<MesFirstOrderDetail> queryFirstOrderDetailReportByPager(MesFirstOrderDetail mesFirstOrderDetail, Pager pager) {
        Integer total = firstOrderDetailDao.getFirstOrderDetailReportCount(mesFirstOrderDetail);
        if(total == 0){
            return new ListPager(new ArrayList(), pager);
        }
        pager = PagerHelper.getPager(pager, total);
        List<MesFirstOrderDetail> firstOrderDetails = firstOrderDetailDao.queryFirstOrderDetailReportByPager(mesFirstOrderDetail, pager);
        if (!CollectionUtils.isEmpty(firstOrderDetails)) {
            for (MesFirstOrderDetail detail : firstOrderDetails) {
                if (null == detail) {
                    continue;
                }
                if (!StringUtils.isEmpty(detail.getIsTeamConfirm())) {
                    detail.setShiftGroupCheckName(MesExtEnumUtil.SHIFT_GROUP_CHECK.valueOfDescription(detail.getIsTeamConfirm()));
                }
                if (!StringUtils.isEmpty(detail.getIsQualityConfirm())) {
                    detail.setQualityCheckName(MesExtEnumUtil.QUALITY_CHECK.valueOfDescription(detail.getIsQualityConfirm()));
                }
                if (!StringUtils.isEmpty(detail.getCheckResult())) {
                    try {
                        detail.setCheckResultName(MesExtEnumUtil.CHECK_RESULT.valueOfDescription(Integer.valueOf(detail.getCheckResult())));
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }
        return new ListPager(firstOrderDetails, pager);
    }

    @Override
    public void updateMesFirstOrderDetailById(List<MesFirstOrderDetail> mesFirstOrderDetailList, String userName) {
        for(MesFirstOrderDetail mesFirstOrderDetail : mesFirstOrderDetailList){
            MesFirstOrderDetail firstOrderDetail = mesFirstOrderDetailRDao.getById(mesFirstOrderDetail.getId());
            if(firstOrderDetail == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("当前首检单明细数据不存在")
                        .build();
            }

            if (mesFirstOrderDetail.getIsTeamConfirm() == MesExtEnumUtil.CONFIRM_TYPE.YES.getValue()) {
                firstOrderDetail.setTeamConfirmUser(userName);
                firstOrderDetail.setTeamConfirmTime(TimeTool.getNowTime(true));
                firstOrderDetail.setIsTeamConfirm(mesFirstOrderDetail.getIsTeamConfirm());
                ConvertBean.serviceModelUpdate(firstOrderDetail, userName);
            } else {
                firstOrderDetail.setQualityConfirmUser(userName);
                firstOrderDetail.setQualityConfirmTime(TimeTool.getNowTime(true));
                firstOrderDetail.setIsQualityConfirm(mesFirstOrderDetail.getIsQualityConfirm());
                ConvertBean.serviceModelUpdate(firstOrderDetail, userName);
            }

            mesFirstOrderDetailRDao.save(firstOrderDetail);
        }
    }
}
