package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.jx;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.jx.ITorqueManageCheckService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOrderJob;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProcessTorqueManageTaskDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOrderJobRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProcessTorqueManageTaskDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
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.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/02/05 13:52
 * @Description:
 **/
@Service
public class TorqueManageCheckDetailService implements ITorqueManageCheckService {
    @Autowired
    private MesProcessTorqueManageTaskDetailRepository torqueManageTaskDetailRepository;
    @Autowired
    private MesOrderJobRepository mesOrderJobRDao;
    @Autowired
    private MesWorkCellRepository mesWorkCellRDao;

    @Override
    public ListPager<MesProcessTorqueManageTaskDetail> queryTorqueManageCheckDetail(MesProcessTorqueManageTaskDetail personCheckDetail, Pager pager) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(personCheckDetail.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(personCheckDetail.getOrderJobNo(), MesPcnExtConstWords.ORDER_JOB_NO, packBean);
        DdlPreparedPack.getNumEqualPack(personCheckDetail.getIsValid(), MesPcnExtConstWords.IS_VALID, packBean);
        DdlPreparedPack.getStringEqualPack(personCheckDetail.getWorkCenterCode(), MesPcnExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(personCheckDetail.getWorkCellCode(), MesPcnExtConstWords.WORK_CELL_CODE, packBean);
        pager = PagerHelper.getPager(pager, torqueManageTaskDetailRepository.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(" order by processCode ");
        List<MesProcessTorqueManageTaskDetail> torqueManageTaskDetailList = torqueManageTaskDetailRepository.findByHqlWherePage(packBean, pager);
        for (MesProcessTorqueManageTaskDetail mesProcessTorqueManageTaskDetail : torqueManageTaskDetailList) {
            if (!StringUtils.isEmpty(mesProcessTorqueManageTaskDetail.getTorqueSpecValue())) {
                mesProcessTorqueManageTaskDetail.setTorqueSpecValueList(Arrays.stream(mesProcessTorqueManageTaskDetail.getTorqueSpecValue().split(MesPcnExtConstWords.COMMA)).collect(Collectors.toList()));
            }
        }
        return new ListPager(torqueManageTaskDetailList, pager);
    }

    @Override
    public void updateTorqueManageCheckDetail(MesProcessTorqueManageTaskDetail torqueManageTaskDetail) {
        MesProcessTorqueManageTaskDetail torqueManageTaskDetailDb = torqueManageTaskDetailRepository.getById(torqueManageTaskDetail.getId());
        if (null == torqueManageTaskDetailDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("该条数据不存在")
                    .build();
        }

        // 前端未判断点检结果则后端进行判断
        if ((torqueManageTaskDetail.getCheckResult() == null || torqueManageTaskDetail.getCheckResult() == 0) && "该项不需要点检".equals(torqueManageTaskDetail.getRemark())) {
            // 未维护上下限的情况
            if (!StringUtils.isEmpty(torqueManageTaskDetail.getUpLimit()) && !StringUtils.isEmpty(torqueManageTaskDetail.getDownLimit())) {

                if (StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue1()) ||
                        StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue2()) ||
                        StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue3()) ||
                        StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue4()) ||
                        StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue5()) ||
                        torqueManageTaskDetail.getRotationNoAbnormal() == null ||
                        torqueManageTaskDetail.getRotationNoAbnormal() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue() ||
                        torqueManageTaskDetail.getFasteningNoAbnormal() == null ||
                        torqueManageTaskDetail.getFasteningNoAbnormal() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue() ||
                        torqueManageTaskDetail.getFasteningIsStc() == null ||
                        torqueManageTaskDetail.getFasteningIsStc() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue() ||
                        torqueManageTaskDetail.getToolHeadNoWear() == null ||
                        torqueManageTaskDetail.getToolHeadNoWear() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue()
                ) torqueManageTaskDetailDb.setCheckResult(MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue());

