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

import cn.estsh.i3plus.ext.mes.api.base.IWeighManagerService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWeighManager;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWeighManagerDetail;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWeighManagerDetailRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWeighManagerRepository;
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.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.sqlpack.MesHqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
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;

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/2/7 14:20
 **/
@Service
@Slf4j
public class WeighManagerService implements IWeighManagerService{

    @Autowired
    private MesWeighManagerRepository weighManagerRepository;
    @Autowired
    private MesWeighManagerDetailRepository weighManagerDetailRepository;

    @Override
    public List<MesWeighManagerDetail> detail(MesWeighManager manager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(manager.getIsValid(), "isValid", packBean);
        DdlPreparedPack.getStringEqualPack(manager.getOrderNo(), "orderNo", packBean);
        DdlPreparedPack.getStringEqualPack(manager.getOrderJobNo(), "orderJobNo", packBean);
        return weighManagerDetailRepository.findByHqlWhere(packBean);
    }


    /**
     * 查询
     *
     * @param weighManager
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesWeighManager> queryByPager(MesWeighManager weighManager, Pager pager) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(weighManager.getOrganizeCode());

        DdlPreparedPack.getNumEqualPack(weighManager.getIsQualityConfirm(), MesExtConstWords.IS_QUALITY_CONFIRM, packBean);
        DdlPreparedPack.getNumEqualPack(weighManager.getIsTeamConfirm(), MesExtConstWords.IS_TEAM_CONFIRM, packBean);
        DdlPreparedPack.timeBuilder(weighManager.getCreateDateTimeStart(), weighManager.getCreateDateTimeEnd(), MesExtConstWords.CREATE_DATE_TIME, packBean, true);
        DdlPreparedPack.getStringEqualPack(weighManager.getWorkCenterCode(), MesExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(weighManager.getOrderNo(), MesExtConstWords.ORDER_NO, packBean);
        DdlPreparedPack.getStringEqualPack(weighManager.getPartNo(), MesExtConstWords.PART_NO, packBean);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.CONFIRM_TYPE.YES.getValue(), MesExtConstWords.CARTON_CONFIRM_CHECK, packBean);
        DdlPreparedPack.getStringBiggerPack(weighManager.getCartonConfirmTimeStart(), MesExtConstWords.CARTON_CONFIRM_TIME, packBean);
        DdlPreparedPack.getStringSmallerPack(weighManager.getCartonConfirmTimeEnd(), MesExtConstWords.CARTON_CONFIRM_TIME, packBean);

        pager = PagerHelper.getPager(pager, weighManagerRepository.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(" order by cartonConfirmTime desc ");
        List<MesWeighManager> weighManagerList = weighManagerRepository.findByHqlWherePage(packBean, pager);
        if (!CollectionUtils.isEmpty(weighManagerList)) {
            for (MesWeighManager item : weighManagerList) {
                if (null == item) {
                    continue;
                }
                if (!StringUtils.isEmpty(item.getIsTeamConfirm())) {
                    item.setShiftGroupCheckName(MesExtEnumUtil.SHIFT_GROUP_CHECK.valueOfDescription(item.getIsTeamConfirm()));
                }
                if (!StringUtils.isEmpty(item.getIsQualityConfirm())) {
                    item.setQualityCheckName(MesExtEnumUtil.QUALITY_CHECK.valueOfDescription(item.getIsQualityConfirm()));
                }
            }
        }
        return new ListPager(weighManagerList, pager);
    }

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

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


    /**
     * 异常
     *
     * @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
    public void updateShiftGroupCheck(List<MesWeighManager> details) {
        for (MesWeighManager detail : details) {
            MesWeighManager equDetail = weighManagerRepository.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());
            }
            weighManagerRepository.save(equDetail);
        }
    }

    @Override
    public void updateQualityCheck(List<MesWeighManager> details) {
        for (MesWeighManager detail : details) {
            MesWeighManager equDetail = weighManagerRepository.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());
            }

            weighManagerRepository.save(equDetail);
        }
    }
}
