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

import cn.estsh.i3plus.ext.mes.api.base.IQManageService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.IQManageDao;
import cn.estsh.i3plus.ext.mes.apiservice.dao.ep.IEpQManageDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesProcessQManage;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesQManageTaskDetail;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesProcessQManageRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesQManageTaskDetailRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
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.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.base.tool.HqlPack;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
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.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/01/18 11:41 上午
 * @Description:
 **/
@Service
public class QManageService implements IQManageService {

    @Autowired
    private MesProcessQManageRepository mesProcessQManageRDao;

    @Autowired
    private IQManageDao qManageDao;

    @Autowired
    private IEpQManageDao epQManageDao;

    @Autowired
    private MesQManageTaskDetailRepository mesQManageTaskDetailRDao;

    @Autowired
    private MesWorkCellRepository workCellRepository;

    @Override
    public MesProcessQManage insertMesProcessQManage(MesProcessQManage mesProcessQManage) {
        //数据唯一性校验
        StringBuffer whereStr = new StringBuffer();

        // 封装唯一校验查询条件
        HqlPack.getStringEqualPack(mesProcessQManage.getOrganizeCode(), "organizeCode", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getPartNo(), "partNo", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getProcessCode(), "processCode", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getManageProjects(), "manageProjects", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getScrewType(), "screwType", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getTighteningTorque(), "tighteningTorque", whereStr);

        if (mesProcessQManageRDao.isExitByHqlWhere(whereStr.toString())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("工序编号【%s】、管理项目【%s】、管理内容【%s】、检查项目【%s】在工序Q管理项目信息中已存在"
                            , mesProcessQManage.getProcessCode(), mesProcessQManage.getManageProjects(), mesProcessQManage.getScrewType(), mesProcessQManage.getTighteningTorque())
                    .setErrorSolution("请更换新增参数")
                    .build();
        }

        ConvertBean.serviceModelInitialize(mesProcessQManage, AuthUtil.getSessionUser().getUserName());
        return mesProcessQManageRDao.insert(mesProcessQManage);
    }

    @Override
    public void updateMesProcessQManage(MesProcessQManage mesProcessQManage, String userName) {
        //数据唯一性校验
        StringBuffer whereStr = new StringBuffer();

        // 封装唯一校验查询条件
        HqlPack.getNumNOEqualPack(mesProcessQManage.getId(), "id", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getOrganizeCode(), "organizeCode", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getPartNo(), "partNo", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getProcessCode(), "processCode", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getManageProjects(), "manageProjects", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getScrewType(), "screwType", whereStr);
        HqlPack.getStringEqualPack(mesProcessQManage.getTighteningTorque(), "tighteningTorque", whereStr);

        if (mesProcessQManageRDao.isExitByHqlWhere(whereStr.toString())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("工序编号【%s】、管理项目【%s】、管理内容【%s】、检查项目【%s】在工序Q管理项目信息中已存在"
                            , mesProcessQManage.getProcessCode(), mesProcessQManage.getManageProjects(), mesProcessQManage.getScrewType(), mesProcessQManage.getTighteningTorque())
                    .setErrorSolution("请更换修改参数")
                    .build();
        }

        MesProcessQManage processQManageDb = mesProcessQManageRDao.getById(mesProcessQManage.getId());
        if (null == processQManageDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("数据不存在")
                    .build();
        }

        BeanUtils.copyProperties(mesProcessQManage, processQManageDb);
        ConvertBean.serviceModelUpdate(processQManageDb, userName);
        mesProcessQManageRDao.save(processQManageDb);
    }

    @Override
    public ListPager<MesProcessQManage> queryMesProcessQManageByPager(MesProcessQManage mesProcessQManage, Pager pager) {
        if (mesProcessQManage == null) {
            pager = PagerHelper.getPager(pager, mesProcessQManageRDao.listCount());
            return new ListPager(mesProcessQManageRDao.listPager(pager), pager);
        } else {
            DdlPackBean hqlPack = MesExtHqlPack.getMesProcessQManage(mesProcessQManage);
            hqlPack.setOrderByStr(mesProcessQManage.orderBy());
            pager = PagerHelper.getPager(pager, mesProcessQManageRDao.findByHqlWhereCount(hqlPack));
            List<MesProcessQManage> byHqlWherePage = mesProcessQManageRDao.findByHqlWherePage(hqlPack, pager);
            return new ListPager(byHqlWherePage, pager);
        }
    }

    @Override
    public void deleteWeaklyMesProcessQManageByIds(Long[] ids, String userName) {
        mesProcessQManageRDao.deleteWeaklyByIds(ids, userName);
    }

    @Override
    public int updateMesProcessQManageStatus(String[] ids, int status, String userName) {
        StringBuffer wheres = new StringBuffer();
        HqlPack.getInPack(String.join(",", ids), "id", wheres);

        int num = mesProcessQManageRDao.updateByHqlWhere(
                wheres.toString(),
                new String[]{"isValid", "modifyUser", "modifyDatetime"},
                new Object[]{status, userName, TimeTool.getNowTime(true)}
        );
        return num;
    }

