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

import cn.estsh.i3plus.ext.mes.api.base.IAntiStaticCheckDetailService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAntiStaticCheckDetail;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesOrderJob;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesAntiStaticCheckDetailRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesOrderJobRepository;
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.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.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.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/2/5 15:42
 **/
@Service
public class AntiStaticCheckDetailService implements IAntiStaticCheckDetailService {

    @Autowired
    private MesAntiStaticCheckDetailRepository antiStaticCheckDetailRepository;

    @Autowired
    private MesOrderJobRepository jobRepository;

    /**
     * 查询
     *
     * @param detail
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesAntiStaticCheckDetail> queryByPager(MesAntiStaticCheckDetail detail, Pager pager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(detail.getWorkCellCode(), "workCellCode", packBean);
        List<Integer> statusList = Stream.of(MesExtEnumUtil.ANTI_CHECK_RESULT.QUALIFIED.getValue(), MesExtEnumUtil.ANTI_CHECK_RESULT.UN_QUALIFIED.getValue()).collect(Collectors.toList());
        DdlPreparedPack.getInPackList(statusList, "checkResult", packBean);
        DdlPreparedPack.getNumEqualPack(detail.getIsValid(), "isValid", packBean);
        DdlPreparedPack.getStringEqualPack(detail.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getNumEqualPack(detail.getIsQualityConfirm(), "isQualityConfirm", packBean);
        DdlPreparedPack.getNumEqualPack(detail.getIsTeamConfirm(), "isTeamConfirm", packBean);
        DdlPreparedPack.timeBuilder(detail.getCreateDateTimeStart(), detail.getCreateDateTimeEnd(), "spotCheckTime", packBean, true);
        List<String> orderJobNos = getOrderJobNos();
        if (CollectionUtils.isEmpty(orderJobNos)) {
            return new ListPager<>(new ArrayList<>(), pager);
        }
        DdlPreparedPack.getInPackList(orderJobNos, "orderJobNo", packBean);
        pager = PagerHelper.getPager(pager, antiStaticCheckDetailRepository.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(" order by spotCheckTime desc ");
        List<MesAntiStaticCheckDetail> antiStaticCheckDetailList = antiStaticCheckDetailRepository.findByHqlWherePage(packBean, pager);
        if (!CollectionUtils.isEmpty(antiStaticCheckDetailList)) {
            for (MesAntiStaticCheckDetail item : antiStaticCheckDetailList) {
                if (null == item) {
                    continue;
                }
                if (!StringUtils.isEmpty(item.getIsTeamConfirm())) {
                    item.setShiftGroupCheckName(MesExtEnumUtil.SHIFT_GROUP_CHECK.valueOfDescription(item.getIsTeamConfirm()));
                }
                if (!StringUtils.isEmpty(item.getIsQualityConfirm())) {
                    item.setQualityCheckName(MesExtEnumUtil.QUALITY_CHECK.valueOfDescription(item.getIsQualityConfirm()));
                }
                if (!StringUtils.isEmpty(item.getCheckResult())) {
                    item.setCheckResultName(MesExtEnumUtil.ANTI_CHECK_RESULT.valueOfDescription(item.getCheckResult()));
                }
            }
        }
        return new ListPager(antiStaticCheckDetailList, pager);
    }

    private List<String> getOrderJobNos() {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(AuthUtil.getOrganizeCode());
        List list = Stream.of(MesExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECK_COMPLETE.getValue(), MesExtEnumUtil.MES_ORJ_ORDER_STATUS.CLOSE.getValue()).collect(Collectors.toList());
        DdlPreparedPack.getInPack(list, "orderStatus", ddlPackBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.MES_OR_ORDER_TYPE.ESD_CHECK.getValue(), "orderType", ddlPackBean);
        List<MesOrderJob> mesOrderJobs = jobRepository.findByHqlWhere(ddlPackBean);
        return mesOrderJobs.stream().map(MesOrderJob::getOrderNo).distinct().collect(Collectors.toList());
    }

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

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


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


    @Override
    public void shiftGroupCheckUpdate(List<MesAntiStaticCheckDetail> details) {
        for (MesAntiStaticCheckDetail detail : details) {
            MesAntiStaticCheckDetail equDetail = antiStaticCheckDetailRepository.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());
            }

            antiStaticCheckDetailRepository.save(equDetail);
        }
    }

    @Override
    public void qualityCheckUpdate(List<MesAntiStaticCheckDetail> details) {
        for (MesAntiStaticCheckDetail detail : details) {
            MesAntiStaticCheckDetail equDetail = antiStaticCheckDetailRepository.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());
            }

            antiStaticCheckDetailRepository.save(equDetail);
        }
    }
}
