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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IEquipmentCheckDetailService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesEquipmentCheck;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesEquipmentCheckDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOrderJob;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkCenterExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesEquipmentCheckDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesEquipmentCheckRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOrderJobRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkCenterExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.mes.pcn.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.BaseResultBean;
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.enumutil.MesEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
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 java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

    @Autowired
    private MesEquipmentCheckDetailRepository equDetailRepository;

    @Autowired
    private MesOrderJobRepository mesOrderJobRepository;
    @Autowired
    private MesWorkCenterExtRepository workCenterRepository;
    @Autowired
    MesEquipmentCheckRepository mesEquipmentCheckRepository;
    @Autowired
    private ISyncFuncService syncFuncService;

    /**
     * 新增
     *
     * @param equipmentCheck
     * @return
     */
    @Override
    public MesEquipmentCheckDetail insert(MesEquipmentCheckDetail equipmentCheck) {
        ConvertBean.modelInitialize(equipmentCheck, AuthUtil.getSessionUser());
        equipmentCheck.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
        return equDetailRepository.insert(equipmentCheck);
    }

    /**
     * 修改
     *
     * @param equipmentCheck
     * @return
     */
    @Override
    public void update(MesEquipmentCheckDetail equipmentCheck) {
        //1、判断单据是否存在
        Long id = equipmentCheck.getId();
        MesEquipmentCheckDetail equipmentCheck2 = equDetailRepository.getById(id);
        if (ObjectUtils.isEmpty(equipmentCheck2)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "点检信息不存在");
        }

        BeanUtils.copyProperties(equipmentCheck, equipmentCheck2);
        ConvertBean.serviceModelUpdate(equipmentCheck2, equipmentCheck.getModifyUser());
        equipmentCheck2.setSpotCheckTime(equipmentCheck2.getModifyDatetime());
        equipmentCheck2.setSpotCheckUser(equipmentCheck2.getModifyUser());

        //根据单号查询任务主表信息
        String orderJobNo = equipmentCheck2.getOrderJobNo();
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(equipmentCheck.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(orderJobNo, "orderNo", ddlPackBean);
        MesOrderJob mesOrderJob = mesOrderJobRepository.getByProperty(ddlPackBean);

        if(null == mesOrderJob){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("单据【%s】不存在",orderJobNo)
                    .build();
        }

        mesOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CHECKING.getValue());
        mesOrderJobRepository.save(mesOrderJob);

        equDetailRepository.save(equipmentCheck2);

    }

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

        String workCenterCode = equipmentCheck.getWorkCenterCode();
        String organizeCode = equipmentCheck.getOrganizeCode();
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(equipmentCheck.getOrderJobNo(), "orderJobNo", packBean);
        DdlPreparedPack.getStringEqualPack(equipmentCheck.getWorkCellCode(), "workCellCode", packBean);

        //获取产线的当前班次
