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

import cn.estsh.i3plus.ext.mes.api.base.jx.ITorqueManageService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesProcessTorqueManage;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesProcessTorqueManageTaskDetail;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesProcessTorqueManageRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesProcessTorqueManageTaskDetailRepository;
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.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: xinwang.yi
 * @CreateDate: 2023/10/09 11:41 上午
 * @Description:
 **/
@Service
public class TorqueManageService implements ITorqueManageService {

    @Autowired
    private MesProcessTorqueManageRepository mesProcessTorqueManageRDao;

    @Autowired
    private MesProcessTorqueManageTaskDetailRepository mesTorqueManageTaskDetailRDao;

    @Override
    public MesProcessTorqueManage insertMesProcessTorqueManage(MesProcessTorqueManage mesProcessTorqueManage) {
        //数据唯一性校验
        StringBuffer whereStr = new StringBuffer();

        // 封装唯一校验查询条件
        HqlPack.getStringEqualPack(mesProcessTorqueManage.getOrganizeCode(), MesExtConstWords.ORGANIZE_CODE, whereStr);
        HqlPack.getStringEqualPack(mesProcessTorqueManage.getPartNo(), MesExtConstWords.PART_NO, whereStr);
        HqlPack.getStringEqualPack(mesProcessTorqueManage.getProcessCode(), MesExtConstWords.PROCESS_CODE, whereStr);
        HqlPack.getStringEqualPack(mesProcessTorqueManage.getFasteningPosition(), MesExtConstWords.FASTENING_POSITION, whereStr);

        if (mesProcessTorqueManageRDao.isExitByHqlWhere(whereStr.toString())) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("物料编码【%s】、工序编号【%s】、紧固部位【%s】在扭矩管理信息中已存在"
                            , mesProcessTorqueManage.getPartNo(), mesProcessTorqueManage.getProcessCode(), mesProcessTorqueManage.getFasteningPosition())
                    .setErrorSolution("请更换新增参数")
                    .build();
        }

