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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IFailCaseCheckDetailService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IWorkCenterExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesFailCaseCheckDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesOrderJob;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesPartCheckDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesFailCaseCheckDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOrderJobRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
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.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.MesWorkCell;
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.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

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

    @Autowired
    private MesFailCaseCheckDetailRepository failCaseCheckDetailRepository;
    @Autowired
    private MesOrderJobRepository mesOrderJobRepository;

    @Autowired
    private IWorkCenterExtService workCenterExtService;

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

    /**
     * 修改
     *
     * @param equipmentCheck
     * @return
     */
    @Override
    public void update(MesFailCaseCheckDetail equipmentCheck) {
        //1、判断单据是否存在
        Long id = equipmentCheck.getId();
        MesFailCaseCheckDetail equipmentCheck2 = failCaseCheckDetailRepository.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(DateUtil.formatDate());
        equipmentCheck2.setSpotCheckUser(equipmentCheck.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);
        failCaseCheckDetailRepository.save(equipmentCheck2);

    }

    /**
     * 查询
     *
     * @param equipmentCheck
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesFailCaseCheckDetail> queryByPager(MesFailCaseCheckDetail equipmentCheck, Pager pager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(equipmentCheck.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(equipmentCheck.getOrderJobNo(), "orderJobNo", packBean);
        DdlPreparedPack.getNumEqualPack(equipmentCheck.getIsValid(), "isValid", packBean);
        DdlPreparedPack.getStringEqualPack(equipmentCheck.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(equipmentCheck.getWorkCellCode(), "workCellCode", packBean);
        pager = PagerHelper.getPager(pager, failCaseCheckDetailRepository.findByHqlWhereCount(packBean));
        return new ListPager(failCaseCheckDetailRepository.findByHqlWherePage(packBean, pager), pager);
    }


    @Override
    public List<MesWorkCell> queryCell(MesFailCaseCheckDetail detail) {
        //根据业务只会是查询一条生产线的工位
        List<MesWorkCell> workCellList = null;
        DdlPackBean packBean = MesHqlPack.getMesAllData(detail.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(detail.getWorkCenterCode(), "workCenterCode", packBean);
        DdlPreparedPack.getStringEqualPack(detail.getOrderJobNo(), "orderJobNo", packBean);
        List<MesFailCaseCheckDetail> failCaseCheckDetailList = failCaseCheckDetailRepository.findByHqlWhere(packBean);

        failCaseCheckDetailList = CollectionUtils.isEmpty(failCaseCheckDetailList) ? null :
                failCaseCheckDetailList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkCenterCode()) && !StringUtils.isEmpty(o.getWorkCellCode()))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(failCaseCheckDetailList)) {
            return workCellList;
        }
        List<String> workCellCodeList = (failCaseCheckDetailList.stream().filter(o -> (null != o)).map(MesFailCaseCheckDetail::getWorkCellCode).collect(Collectors.toList()))
                .stream().filter(o -> !StringUtils.isEmpty(o)).distinct().collect(Collectors.toList());
        workCellList = workCenterExtService.queryCellsByCenter(failCaseCheckDetailList.get(0).getWorkCenterCode(), detail.getOrganizeCode());
        workCellList = CollectionUtils.isEmpty(workCellList) ? null :
                workCellList.stream().filter(o -> (null != o && workCellCodeList.contains(o.getWorkCellCode()))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(workCellList)) {
            return workCellList;
        }
        workCellList = workCellList.stream().filter(o -> null != o).distinct().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MesWorkCell::getWorkCellCode))), ArrayList::new)
        );
        return workCellList.stream().filter(o -> null != o).sorted(Comparator.comparing(MesWorkCell::getWorkCellCode)).collect(Collectors.toList());
    }


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


}