//        MesWorkCenterExt mesWorkCenter = getWorkCenter(workCenterCode, organizeCode);
//        DdlPreparedPack.getStringEqualPack(mesWorkCenter.getShiftCode(), "shiftCode", packBean);

        DdlPreparedPack.getNumEqualPack(equipmentCheck.getIsValid(), "isValid", packBean);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", packBean);
        pager = PagerHelper.getPager(pager, equDetailRepository.findByHqlWhereCount(packBean));
        return new ListPager(equDetailRepository.findByHqlWherePage(packBean, pager), 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()});
    }

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

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

    @Override
    public List<String> queryCell(MesEquipmentCheckDetail detail) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(detail.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(detail.getWorkCellCode(), "workCellCode", packBean);
        DdlPreparedPack.getStringEqualPack(detail.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(detail.getOrderJobNo(), "orderJobNo", packBean);
        List<MesEquipmentCheckDetail> details = equDetailRepository.findByHqlWhere(packBean);
        return details.stream().map(MesEquipmentCheckDetail::getWorkCellCode).distinct().collect(Collectors.toList());
    }

    @Override
    public void generateWeekCheck(String organizeCode,String workCenterCode) {
        generateOrderJob(organizeCode,workCenterCode,MesPcnExtEnumUtil.MES_EQUIPMENT_CHECK_TYPE.WEEK_CHECK.getValue());
    }

    @Override
    public void generateMonthCheck(String organizeCode,String workCenterCode) {
        generateOrderJob(organizeCode,workCenterCode,MesPcnExtEnumUtil.MES_EQUIPMENT_CHECK_TYPE.MONTH_CHECK.getValue());
    }

    private void generateOrderJob(String organizeCode, String workCenterCode, String checkType) {
        List<MesEquipmentCheck> mesEquipmentChecks = findEquByCenterCode(organizeCode, workCenterCode, checkType);
        if (!CollectionUtils.isEmpty(mesEquipmentChecks)) {
            MesWorkCenterExt workCenter = getWorkCenter(workCenterCode, organizeCode);
            MesOrderJob newOrderJob = new MesOrderJob();
            newOrderJob.setTaskType(MesPcnExtEnumUtil.MES_OR_TASK_TYPE.PREPARE_TASK.getValue());
            newOrderJob.setOrderType(MesPcnExtEnumUtil.MES_OR_ORDER_TYPE.EQU_CHECK.getValue());
            newOrderJob.setOrderNo(getOrderNo(organizeCode));
            newOrderJob.setWorkCenterCode(workCenterCode);
            newOrderJob.setOrderStatus(MesPcnExtEnumUtil.MES_ORJ_ORDER_STATUS.CREATE.getValue());
            newOrderJob.setOrderDate(DateUtil.formatDate("yyyy-MM-dd", new Date()));
            newOrderJob.setWorkTime(DateUtil.formatDate("yyyy-MM-dd", new Date()));
            newOrderJob.setGenerateTime(DateUtil.formatDate("yyyy-MM-dd", new Date()));
            newOrderJob.setOrganizeCode(organizeCode);
            newOrderJob.setIsValid(MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue());
            newOrderJob.setIsDeleted(MesEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            newOrderJob.setCreateDatetime(DateUtil.formatDate());
            newOrderJob.setModifyDatetime(DateUtil.formatDate());
            newOrderJob.setCheckType(checkType);
            newOrderJob.setHandlerMethod(MesPcnExtEnumUtil.HANDLER_METHOD.MANUALLY_CREATE.getValue());
            newOrderJob.setShiftCode(workCenter.getShiftCode());
            MesOrderJob job = mesOrderJobRepository.save(newOrderJob);


            for (MesEquipmentCheck mesEquipmentCheck : mesEquipmentChecks) {
                MesEquipmentCheckDetail mesEquipmentCheckDetail = new MesEquipmentCheckDetail();
                mesEquipmentCheckDetail.setOrderJobNo(job.getOrderNo());
                BeanUtils.copyProperties(mesEquipmentCheck, mesEquipmentCheckDetail, "id");
                mesEquipmentCheckDetail.setCheckType(checkType);
                mesEquipmentCheckDetail.setShiftCode(workCenter.getShiftCode());
                equDetailRepository.save(mesEquipmentCheckDetail);
            }
        }


    }

    public List<MesEquipmentCheck> findEquByCenterCode(String organizeCode, String workCenterCode, String checkType) {
        DdlPackBean ddlPackBean2 = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(checkType, "checkType", ddlPackBean2);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", ddlPackBean2);
        return mesEquipmentCheckRepository.findByHqlWhere(ddlPackBean2);

    }

    private String getOrderNo(String organizeCode) {
        String orderNo = "";
        BaseResultBean oneCodeResult = syncFuncService.syncSerialNo(new GenSerialNoModel(MesPcnExtConstWords.ORDER_NO_RULE), null, organizeCode, 1);
        if (oneCodeResult != null && oneCodeResult.isSuccess()) {
            orderNo = oneCodeResult.getResultList().get(0).toString();
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.CLOUD_CALL_EXCEPTION.getCode())
                    .setErrorDetail("生成唯一工单号失败")
                    .build();
        }
        return orderNo;
    }


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