package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.jx;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPartExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu.IBuOutPutStatisticsService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.jx.IJxOqcCheckService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.jx.IJxOqcLastCheckService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.jx.IJxOutPutStatisticsDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.OqcLastCheckModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.OqcLastCheckParamModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu.BuOutPutStatisticsModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOqcLastCheckIfRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOutPutStatisticsOqcRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
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.mes.model.GenSerialNoModel;
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.StringUtils;

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

/**
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2022-06-09 13:42
 */
@Slf4j
@Service
public class JxOqcLastCheckService implements IJxOqcLastCheckService {

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private MesOutPutStatisticsOqcRepository outPutStatisticsOqcRepository;

    @Autowired
    private IJxOutPutStatisticsDao outPutStatisticsDao;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private MesOqcLastCheckIfRepository oqcLastCheckIfRepository;

    @Autowired
    private IBuOutPutStatisticsService buOutPutStatisticsService;

    @Override
    public ListPager<OqcLastCheckModel> queryOqcLastCheckPager(OqcLastCheckModel model, Pager pager) {
        pager = PagerHelper.getPager(pager, outPutStatisticsDao.queryOutPutStatisticsOqcByPagerCount(model));
        List<OqcLastCheckModel> resultList = outPutStatisticsDao.queryOutPutStatisticsOqcByPager(model , pager);
        if (!CollectionUtils.isEmpty(resultList)) {
            List<String> partNoList = (resultList.stream().filter(o -> null != o).map(OqcLastCheckModel::getPartNo).collect(Collectors.toList()))
                    .stream().distinct().filter(o -> !StringUtils.isEmpty(o)).collect(Collectors.toList());

            //List<BuOutPutStatisticsModel> outPutStatisticsList = httpRequestToPcnService.queryOutPutStatisticsList(model, model.getOrganizeCode());

            List<BuOutPutStatisticsModel> outPutStatisticsList = buOutPutStatisticsService.queryOutPutStatisticsModelList(model, model.getOrganizeCode());

            Map<Long, BuOutPutStatisticsModel> pidMap = CollectionUtils.isEmpty(outPutStatisticsList) ? null :
                    outPutStatisticsList.stream().filter(o -> null != o).collect(Collectors.toMap(BuOutPutStatisticsModel::getId, o -> o));

            List<MesPartExt> partExtList = partExtService.getPartExtListByPartNoList(model.getOrganizeCode(), partNoList);
            Map<String, List<MesPartExt>> partNoMap = CollectionUtils.isEmpty(partExtList) ? new HashMap<>() :
                    partExtList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartExt::getPartNo));

