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

import cn.estsh.i3plus.ext.mes.api.base.IEquipmentCheckDetailService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.IEquipmentCheckDetailDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEquipmentCheckDetail;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelEquipmentCheckDetail;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesEquipmentCheckDetailRepository;
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.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.mes.bean.MesWorkCenter;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
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.List;

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

    @Autowired
    private MesEquipmentCheckDetailRepository equipmentCheckDetailRepository;
    @Autowired
    private IEquipmentCheckDetailDao equipmentCheckDetailDao;
    @Autowired
    private MesWorkCenterRepository workCenterRepository;

    /**
     * 查询
     *
     * @param equipmentCheckDetail
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesEquipmentCheckDetail> queryByPager(MesEquipmentCheckDetail equipmentCheckDetail, Pager pager) {
        pager = PagerHelper.getPager(pager, equipmentCheckDetailDao.queryEquipmentCheckDetailCount(equipmentCheckDetail));
        List<MesEquipmentCheckDetail> equipmentCheckDetailList = equipmentCheckDetailDao.queryEquipmentCheckDetailByPager(equipmentCheckDetail , pager);
        if (!CollectionUtils.isEmpty(equipmentCheckDetailList)) {
            for (MesEquipmentCheckDetail detail : equipmentCheckDetailList) {
                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.getCheckType())) {
                    detail.setCheckTypeName(MesExtEnumUtil.MES_EQUIPMENT_CHECK_TYPE.valueOfDescription(detail.getCheckType()));
                }
                if (!StringUtils.isEmpty(detail.getCheckResult())) {
                    detail.setCheckResultName(MesExtEnumUtil.EQU_CHECK_RESULT.valueOfDescription(detail.getCheckResult()));
                }
            }
        }
        return new ListPager(equipmentCheckDetailList, pager);
    }

    /**
     * 根据
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public int updateIsValidById(long id, Integer status) {
        //1、判断单据是否存在
        MesEquipmentCheckDetail 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[]{"id"}, new Object[]{id},
                new String[]{MesConstWords.IS_VALID, "modifyUser", "modifyDatetime"},
                new Object[]{status, AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true)});
    }

    /**
     * 导入数据
     *
     * @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[]{"organizeCode", "isValid", "isDeleted"},
                    new Object[]{organizeCode,
                            CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            CommonEnumUtil.IS_DEAL.NO.getValue()});
            if (ObjectUtils.isEmpty(mesWorkCenter)) {
                throw new BaseImppException("产线不存在");
            }
            MesEquipmentCheckDetail mesEquipmentCheck = new MesEquipmentCheckDetail();
            BeanUtils.copyProperties(excelEquipmentCheck, mesEquipmentCheck);


            ConvertBean.modelInitialize(mesEquipmentCheck, AuthUtil.getSessionUser());
            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<MesEquipmentCheckDetail> details) {
        for (MesEquipmentCheckDetail detail : details) {
            MesEquipmentCheckDetail 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());
                ConvertBean.serviceModelUpdate(equDetail, equDetail.getTeamConfirmUser());
            }

            equipmentCheckDetailRepository.save(equDetail);
        }
    }

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

            equipmentCheckDetailRepository.save(equDetail);
        }
    }
}