    @Override
    public ListPager<MesQManageTaskDetail> queryQmanageTaskDetailReportByPager(MesQManageTaskDetail mesQManageTaskDetail, Pager pager) {
        pager = PagerHelper.getPager(pager, qManageDao.getQManageTaskDetailReportCount(mesQManageTaskDetail));
        List<MesQManageTaskDetail> qmanageTaskDetails = qManageDao.queryQManageTaskDetailReportByPager(mesQManageTaskDetail, pager);

        if (!CollectionUtils.isEmpty(qmanageTaskDetails)) {

            for (MesQManageTaskDetail qmanageTaskDetail : qmanageTaskDetails) {
                if (qmanageTaskDetail != null) {
                    qmanageTaskDetail.setIsIntactName(!StringUtils.isEmpty(qmanageTaskDetail.getIsIntact()) ?
                            CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(Integer.valueOf(qmanageTaskDetail.getIsIntact())) : null);
                    qmanageTaskDetail.setIsTeamConfirmName(
                            StringUtils.isEmpty(CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsTeamConfirm())) ?
                                    CommonEnumUtil.TRUE_OR_FALSE.FALSE.getDescription() : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsTeamConfirm()));
                    qmanageTaskDetail.setIsQualityConfirmName(
                            StringUtils.isEmpty(CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsQualityConfirm())) ?
                                    CommonEnumUtil.TRUE_OR_FALSE.FALSE.getDescription() : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsQualityConfirm()));
                    if(!StringUtils.isEmpty(qmanageTaskDetail.getCheckType()) && qmanageTaskDetail.getCheckType().equals(MesExtEnumUtil.MES_Q_MANAGER_CHECK_TYPE.MONTH_CHECK.getValue())) {
                        qmanageTaskDetail.setPartNo("");
                        qmanageTaskDetail.setWorkOrderNo("");
                    }else{
                        qmanageTaskDetail.setCheckType(MesExtEnumUtil.MES_Q_MANAGER_CHECK_TYPE.ORDER_CHECK.getValue());
                    }
                }
            }
        }
        return new ListPager(qmanageTaskDetails, pager);
    }

    private Map<String, String> getWorkCenterCodeByWorkCellCodeMap(MesQManageTaskDetail mesQManageTaskDetail, List<MesQManageTaskDetail> qmanageTaskDetails) {
        List<String> workCellCodeList = qmanageTaskDetails.stream().map(MesQManageTaskDetail::getWorkCellCode).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(workCellCodeList)) return null;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesQManageTaskDetail.getOrganizeCode());
        DdlPreparedPack.getInPackList(workCellCodeList, MesExtConstWords.WORK_CELL_CODE, packBean);
        List<MesWorkCell> mesWorkCellDbList = workCellRepository.findByHqlWhere(packBean);
        return CollectionUtils.isEmpty(mesWorkCellDbList) ? null : mesWorkCellDbList.stream().collect(Collectors.toMap(MesWorkCell::getWorkCellCode, MesWorkCell::getWorkCenterCode));
    }

    @Override
    public ListPager<MesQManageTaskDetail> queryEpQManageTaskDetailReportByPager(MesQManageTaskDetail mesQManageTaskDetail, Pager pager) {
        pager = PagerHelper.getPager(pager, epQManageDao.getQManageTaskDetailReportCount(mesQManageTaskDetail));
        List<MesQManageTaskDetail> qmanageTaskDetails = epQManageDao.queryQManageTaskDetailReportByPager(mesQManageTaskDetail, pager);
        if (!CollectionUtils.isEmpty(qmanageTaskDetails)) {
            for (MesQManageTaskDetail qmanageTaskDetail : qmanageTaskDetails) {
                if (qmanageTaskDetail != null) {
                    qmanageTaskDetail.setIsIntactName(!StringUtils.isEmpty(qmanageTaskDetail.getIsIntact()) ?
                            MesExtEnumUtil.EP_PRODUCT_DATA_RESULT.valueOfDescription(qmanageTaskDetail.getIsIntact()) : null);
                    qmanageTaskDetail.setIsTeamConfirmName(
                            StringUtils.isEmpty(CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsTeamConfirm())) ?
                                    CommonEnumUtil.TRUE_OR_FALSE.FALSE.getDescription() : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsTeamConfirm()));
                    qmanageTaskDetail.setIsQualityConfirmName(
                            StringUtils.isEmpty(CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsQualityConfirm())) ?
                                    CommonEnumUtil.TRUE_OR_FALSE.FALSE.getDescription() : CommonEnumUtil.TRUE_OR_FALSE.valueOfDescription(qmanageTaskDetail.getIsQualityConfirm()));
                }
            }
        }
        return new ListPager(qmanageTaskDetails, pager);
    }

    @Override
    public void updateMesQManageTaskDetailById(List<MesQManageTaskDetail> mesQmanageTaskDetailList, String userName) {
        for (MesQManageTaskDetail mesQManageTaskDetail : mesQmanageTaskDetailList) {
            MesQManageTaskDetail qManageTaskDetail = mesQManageTaskDetailRDao.getById(mesQManageTaskDetail.getId());
            if (qManageTaskDetail == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("当前Q管理任务明细数据不存在")
                        .build();
            }

            if (mesQManageTaskDetail.getIsTeamConfirm() == CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) {
                qManageTaskDetail.setTeamConfirmUser(mesQManageTaskDetail.getTeamConfirmUser());
                qManageTaskDetail.setTeamConfirmTime(mesQManageTaskDetail.getTeamConfirmTime());
                qManageTaskDetail.setIsTeamConfirm(mesQManageTaskDetail.getIsTeamConfirm());
                ConvertBean.serviceModelUpdate(qManageTaskDetail, qManageTaskDetail.getTeamConfirmUser());
            } else {
                qManageTaskDetail.setQualityConfirmUser(mesQManageTaskDetail.getQualityConfirmUser());
                qManageTaskDetail.setQualityConfirmTime(mesQManageTaskDetail.getQualityConfirmTime());
                qManageTaskDetail.setIsQualityConfirm(mesQManageTaskDetail.getIsQualityConfirm());
                ConvertBean.serviceModelUpdate(qManageTaskDetail, qManageTaskDetail.getQualityConfirmUser());
            }

            mesQManageTaskDetailRDao.save(qManageTaskDetail);
        }
    }
}
