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

import cn.estsh.i3plus.ext.mes.api.base.ep.IEpEquipmentCheckDetailService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.ep.IEpEquipmentCheckDetailDao;
import cn.estsh.i3plus.ext.mes.apiservice.daoimpl.ep.EpEquipmentCheckDetailDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEpEquipmentCheckDetail;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEquipmentCheckDetail;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesOrderJob;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelEquipmentCheckDetail;
import cn.estsh.i3plus.ext.mes.pojo.model.ep.EpEquipmentCheckDetailModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesEpEquipmentCheckDetailRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesOrderJobRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
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.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.MesWorkCenter;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
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.transaction.annotation.Transactional;
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;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-13 14:42
 */
@Service
public class EpEquipmentCheckDetailService implements IEpEquipmentCheckDetailService {
    @Autowired
    private MesEpEquipmentCheckDetailRepository equipmentCheckDetailRepository;
    @Autowired
    private MesWorkCenterRepository workCenterRepository;
    @Autowired
    private MesOrderJobRepository jobRepository;
    @Autowired
    private IEpEquipmentCheckDetailDao equipmentCheckDetailDao;
    /**
     * 查询
     *
     * @param equipmentCheck
     * @param pager
     * @return
     */
    @Override
    public ListPager<EpEquipmentCheckDetailModel> queryByPager(MesEpEquipmentCheckDetail equipmentCheck, Pager pager) {
        pager = PagerHelper.getPager(pager, equipmentCheckDetailDao.queryEquipmentCheckDetailCount(equipmentCheck));
        List<MesEpEquipmentCheckDetail> equipmentCheckDetailList = equipmentCheckDetailDao.queryEquipmentCheckDetailByPager(equipmentCheck , pager);
        List<EpEquipmentCheckDetailModel> epEquipmentCheckDetailModels = new ArrayList<>();
        if (!CollectionUtils.isEmpty(equipmentCheckDetailList)) {
            for (MesEpEquipmentCheckDetail detail : equipmentCheckDetailList) {
                if (null == detail) {
                    continue;
                }
                EpEquipmentCheckDetailModel epEquipmentCheckDetailModel = new EpEquipmentCheckDetailModel();
                BeanUtils.copyProperties(detail, epEquipmentCheckDetailModel);
                if (!StringUtils.isEmpty(detail.getIsTeamConfirm())) {
                    epEquipmentCheckDetailModel.setShiftGroupCheckName(MesExtEnumUtil.SHIFT_GROUP_CHECK.valueOfDescription(detail.getIsTeamConfirm()));
                }
                if (!StringUtils.isEmpty(detail.getIsQualityConfirm())) {
                    epEquipmentCheckDetailModel.setQualityCheckName(MesExtEnumUtil.QUALITY_CHECK.valueOfDescription(detail.getIsQualityConfirm()));
                }
                if (!StringUtils.isEmpty(detail.getCheckType())) {
                    epEquipmentCheckDetailModel.setCheckTypeName(MesExtEnumUtil.MES_EQUIPMENT_CHECK_TYPE.valueOfDescription(detail.getCheckType()));
                }
                if (!StringUtils.isEmpty(detail.getCheckResult())) {
                    epEquipmentCheckDetailModel.setCheckResultName(MesExtEnumUtil.EQU_CHECK_RESULT.valueOfDescription(detail.getCheckResult()));
                }
                if(!StringUtils.isEmpty(detail.getResultType())){
                    epEquipmentCheckDetailModel.setResultTypeName(MesExtEnumUtil.EP_EQUIPMENT_CHECK_RESULT_TYPE.valueOfDescription(detail.getResultType()));
                }
                epEquipmentCheckDetailModels.add(epEquipmentCheckDetailModel);
            }
        }
        return new ListPager(epEquipmentCheckDetailModels, 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, MesExtConstWords.ORDER_STATUS, ddlPackBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.MES_OR_ORDER_TYPE.EQU_CHECK.getValue(), MesExtConstWords.ORDER_TYPE, 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、判断单据是否存在
        MesEpEquipmentCheckDetail equipmentCheck = equipmentCheckDetailRepository.getById(id);
        if (ObjectUtils.isEmpty(equipmentCheck)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "自动配置不存在");
        }

        return equipmentCheckDetailRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.SYSTEM_SYNC_STATUS },
                new Object[]{status, AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true), MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue()});
    }

    /**
     * 导入数据
     *
     * @param excelEquipmentChecks excel部分自动降落
     */
    @Override
    public void importData(List<ExcelEquipmentCheckDetail> excelEquipmentChecks) {
        if (CollectionUtils.isEmpty(excelEquipmentChecks)) {
            throw new BaseImppException("导入数据为空");
        }
        for (ExcelEquipmentCheckDetail excelEquipmentCheck : excelEquipmentChecks) {
            String workCenterCode = excelEquipmentCheck.getWorkCenterCode();
            String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
            MesWorkCenter mesWorkCenter = workCenterRepository.getByProperty(
                    new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                    new Object[]{organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});
            if (ObjectUtils.isEmpty(mesWorkCenter)) {
                throw new BaseImppException("产线不存在");
            }
            MesEpEquipmentCheckDetail mesEquipmentCheck = new MesEpEquipmentCheckDetail();
            BeanUtils.copyProperties(excelEquipmentCheck, mesEquipmentCheck);
            ConvertBean.modelInitialize(mesEquipmentCheck, AuthUtil.getSessionUser());
            mesEquipmentCheck.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            equipmentCheckDetailRepository.save(mesEquipmentCheck);
        }
    }

    /**
     * 异常
     *
     * @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
    @Transactional(rollbackFor = Exception.class)
    public void updateShiftGroupCheck(List<MesEpEquipmentCheckDetail> details) {
        for (MesEpEquipmentCheckDetail detail : details) {
            MesEpEquipmentCheckDetail equDetail = equipmentCheckDetailRepository.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());
                equDetail.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                ConvertBean.serviceModelUpdate(equDetail, equDetail.getTeamConfirmUser());
            }

            equipmentCheckDetailRepository.save(equDetail);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQualityCheck(List<MesEpEquipmentCheckDetail> details) {
        for (MesEpEquipmentCheckDetail detail : details) {
            MesEpEquipmentCheckDetail equDetail = equipmentCheckDetailRepository.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());
                equDetail.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                ConvertBean.serviceModelUpdate(equDetail, equDetail.getQualityConfirmUser());
            }

            equipmentCheckDetailRepository.save(equDetail);
        }
    }
}
