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

import cn.estsh.i3plus.ext.mes.api.base.ISpeParamService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesSpeParam;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesSpeParamResult;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkCenterExt;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesSpeParamRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesSpeParamResultRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkCenterExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkOrderExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.mes.apiservice.util.DateUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
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.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.List;
import java.util.stream.Collectors;

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

    @Autowired
    private MesSpeParamRepository speParamRepository;

    @Autowired
    private MesSpeParamResultRepository speParamResultRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterRepository;

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    /**
     * 新增
     *
     * @param speParam
     * @return
     */
    @Override
    public MesSpeParam insert(MesSpeParam speParam) {
        ConvertBean.modelInitialize(speParam, AuthUtil.getSessionUser());
        speParam.setParamStatus(MesExtEnumUtil.CONFIRM_TYPE.NO.getValue());
        return speParamRepository.insert(speParam);
    }

    /**
     * 修改
     *
     * @param speParam
     * @return
     */
    @Override
    public void update(MesSpeParam speParam) {
        //1、判断单据是否存在
        Long id = speParam.getId();
        MesSpeParam speParam2 = speParamRepository.getById(id);
        if (ObjectUtils.isEmpty(speParam2)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "数据不存在");
        }
        BeanUtils.copyProperties(speParam, speParam2);
        ConvertBean.serviceModelUpdate(speParam2, AuthUtil.getSessionUser().getUserName());
        speParamRepository.update(speParam2);

    }

    /**
     * 查询
     *
     * @param speParam
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesSpeParam> queryByPager(MesSpeParam speParam, Pager pager) {

        String workCenterCode = speParam.getWorkCenterCode();

        String workCellCode = speParam.getWorkCellCode();
        String equNo = speParam.getEquNo();
        Integer isQualityConfirm = speParam.getIsQualityConfirm();
        Integer isTeamConfirm = speParam.getIsTeamConfirm();
        String createDateTimeStart = speParam.getCreateDateTimeStart();
        String createDateTimeEnd = speParam.getCreateDateTimeEnd();
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(speParam.getIsValid(), "isValid", packBean);
        DdlPreparedPack.getNumEqualPack(isQualityConfirm, "isQualityConfirm", packBean);
        DdlPreparedPack.getNumEqualPack(isTeamConfirm, "isTeamConfirm", packBean);
        DdlPreparedPack.getStringEqualPack(workCellCode, "workCellCode", packBean);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(equNo, "equNo", packBean);
        DdlPreparedPack.timeBuilder(createDateTimeStart, createDateTimeEnd, "createDatetime", packBean, true);


        pager = PagerHelper.getPager(pager, speParamRepository.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(" order by modifyDatetime desc ");
        List<MesSpeParam> speParamList = speParamRepository.findByHqlWherePage(packBean, pager);
        if (!CollectionUtils.isEmpty(speParamList)) {
            for (MesSpeParam detail : speParamList) {
                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()));
                }
                Long rId = detail.getSpeParamResultId();
                if (rId != 0 && rId != null) {
                    MesSpeParamResult paramResultById = speParamResultRepository.getById(rId);
                    detail.setResult1(paramResultById.getResult1());
                    detail.setResult2(paramResultById.getResult2());
                    detail.setResult3(paramResultById.getResult3());
                    detail.setResult4(paramResultById.getResult4());
                    detail.setResult5(paramResultById.getResult5());
                    detail.setResult6(paramResultById.getResult6());
                    detail.setResult7(paramResultById.getResult7());
                    detail.setResult8(paramResultById.getResult8());
                    detail.setResult9(paramResultById.getResult9());
                    detail.setResult10(paramResultById.getResult10());
                }
            }
        }
        return new ListPager(speParamList, pager);
    }

    private MesWorkCenterExt getWorkCenter(String workCenterCode, String organizeCode) {
        return workCenterRepository.getByProperty(
                new String[]{"workCenterCode", "organizeCode", "isValid", "isDeleted"},
                new Object[]{workCenterCode, organizeCode,
                        CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        CommonEnumUtil.IS_DEAL.NO.getValue()});
    }


    @Override
    public List<String> queryCell(String workCenterCode, String organizeCode) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", packBean);
        List<MesSpeParam> details = speParamRepository.findByHqlWhere(packBean);
        return details.stream().map(MesSpeParam::getWorkCellCode).distinct().collect(Collectors.toList());
    }

    @Override
    public List<String> queryParamNo(String workCenterCode, String organizeCode, String workCellCode) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(workCellCode, "workCellCode", packBean);
        List<MesSpeParam> details = speParamRepository.findByHqlWhere(packBean);
        return details.stream().map(MesSpeParam::getParamNo).distinct().collect(Collectors.toList());
    }

    @Override
    public List<MesWorkOrderExt> queryWorkOrder(String workCenterCode, String organizeCode) {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue(), "workOrderStatus", ddlPackBean);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", ddlPackBean);
        ddlPackBean.setOrderByStr(" order by seq desc ");
        return workOrderExtRepository.findByHqlWhere(ddlPackBean);

    }


    @Override
    public void updateShiftGroupCheck(List<MesSpeParam> details) {
        for (MesSpeParam detail : details) {
            MesSpeParam equDetail = speParamRepository.getById(detail.getId());
            if (equDetail == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("当前任务明细数据不存在")
                        .build();
            }

            if (detail.getIsTeamConfirm() == MesExtEnumUtil.SHIFT_GROUP_CHECK.YES.getValue()) {
                equDetail.setTeamConfirmUser(AuthUtil.getSessionUser().getUserName());
                equDetail.setTeamConfirmTime(DateUtil.formatDate());
                equDetail.setIsTeamConfirm(detail.getIsTeamConfirm());
                ConvertBean.serviceModelUpdate(equDetail, equDetail.getTeamConfirmUser());
            }
            speParamRepository.save(equDetail);
        }
    }

    @Override
    public void updateQualityCheck(List<MesSpeParam> details) {
        for (MesSpeParam detail : details) {
            MesSpeParam equDetail = speParamRepository.getById(detail.getId());
            if (equDetail == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("当前任务明细数据不存在")
                        .build();
            }

            if (detail.getIsQualityConfirm() == MesExtEnumUtil.QUALITY_CHECK.YES.getValue()) {
                equDetail.setQualityConfirmUser(AuthUtil.getSessionUser().getUserName());
                equDetail.setQualityConfirmTime(DateUtil.formatDate());
                equDetail.setIsQualityConfirm(detail.getIsQualityConfirm());
                ConvertBean.serviceModelUpdate(equDetail, equDetail.getQualityConfirmUser());
            }

            speParamRepository.save(equDetail);
        }
    }


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