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

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

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 mesOrderJobRepository;
    @Autowired
    private MesWorkCenterRepository workCenterRepository;

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

    /**
     * 修改
     *
     * @param antiStaticCheckDetail
     * @return
     */
    @Override
    public void update(MesAntiStaticCheckDetail antiStaticCheckDetail) {
        //1、判断单据是否存在
        Long id = antiStaticCheckDetail.getId();
        MesAntiStaticCheckDetail antiStaticCheckDetail2 = antiStaticCheckDetailRepository.getById(id);
        if (ObjectUtils.isEmpty(antiStaticCheckDetail2)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "数据不存在");
        }

        BeanUtils.copyProperties(antiStaticCheckDetail, antiStaticCheckDetail2);
        ConvertBean.serviceModelUpdate(antiStaticCheckDetail2, antiStaticCheckDetail.getModifyUser());
        antiStaticCheckDetail2.setSpotCheckTime(antiStaticCheckDetail2.getModifyDatetime());
        antiStaticCheckDetail2.setSpotCheckUser(antiStaticCheckDetail2.getModifyUser());

        //根据单号查询任务主表信息
        String orderJobNo = antiStaticCheckDetail2.getOrderJobNo();
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(antiStaticCheckDetail.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);

        antiStaticCheckDetailRepository.save(antiStaticCheckDetail2);

    }

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

    /**
     * 根据
     *
     * @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_PCN.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)});
    }

    @Override
    public List<String> queryCell(String orderNo, String organizeCode) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", packBean);
        List<MesAntiStaticCheckDetail> details = antiStaticCheckDetailRepository.findByHqlWhere(packBean);
        return (details.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkCellCode())))
                .map(MesAntiStaticCheckDetail::getWorkCellCode).collect(Collectors.toList()))
                .stream().filter(o -> !StringUtils.isEmpty(o)).distinct().collect(Collectors.toList());
    }

    //@Override
    //public List<String> queryProcessCodeList(String orderNo, String organizeCode) {
    //    DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
    //    DdlPreparedPack.getStringEqualPack(orderNo, "orderJobNo", packBean);
    //    List<MesAntiStaticCheckDetail> details = antiStaticCheckDetailRepository.findByHqlWhere(packBean);
    //    return (details.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getWorkCellCode())))
    //            .map(MesAntiStaticCheckDetail::getProcessCode).collect(Collectors.toList()))
    //            .stream().filter(o -> !StringUtils.isEmpty(o)).distinct().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();
    }



}