                else {

                    Double upLimitDouble = Double.parseDouble(torqueManageTaskDetail.getUpLimit());
                    Double downLimitDouble = Double.parseDouble(torqueManageTaskDetail.getDownLimit());

                    boolean isNG = false;
                    if (checkValue(torqueManageTaskDetail.getTorqueValue1(), upLimitDouble, downLimitDouble)) isNG = true;
                    else if (checkValue(torqueManageTaskDetail.getTorqueValue2(), upLimitDouble, downLimitDouble)) isNG = true;
                    else if (checkValue(torqueManageTaskDetail.getTorqueValue3(), upLimitDouble, downLimitDouble)) isNG = true;
                    else if (checkValue(torqueManageTaskDetail.getTorqueValue4(), upLimitDouble, downLimitDouble)) isNG = true;
                    else if (checkValue(torqueManageTaskDetail.getTorqueValue5(), upLimitDouble, downLimitDouble)) isNG = true;

                    if (isNG)  torqueManageTaskDetailDb.setCheckResult(MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue());
                    else torqueManageTaskDetailDb.setCheckResult(MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.OK.getValue());

                }

            } else {
                // 未维护上下限的情况 不判断扭矩值1-5
                if (torqueManageTaskDetail.getRotationNoAbnormal() == null ||
                        torqueManageTaskDetail.getRotationNoAbnormal() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue() ||
                        torqueManageTaskDetail.getFasteningNoAbnormal() == null ||
                        torqueManageTaskDetail.getFasteningNoAbnormal() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue() ||
                        torqueManageTaskDetail.getFasteningIsStc() == null ||
                        torqueManageTaskDetail.getFasteningIsStc() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue() ||
                        torqueManageTaskDetail.getToolHeadNoWear() == null ||
                        torqueManageTaskDetail.getToolHeadNoWear() == MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue()
                ) torqueManageTaskDetailDb.setCheckResult(MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.NG.getValue());

                else torqueManageTaskDetailDb.setCheckResult(MesPcnExtEnumUtil.TORQUE_MANAGE_CHECK_RESULT.OK.getValue());
            }
        }

        if("该项不需要点检".equals(torqueManageTaskDetail.getRemark())) torqueManageTaskDetailDb.setCheckResult(MesPcnExtEnumUtil.CHECK_RESULT.OK.getValue());

        torqueManageTaskDetailDb.setCheckTime(TimeTool.getNowTime(true));
        torqueManageTaskDetailDb.setCheckUser(torqueManageTaskDetail.getModifyUser());
        torqueManageTaskDetailDb.setRotationNoAbnormal(torqueManageTaskDetail.getRotationNoAbnormal());
        torqueManageTaskDetailDb.setFasteningNoAbnormal(torqueManageTaskDetail.getFasteningNoAbnormal());
        torqueManageTaskDetailDb.setFasteningIsStc(torqueManageTaskDetail.getFasteningIsStc());
        torqueManageTaskDetailDb.setToolHeadNoWear(torqueManageTaskDetail.getToolHeadNoWear());
        torqueManageTaskDetailDb.setScrewdriverNo(torqueManageTaskDetail.getScrewdriverNo());
        if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue1())) torqueManageTaskDetailDb.setTorqueValue1(torqueManageTaskDetail.getTorqueValue1());
        if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue2())) torqueManageTaskDetailDb.setTorqueValue2(torqueManageTaskDetail.getTorqueValue2());
        if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue3())) torqueManageTaskDetailDb.setTorqueValue3(torqueManageTaskDetail.getTorqueValue3());
        if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue4())) torqueManageTaskDetailDb.setTorqueValue4(torqueManageTaskDetail.getTorqueValue4());
        if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueValue5())) torqueManageTaskDetailDb.setTorqueValue5(torqueManageTaskDetail.getTorqueValue5());
        torqueManageTaskDetailDb.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        torqueManageTaskDetailDb.setCheckResult(torqueManageTaskDetail.getCheckResult());
        torqueManageTaskDetailDb.setRemark(torqueManageTaskDetail.getRemark());
        ConvertBean.serviceModelUpdate(torqueManageTaskDetailDb, torqueManageTaskDetail.getModifyUser());
        torqueManageTaskDetailRepository.save(torqueManageTaskDetailDb);

        //单据主表状态改为点检中
        updateOrderJobStatus(torqueManageTaskDetail);
    }

    private boolean checkValue(String checkValue, Double upLimit, Double dowmLimit) {

        Double torqueValueDouble = Double.parseDouble(checkValue);

        if (torqueValueDouble > upLimit || torqueValueDouble < dowmLimit) {
            return true;
        }
        return false;
    }

    @Override
    public void updateTopTorqueManageCheckDetail(MesProcessTorqueManageTaskDetail torqueManageTaskDetail) {

        torqueManageTaskDetailRepository.updateByProperties(new String[]{MesPcnExtConstWords.ORDER_JOB_NO}, new Object[]{torqueManageTaskDetail.getOrderJobNo()},
                new String[]{MesPcnExtConstWords.SYSTEM_SYNC_STATUS, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME, MesPcnExtConstWords.TORQUE_MANAGE_NO1, MesPcnExtConstWords.TORQUE_MANAGE_NO2, MesPcnExtConstWords.TORQUE_MANAGE_NO3, MesPcnExtConstWords.TORQUE_SPEC_VALUE},
                new Object[]{MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue(), AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true), torqueManageTaskDetail.getTorqueManageNo1(), torqueManageTaskDetail.getTorqueManageNo2(), torqueManageTaskDetail.getTorqueManageNo3(), torqueManageTaskDetail.getTorqueSpecValue()});
    }

    private void updateOrderJobStatus(MesProcessTorqueManageTaskDetail torqueManageTaskDetail) {
        //单据主表状态改为点检中
        MesOrderJob mesOrderJob = mesOrderJobRDao.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.ORDER_NO},
                new Object[]{torqueManageTaskDetail.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),
                        MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue(), torqueManageTaskDetail.getOrderJobNo()});
        if (mesOrderJob.getOrderStatus() == MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue()) {
            mesOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue());
            mesOrderJob.setComplateTime(TimeTool.getNowTime(true));
            ConvertBean.serviceModelUpdate(mesOrderJob, torqueManageTaskDetail.getModifyUser());
            mesOrderJobRDao.save(mesOrderJob);
        }
    }

    @Override
    public List<MesWorkCell> queryCellByOrderNo(String orderNo, String organizeCode) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, MesPcnExtConstWords.ORDER_JOB_NO, packBean);
        List<MesProcessTorqueManageTaskDetail> checkDetailList = torqueManageTaskDetailRepository.findByHqlWhere(packBean);
        List<String> centerList = checkDetailList.stream().map(MesProcessTorqueManageTaskDetail::getWorkCenterCode).collect(Collectors.toList());
        List<String> cellList = checkDetailList.stream().map(MesProcessTorqueManageTaskDetail::getWorkCellCode).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cellList)) {
            return null;
        }
        DdlPackBean cellPackBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getInPackList(cellList, MesPcnExtConstWords.WORK_CELL_CODE, cellPackBean);
        DdlPreparedPack.getInPackList(centerList, MesPcnExtConstWords.WORK_CENTER_CODE, cellPackBean);
        return mesWorkCellRDao.findByHqlWhere(cellPackBean);
    }
}