            Iterator<OqcLastCheckModel> iterator = resultList.iterator();
            while (iterator.hasNext()) {
                OqcLastCheckModel result = iterator.next();
                if (null == result) {
                    continue;
                }
                if (StringUtils.isEmpty(result.getCheckResult()) ||
                        MesPcnExtEnumUtil.OQC_TOTAL_STATUS.UNTREATED.getValue() == result.getCheckResult() ||
                        StringUtils.isEmpty(MesPcnExtEnumUtil.OQC_TOTAL_STATUS.valueOfDescription(result.getCheckResult()))) {
                    result.setColor(MesPcnExtConstWords.WHITE);
                } else if (MesPcnExtEnumUtil.OQC_TOTAL_STATUS.QUALIFIED.getValue() == result.getCheckResult()) {
                    result.setColor(MesPcnExtConstWords.GREEN);
                } else {
                    result.setColor(MesPcnExtConstWords.RED);
                }

                if(!CollectionUtils.isEmpty(pidMap) && pidMap.containsKey(result.getPid())){
                    BuOutPutStatisticsModel outPutStatisticsModel = pidMap.get(result.getPid());
                    result.setQty(outPutStatisticsModel.getQty());
                    result.setPlanQty(outPutStatisticsModel.getPlanQty());
                    result.setUnFinishQty(outPutStatisticsModel.getUnFinishQty());
                }
                //检验结果
                result.setCheckResultName(StringUtils.isEmpty(result.getCheckResult()) ? null : MesPcnExtEnumUtil.OQC_TOTAL_STATUS.valueOfDescription(result.getCheckResult()));
                if(result.getWorkOrderType() != null){
                    if (result.getWorkOrderType() == MesPcnExtEnumUtil.WORK_ORDER_TYPE.ATTEMPT_ORDER.getValue()) {
                        iterator.remove();
                        continue;
                    }
                    //工单类型
                    result.setWorkOrderTypeName(MesPcnExtEnumUtil.WORK_ORDER_TYPE.valueOfDescription(result.getWorkOrderType()));
                }
                if (partNoMap.containsKey(result.getPartNo()) &&
                        !StringUtils.isEmpty(partNoMap.get(result.getPartNo()).get(0).getCategoryCode3()) && !partNoMap.get(result.getPartNo()).get(0).getCategoryCode3().equals(MesPcnExtEnumUtil.OQC_MANAGE_ACTION_TYPE.SERIAL_NUMBER.getValue())) {
                    result.setZjCheckBoo(true);
                } else {
                    result.setZjCheckBoo(false);
                }
            }
        }
        return new ListPager(resultList, pager);
    }

    @Override
    public void updateOutPutStatisticsOqcCheck(OqcLastCheckParamModel model) {
        for (OqcLastCheckParamModel item : model.getModelList()) {
            MesOutPutStatisticsOqc oqc = outPutStatisticsOqcRepository.getById(item.getId());
            oqc.setCheckResult(model.getCheckResult());
            oqc.setCheckUser(model.getUserInfo());
            oqc.setRemark(item.getRemark());
            oqc.setCheckNo(getTotalOqcNo(model.getUserInfo(), model.getOrganizeCode()));
            ConvertBean.serviceModelUpdate(oqc, model.getUserInfo());
            oqc.setConfirmTime(oqc.getModifyDatetime());
            oqc.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            outPutStatisticsOqcRepository.save(oqc);

            MesPartExt part = partExtService.getPartExt(oqc.getOrganizeCode(), oqc.getPartNo());
            if (null == part) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("物料编码[%s]信息不存在", oqc.getPartNo())
                        .build();
            }

            if (StringUtils.isEmpty(part.getCategoryCode3())) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("物料分类3未维护")
                        .build();
            }

            MesOqcLastCheckIf oqcLastCheckIf = new MesOqcLastCheckIf();
            oqcLastCheckIf.setWorkTime(oqc.getWorkTime());
            oqcLastCheckIf.setShiftCode(oqc.getShiftCode());
            oqcLastCheckIf.setWorkOrderNo(oqc.getWorkOrderNo());
            oqcLastCheckIf.setCheckResult(oqc.getCheckResult());
            oqcLastCheckIf.setPartType(part.getCategoryCode3().equals(MesPcnExtEnumUtil.OQC_MANAGE_ACTION_TYPE.SERIAL_NUMBER.getValue()) ?
                    MesPcnExtEnumUtil.OQC_MANAGE_ACTION_TYPE.SERIAL_NUMBER.getValue() :
                    MesPcnExtEnumUtil.OQC_MANAGE_ACTION_TYPE.ZJ.getValue());
            oqcLastCheckIf.setOrganizeCode(model.getOrganizeCode());
            oqcLastCheckIf.setSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelInitialize(oqcLastCheckIf, model.getUserInfo());
            oqcLastCheckIfRepository.insert(oqcLastCheckIf);
        }
    }

    //private List<String> getSn(Integer num) {
    //    try {
    //        BaseResultBean<String> oneCodeResult = sysOrderNoRuleCloud.getOrderNo(MesPcnExtConstWords.OQC_TOTAL_CHECK_NO, num);
    //        if (null != oneCodeResult && oneCodeResult.success && !CollectionUtils.isEmpty(oneCodeResult.getResultList())) {
    //            return oneCodeResult.getResultList();
    //        } else {
    //            throw ImppExceptionBuilder.newInstance()
    //                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
    //                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
    //                    .setErrorDetail("调用IMPP创建OQC_TOTAL_CHECK_NO编号出现问题")
    //                    .build();
    //        }
    //    } catch (Exception e) {
    //        throw ImppExceptionBuilder.newInstance()
    //                .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
    //                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
    //                .setErrorDetail("调用IMPP创建OQC_TOTAL_CHECK_NO编号时异常:%s", e.getMessage())
    //                .build();
    //    }
    //}

    private String getTotalOqcNo(String userName, String organizeCode) {
        BaseResultBean oneCodeResult = syncFuncService.syncSerialNo(new GenSerialNoModel(MesPcnExtEnumUtil.COMMON_SN.TOQC_NO.getCode()), userName, organizeCode, 1);
        if (oneCodeResult != null && oneCodeResult.isSuccess()) {
            return oneCodeResult.getResultList().get(0).toString();
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.CLOUD_CALL_EXCEPTION.getCode())
                    .setErrorDetail("生成唯一工单号失败")
                    .build();
        }
    }

}