        ConvertBean.serviceModelInitialize(mesProcessTorqueManage, AuthUtil.getSessionUser().getUserName());
        return mesProcessTorqueManageRDao.insert(mesProcessTorqueManage);
    }

    @Override
    public void updateMesProcessTorqueManage(MesProcessTorqueManage mesProcessTorqueManage, String userName) {
        MesProcessTorqueManage processTorqueManageDb = mesProcessTorqueManageRDao.getById(mesProcessTorqueManage.getId());

        if (null == processTorqueManageDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", processTorqueManageDb.getId())
                    .build();

        // 封装唯一校验查询条件
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(mesProcessTorqueManage.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesProcessTorqueManage.getOrganizeCode(), MesExtConstWords.ORGANIZE_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(mesProcessTorqueManage.getPartNo(), MesExtConstWords.PART_NO, packBean);
        DdlPreparedPack.getStringEqualPack(mesProcessTorqueManage.getProcessCode(), MesExtConstWords.PROCESS_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(mesProcessTorqueManage.getFasteningPosition(), MesExtConstWords.FASTENING_POSITION, packBean);
        MesProcessTorqueManage processTorqueManageDbIsExist = mesProcessTorqueManageRDao.getByProperty(packBean);

        if (null != processTorqueManageDbIsExist && processTorqueManageDbIsExist.getId().compareTo(processTorqueManageDbIsExist.getId()) != 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("物料编码【%s】、工序编号【%s】、紧固部位【%s】在扭矩管理信息启用或禁用数据中已存在"
                            , mesProcessTorqueManage.getPartNo(), mesProcessTorqueManage.getProcessCode(), mesProcessTorqueManage.getFasteningPosition())
                    .setErrorSolution("请更换新增参数")
                    .build();
        }

        processTorqueManageDb.setPartNo(mesProcessTorqueManage.getPartNo());
        processTorqueManageDb.setPartName(mesProcessTorqueManage.getPartName());
        processTorqueManageDb.setProcessCode(mesProcessTorqueManage.getProcessCode());
        processTorqueManageDb.setProcessName(mesProcessTorqueManage.getProcessName());
        processTorqueManageDb.setSpecification(mesProcessTorqueManage.getSpecification());
        processTorqueManageDb.setFasteningPosition(mesProcessTorqueManage.getFasteningPosition());
        processTorqueManageDb.setUpLimit(mesProcessTorqueManage.getUpLimit());
        processTorqueManageDb.setDownLimit(mesProcessTorqueManage.getDownLimit());
        processTorqueManageDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

        ConvertBean.serviceModelUpdate(processTorqueManageDb, userName);
        mesProcessTorqueManageRDao.save(processTorqueManageDb);
    }

    @Override
    public ListPager<MesProcessTorqueManage> queryMesProcessTorqueManageByPager(MesProcessTorqueManage mesProcessTorqueManage, Pager pager) {
        if (mesProcessTorqueManage == null) {
            pager = PagerHelper.getPager(pager, mesProcessTorqueManageRDao.listCount());
            return new ListPager(mesProcessTorqueManageRDao.listPager(pager), pager);
        } else {
            DdlPackBean hqlPack = MesExtHqlPack.getMesProcessTorqueManage(mesProcessTorqueManage);
            hqlPack.setOrderByStr(mesProcessTorqueManage.orderBy());
            pager = PagerHelper.getPager(pager, mesProcessTorqueManageRDao.findByHqlWhereCount(hqlPack));
            List<MesProcessTorqueManage> byHqlWherePage = mesProcessTorqueManageRDao.findByHqlWherePage(hqlPack, pager);
            return new ListPager(byHqlWherePage, pager);
        }
    }

    @Override
    public void deleteWeaklyMesProcessTorqueManageByIds(String[] ids, String userName) {
        //mesProcessTorqueManageRDao.deleteWeaklyByIds(ids, userName);

        StringBuffer wheres = new StringBuffer();
        HqlPack.getInPack(String.join(",", ids), MesExtConstWords.ID, wheres);

        int num = mesProcessTorqueManageRDao.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesExtConstWords.IS_DELETED, MesExtConstWords.SYSTEM_SYNC_STATUS, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue(), userName, TimeTool.getNowTime(true)}
        );

    }

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

        int num = mesProcessTorqueManageRDao.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.SYSTEM_SYNC_STATUS, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue(), userName, TimeTool.getNowTime(true)}
        );
        return num;
    }

    @Override
    public ListPager<MesProcessTorqueManageTaskDetail> queryTorqueManageTaskDetailReportByPager(MesProcessTorqueManageTaskDetail mesTorqueManageTaskDetail, Pager pager) {
        DdlPackBean packBean = MesExtHqlPack.getMesProcessTorqueManageTaskDetail(mesTorqueManageTaskDetail);

        pager = PagerHelper.getPager(pager, mesTorqueManageTaskDetailRDao.findByHqlWhereCount(packBean));
        List<MesProcessTorqueManageTaskDetail> torqueManageTaskDetailList = mesTorqueManageTaskDetailRDao.findByHqlWhere(packBean);

        if (!CollectionUtils.isEmpty(torqueManageTaskDetailList)) {

            for (MesProcessTorqueManageTaskDetail torqueManageTaskDetail : torqueManageTaskDetailList) {
                if (torqueManageTaskDetail != null) {
                    if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueSpecValue())) {
                        List<String> torqueSpecValueList = Arrays.stream(torqueManageTaskDetail.getTorqueSpecValue().split(MesExtConstWords.COMMA)).collect(Collectors.toList());
                        StringBuffer torqueSpecValueDesc = new StringBuffer();
                        for (String torqueSpecValue : torqueSpecValueList) {
                            torqueSpecValueDesc.append(MesExtEnumUtil.TORQUE_SPEC_VALUE.valueOfDescription(torqueSpecValue));
                            torqueSpecValueDesc.append(MesExtConstWords.COMMA);
                        }
                        torqueSpecValueDesc.deleteCharAt(torqueSpecValueDesc.length() - 1);
                        torqueManageTaskDetail.setTorqueSpecValueDesc(torqueSpecValueDesc.toString());
                    }

                    if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueManageNo1())) torqueManageTaskDetail.setTorqueManageNo1Full("M60-"+ torqueManageTaskDetail.getTorqueManageNo1() +"-Q0");
                    if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueManageNo2())) torqueManageTaskDetail.setTorqueManageNo2Full("M60-"+ torqueManageTaskDetail.getTorqueManageNo2() +"-Q0");
                    if (!StringUtils.isEmpty(torqueManageTaskDetail.getTorqueManageNo3())) torqueManageTaskDetail.setTorqueManageNo3Full("M60-"+ torqueManageTaskDetail.getTorqueManageNo3() +"-Q0");
                }
            }
        }
        return new ListPager(torqueManageTaskDetailList, pager);
    }

    @Override
    public void doConfirmTorqueManageList(List<MesProcessTorqueManageTaskDetail> mesTorqueManageTaskDetailList, String userName) {
        List<MesProcessTorqueManageTaskDetail> mesTorqueManageTaskDetailDbList = new ArrayList<>();
        for (MesProcessTorqueManageTaskDetail mesTorqueManageTaskDetail : mesTorqueManageTaskDetailList) {
            MesProcessTorqueManageTaskDetail torqueManageTaskDetail = mesTorqueManageTaskDetailRDao.getById(mesTorqueManageTaskDetail.getId());
            if (torqueManageTaskDetail == null) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("当前Q管理任务明细数据不存在")
                        .build();
            }

            torqueManageTaskDetail.setTeamConfirmUser(userName);
            torqueManageTaskDetail.setTeamConfirmTime(TimeTool.getNowTime(true));
            torqueManageTaskDetail.setIsTeamConfirm(MesExtEnumUtil.CONFIRM_TYPE.YES.getValue());
            torqueManageTaskDetail.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelUpdate(torqueManageTaskDetail, userName);
            mesTorqueManageTaskDetailDbList.add(torqueManageTaskDetail);

        }

        mesTorqueManageTaskDetailRDao.saveAll(mesTorqueManageTaskDetailDbList);
    }
}
