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

import cn.estsh.i3plus.ext.mes.api.base.IFourMDetailService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.IFourMDetailDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pojo.model.FourMDetailModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.*;
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.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 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;
import java.util.stream.Collectors;

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

    @Autowired
    private MesFourMDetailRepository fourMDetailRepository;

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

    @Autowired
    private MesFourMManageRepository fourMManageRepository;

    @Autowired
    private MesFourMConfirmRepository fourMConfirmRepository;

    @Autowired
    private MesFourMChangeRepository fourMChangeRepository;

    @Autowired
    private IFourMDetailDao fourMDetailDao;


    /**
     * 新增
     *
     * @param speParam
     * @return
     */
    @Override
    public MesFourMDetail insert(MesFourMDetail speParam) {
        ConvertBean.modelInitialize(speParam, AuthUtil.getSessionUser());
        return fourMDetailRepository.insert(speParam);
    }

    /**
     * 修改
     *
     * @param speParam
     * @return
     */
    @Override
    public void update(MesFourMDetail speParam) {
        //1、判断单据是否存在
        Long id = speParam.getId();
        MesFourMDetail speParam2 = fourMDetailRepository.getById(id);
        if (ObjectUtils.isEmpty(speParam2)) {
            throwImppException(CommonEnumUtil.SOFT_TYPE.MES.getCode(), ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode(), "数据不存在");
        }
        BeanUtils.copyProperties(speParam, speParam2);
        ConvertBean.serviceModelUpdate(speParam2, AuthUtil.getSessionUser().getUserName());
        fourMDetailRepository.update(speParam2);

    }

    /**
     * 查询
     *
     * @param fourMDetail
     * @param pager
     * @return
     */
    @Override
    public ListPager<FourMDetailModel> queryByPager(MesFourMDetail fourMDetail, Pager pager) {
        pager = PagerHelper.getPager(pager, fourMDetailDao.queryFourMDetailByPagerCount(fourMDetail));
        List<FourMDetailModel> fourMDetailList = fourMDetailDao.queryFourMDetailByPager(fourMDetail , pager);
        if (!CollectionUtils.isEmpty(fourMDetailList)) {
            for (FourMDetailModel detail : fourMDetailList) {
                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.getManageType())) {
                    detail.setManageTypeName(MesExtEnumUtil.MANAGE_TYPE.valueOfDescription(detail.getManageType()));
                }
            }
        }
        return new ListPager(fourMDetailList, pager);
    }

    @Override
    public List<String> queryCell(String workCenterCode, String organizeCode) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(organizeCode);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", packBean);
        List<MesFourMDetail> details = fourMDetailRepository.findByHqlWhere(packBean);
        return details.stream().map(MesFourMDetail::getWorkCellCode).distinct().collect(Collectors.toList());
    }

    @Override
    public List<MesWorkOrderExt> queryWorkOrder(String workCenterCode, String organizeCode) {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(MesExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue(), "workOrderStatus", ddlPackBean);
        DdlPreparedPack.getStringEqualPack(workCenterCode, "workCenterCode", ddlPackBean);
        ddlPackBean.setOrderByStr(" order by seq desc ");
        return workOrderExtRepository.findByHqlWhere(ddlPackBean);

    }

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

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

    /**
     * 查询
     *
     * @param fourMConfirm
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesFourMConfirm> queryByPager(MesFourMConfirm fourMConfirm, Pager pager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(fourMConfirm.getConfirmCode(), "confirmCode", packBean);
        DdlPreparedPack.getNumEqualPack(fourMConfirm.getIsValid(), "isValid", packBean);
        DdlPreparedPack.getNumEqualPack(fourMConfirm.getManageType(), "manageType", packBean);
        pager = PagerHelper.getPager(pager, fourMConfirmRepository.findByHqlWhereCount(packBean));
        return new ListPager(fourMConfirmRepository.findByHqlWherePage(packBean, pager), pager);
    }

    /**
     * 查询
     *
     * @param equipmentParam
     * @param pager
     * @return
     */
    @Override
    public ListPager<MesFourMManage> queryByPager(MesFourMManage equipmentParam, Pager pager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(equipmentParam.getManageCode(), "manageCode", packBean);
        DdlPreparedPack.getNumEqualPack(equipmentParam.getManageType(), "manageType", packBean);
        DdlPreparedPack.getNumEqualPack(equipmentParam.getIsValid(), "isValid", packBean);
        pager = PagerHelper.getPager(pager, fourMManageRepository.findByHqlWhereCount(packBean));
        return new ListPager(fourMManageRepository.findByHqlWherePage(packBean, pager), pager);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShiftGroupCheck(List<MesFourMDetail> details) {
        for (MesFourMDetail detail : details) {
            MesFourMDetail equDetail = fourMDetailRepository.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());
            }

            fourMDetailRepository.save(equDetail);
        }
    }

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

            fourMDetailRepository.save(equDetail);
        }
    }
}
