package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.busi.bu3;

import cn.estsh.i3plus.ext.mes.api.base.IShiftExtService;
import cn.estsh.i3plus.ext.mes.api.base.bu3.ISxReworkRangeService;
import cn.estsh.i3plus.ext.mes.apiservice.dao.bu3.ISxBuPackageExtDao;
import cn.estsh.i3plus.ext.mes.icloud.sdk.IQmsReworkRangeCloud;
import cn.estsh.i3plus.ext.mes.pojo.model.SxPackSnReportModel;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxInsertReworkRangeModel;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxReworkRangeModel;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
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.bean.MesShift;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import com.alibaba.fastjson.JSONObject;
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.*;

/**
 * @PROJECT_NAME: i3plus-qms-panasonic
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2023-06-14 10:31
 */
@Slf4j
@Service
public class SxReworkRangeService implements ISxReworkRangeService {

    @Autowired
    private ISxBuPackageExtDao packageExtDao;

    @Autowired
    private IQmsReworkRangeCloud reworkRangeCloud;

    @Autowired
    private IShiftExtService shiftExtService;

    @Override
    public int updateConfigValidById(Long[] ids, Integer status, String userName) {

        BaseResultBean baseResultBean = reworkRangeCloud.updateReworkRangeValidByIdsWithMes(ids, status, userName);

        if(!baseResultBean.isSuccess()){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail(baseResultBean.getErrorMsg())
                    .build();
        }
        return 1;

        //if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
        //    throw ImppExceptionBuilder.newInstance()
        //            .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
        //            .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
        //            .setErrorDetail("启用，禁用枚举状态值[%s]未被定义", status)
        //            .build();
        //}
        //
        //String nowTime = TimeTool.getNowTime(true);
        //List<MesReworkRange> reworkRangeList = new ArrayList<>();
        //for (Long id : ids) {
        //    MesReworkRange reworkRangeDb = reworkRangeRepository.getById(id);
        //    if (reworkRangeDb == null || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == reworkRangeDb.getIsDeleted()) {
        //        throw ImppExceptionBuilder.newInstance()
        //                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
        //                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
        //                .setErrorDetail("ID【%s】记录不存在", id)
        //                .build();
        //    }
        //
        //    if(reworkRangeDb.getBindStatus() == MesExtEnumUtil.REWORK_RANGE_IS_BAND.YES.getValue()){
        //        throw ImppExceptionBuilder.newInstance()
        //                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
        //                .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
        //                .setErrorDetail("包装条码【%s】已关联返工工单【%s】,无法%s", reworkRangeDb.getPackageNo(), reworkRangeDb.getWorkOrderNo(),  MesExtEnumUtil.IS_ENABLE.valueOfDescription(status))
        //               .build();
        //    }
        //
        //    reworkRangeDb.setIsValid(status);
        //    reworkRangeDb.setModifyDatetime(nowTime);
        //    reworkRangeDb.setModifyUser(userName);
        //    ConvertBean.serviceModelUpdate(reworkRangeDb, userName);
        //    reworkRangeList.add(reworkRangeDb);
        //}
        //
        //reworkRangeRepository.saveAll(reworkRangeList);
        //return 1;
    }

    @Override
    public ListPager queryMesReworkRangeByPager(SxReworkRangeModel reworkRange, Pager pager) {
        reworkRange.setPager(pager);
        BaseResultBean baseResultBean = reworkRangeCloud.queryReworkRangeListByPager(reworkRange);

        if(!baseResultBean.isSuccess()){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail(baseResultBean.getErrorMsg())
                    .build();
        }
        ListPager listPager = baseResultBean.getListPager();
        List<LinkedHashMap> resultObject = listPager.getObjectList();
        List<SxReworkRangeModel> reworkRangeModelList = JsonUtilTool.toList(JSONObject.toJSONString(resultObject), SxReworkRangeModel.class);
        if(!CollectionUtils.isEmpty(reworkRangeModelList)){
            Map<String, MesShift> shiftCodeMap = shiftExtService.queryShiftMap(reworkRange.getOrganizeCode());
            for (SxReworkRangeModel reworkRangeModel : reworkRangeModelList) {
                if(StringUtils.isEmpty(reworkRangeModel.getWorkCenterCode()) || StringUtils.isEmpty(reworkRangeModel.getShiftCode())) continue;
                String key = new StringJoiner(MesExtConstWords.AND).add(reworkRangeModel.getWorkCenterCode()).add(reworkRangeModel.getShiftCode()).toString();
                if(!CollectionUtils.isEmpty(shiftCodeMap) && shiftCodeMap.containsKey(key)) reworkRangeModel.setShiftName(shiftCodeMap.get(key).getShiftName());
            }
        }
        baseResultBean.setListPager(new ListPager(reworkRangeModelList, listPager.getObjectPager()));
        return baseResultBean.getListPager();

        //if (!StringUtils.isEmpty(reworkRange.getYearMonth())) {
        //    DdlPackBean packBean = MesExtHqlPack.getReworkRange(reworkRange);
        //    DdlPreparedPack.getStringRightLikerPack(reworkRange.getYearMonth(), MesExtConstWords.WORK_TIME, packBean);
        //    List<MesReworkRange> reworkRangeList = reworkRangeRepository.findByHqlWhere(packBean);
        //
        //    if (CollectionUtils.isEmpty(reworkRangeList)) return new ListPager<>(new ArrayList<>(), pager);
        //
        //    BuNumberRuleModel numberRuleModel = baseDataService.queryMesSnRule(reworkRange.getOrganizeCode(), reworkRange.getPartNo(), MesExtEnumUtil.ENCODE_CODE_TYPE.PACK_SN.getValue(),
        //            MesExtEnumUtil.ENCODE_MATCH_TYPE.PART.getValue());
        //
        //    if(numberRuleModel == null){
        //        throw ImppExceptionBuilder.newInstance()
        //                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
        //                .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
        //                .setErrorDetail("物料编码{}未配置生产编码规则",reworkRange.getPartNo())
        //                .build();
        //    }
        //
        //    if("{serialnumber}".equals(numberRuleModel.getNumberRule())){
        //        numberRuleModel = baseDataService.queryMesSnRule(reworkRange.getOrganizeCode(), reworkRange.getPartNo(), MesExtEnumUtil.ENCODE_CODE_TYPE.STANDARD_SERIAL_SN.getValue(),
        //                MesExtEnumUtil.ENCODE_MATCH_TYPE.PART.getValue());
        //    }
        //
        //    //编码规则
        //    String[] serialNoArray = numberRuleModel.getNumberRule().split("}\\{");
        //    //规则属性长度拼接
        //    String[] ruleLengthSpiltArray = numberRuleModel.getRuleLengthSpilt().split(",");
        //    String year = "year";
        //    String month = "month";
        //    String serialNoStr = "serialno";
        //    int serialNoIndex = -1;
        //    int yearIndex = -1;
        //    int monthIndex = -1;
        //    for (int index = 0; index < serialNoArray.length; index++) {
        //        if(serialNoArray[index].contains(serialNoStr)) serialNoIndex = index;
        //        if(serialNoArray[index].contains(year)) yearIndex = index;
        //        if(serialNoArray[index].contains(month)) monthIndex = index;
        //    }
        //
        //    int ruleLengthTotal = 0;
        //    if(serialNoIndex != -1){
        //        for (int index = 0; index < serialNoIndex; index++) {
        //            ruleLengthTotal += Integer.parseInt(ruleLengthSpiltArray[index]);
        //        }
        //    }
        //
        //    int yearLengthTotal = 0;
        //    if(yearIndex != -1){
        //        for (int index = 0; index < yearIndex; index++) {
        //            yearLengthTotal += Integer.parseInt(ruleLengthSpiltArray[index]);
        //        }
        //    }
        //
        //    int monthLengthTotal = 0;
        //    if(monthIndex != -1){
        //        for (int index = 0; index < monthIndex; index++) {
        //            monthLengthTotal += Integer.parseInt(ruleLengthSpiltArray[index]);
        //        }
        //    }
        //
        //    int finalRuleLengthTotal = ruleLengthTotal;
        //    int finalSerialNoIndex = serialNoIndex;
        //    int finalYearLengthTotal = yearLengthTotal;
        //    int finalYearIndex = yearIndex;
        //    int finalMonthLengthTotal = monthLengthTotal;
        //    int finalMonthIndex = monthIndex;
        //
        //    String yearMonth = reworkRange.getYearMonth();
        //    int selectYear = Integer.parseInt(yearMonth.substring(4 - Integer.parseInt(ruleLengthSpiltArray[yearIndex]), 4));
        //    int selectMonth = Integer.parseInt(yearMonth.substring(5 + (2 - Integer.parseInt(ruleLengthSpiltArray[monthIndex]))));
        //    if (!StringUtils.isEmpty(reworkRange.getBatchLimitStart()) && !StringUtils.isEmpty(reworkRange.getBatchLimitEnd())) {
        //        reworkRangeList = reworkRangeList.stream().filter(oqcCheckPackageDetail -> {
        //                    try {
        //                        return selectYear == Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalYearLengthTotal, finalYearLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalYearIndex]))) &&
        //                            selectMonth == Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalMonthLengthTotal, finalMonthLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalMonthIndex]))) &&
        //                            reworkRange.getBatchLimitStart() <= Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalRuleLengthTotal, finalRuleLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalSerialNoIndex]))) &&
        //                            reworkRange.getBatchLimitEnd() >= Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalRuleLengthTotal, finalRuleLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalSerialNoIndex])));
        //                    } catch (NumberFormatException e) {
        //                        return false;
        //                    }
        //                }
        //        ).collect(Collectors.toList());
        //    } else if(!StringUtils.isEmpty(reworkRange.getBatchLimitStart())){
        //        reworkRangeList = reworkRangeList.stream().filter(oqcCheckPackageDetail -> {
        //                    try {
        //                        return selectYear == Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalYearLengthTotal, finalYearLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalYearIndex]))) &&
        //                                selectMonth == Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalMonthLengthTotal, finalMonthLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalMonthIndex]))) &&
        //                                reworkRange.getBatchLimitStart() <= Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalRuleLengthTotal, finalRuleLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalSerialNoIndex])));
        //                    } catch (NumberFormatException e) {
        //                        return false;
        //                    }
        //                }
        //        ).collect(Collectors.toList());
        //    } else if(!StringUtils.isEmpty(reworkRange.getBatchLimitEnd())){
        //        reworkRangeList = reworkRangeList.stream().filter(oqcCheckPackageDetail -> {
        //                    try {
        //                        return selectYear == Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalYearLengthTotal, finalYearLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalYearIndex]))) &&
        //                                selectMonth == Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalMonthLengthTotal, finalMonthLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalMonthIndex]))) &&
        //                                reworkRange.getBatchLimitEnd() >= Integer.parseInt(oqcCheckPackageDetail.getSerialNumber().substring(finalRuleLengthTotal, finalRuleLengthTotal + Integer.parseInt(ruleLengthSpiltArray[finalSerialNoIndex])));
        //                    } catch (NumberFormatException e) {
        //                        return false;
        //                    }
        //                }
        //        ).collect(Collectors.toList());
        //    }
        //    pager = PagerHelper.getPager(pager, reworkRangeList.size());
        //    reworkRangeList = reworkRangeList.stream().skip((long) (pager.getCurrentPage() - 1) * pager.getPageSize()).limit(pager.getPageSize()).collect(Collectors.toList());
        //    reworkRangeList.forEach(o -> {
        //        if(o.getPackageNo().equals(o.getOuterPackageNo())){
        //            if(o.getPackageNo().equals(o.getOuterPackageNo())){
        //                o.setOuterPackageNoShow("");
        //            }else{
        //                o.setOuterPackageNoShow(o.getOuterPackageNo());
        //            }
        //        }
        //    });
        //    return new ListPager<>(reworkRangeList, pager);
        //} else {
        //    DdlPackBean packBean = MesExtHqlPack.getReworkRange(reworkRange);
        //    pager = PagerHelper.getPager(pager, reworkRangeRepository.findByHqlWhereCount(packBean));
        //    List<MesReworkRange> reworkRangeDbList = reworkRangeRepository.findByHqlWherePage(packBean, pager);
        //    reworkRangeDbList.forEach(o -> {
        //        if(o.getPackageNo().equals(o.getOuterPackageNo())){
        //            o.setOuterPackageNoShow("");
        //        }else{
        //            o.setOuterPackageNoShow(o.getOuterPackageNo());
        //        }
        //    });
        //    return new ListPager<>(reworkRangeDbList, pager);
        //}
    }

    @Override
    public ListPager<SxPackSnReportModel> queryStandardWorkOrderPackSnPager(SxPackSnReportModel model, Pager pager) {
        pager = PagerHelper.getPager(pager, packageExtDao.queryStandardWorkOrderPackSnPagerCount(model));
        List<SxPackSnReportModel> packSnReportModelList = packageExtDao.queryStandardWorkOrderPackSnPager(model, pager);

        Map<String, MesShift> shiftCodeMap = shiftExtService.queryShiftMap(model.getOrganizeCode());

        for (SxPackSnReportModel sxPackSnReportModel : packSnReportModelList) {
            sxPackSnReportModel.setShiftName(shiftCodeMap.containsKey(sxPackSnReportModel.getShiftCode()) ? shiftCodeMap.get(sxPackSnReportModel.getShiftCode()).getShiftName() : "");
        }
        return new ListPager(packSnReportModelList, pager);
    }

    @Override
    public List<SxPackSnReportModel> queryStandardWorkOrderPackSn(SxPackSnReportModel model) {
        log.info("queryStandardWorkOrderPackSn --- 参数：{}", model);
        List<SxPackSnReportModel> sxPackSnReportModels = packageExtDao.queryStandardWorkOrderPackSnList(model);

        log.info("queryStandardWorkOrderPackSn --- 结果集数：{}", sxPackSnReportModels.size());
        return sxPackSnReportModels;
    }

    @Override
    public void insertMesReworkRange(String organizeCode, List<SxPackSnReportModel> sxPackSnReportModelList) {
        //List<String> packageNoList = sxPackSnReportModelList.stream().map(SxPackSnReportModel::getPackageNo).collect(Collectors.toList());
        ////根据包装条码获取大包装条码信息
        //DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        //DdlPreparedPack.getInPackList(packageNoList, MesExtConstWords.INNER_PACKAGE_NO, packBean);
        //List<MesOuterPackageDetail> outerPackageDetailList = outerPackageDetailRepository.findByHqlWhere(packBean);
        //Map<String, MesOuterPackageDetail> outerPackageDetailByPackNoMap = outerPackageDetailList.stream().collect(Collectors.toMap(MesOuterPackageDetail::getInnerPackageNo, Function.identity(), (x,y) -> y));
        //List<MesReworkRange> reworkRangeList = new ArrayList<>();
        //for (SxPackSnReportModel sxPackSnReportModel : sxPackSnReportModelList) {
        //    MesReworkRange reworkRange = new MesReworkRange();
        //    BeanUtils.copyProperties(sxPackSnReportModel, reworkRange, MesExtConstWords.ID, MesExtConstWords.CREATE_USER, MesExtConstWords.CREATE_DATE_TIME, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.CREATE_USER);
        //    reworkRange.setPartName(sxPackSnReportModel.getPartNameRdd());
        //    reworkRange.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        //    reworkRange.setBindStatus(MesExtEnumUtil.PACKAGE_BIND_STATUS.UNBIND.getValue());
        //    MesOuterPackageDetail mesOuterPackageDetail = outerPackageDetailByPackNoMap.get(sxPackSnReportModel.getPackageNo());
        //    if(mesOuterPackageDetail != null) {
        //        reworkRange.setOuterPackageNo(mesOuterPackageDetail.getOuterPackageNo());
        //    }else{
        //        reworkRange.setOuterPackageNo(reworkRange.getPackageNo());
        //    }
        //    reworkRangeList.add(reworkRange);
        //}
        //if(!CollectionUtils.isEmpty(reworkRangeList)) reworkRangeRepository.saveAll(reworkRangeList);

        BaseResultBean baseResultBean = reworkRangeCloud.insertSxQmsReworkRangeWithMes(new SxInsertReworkRangeModel(sxPackSnReportModelList, organizeCode));
        if(!baseResultBean.success){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail(baseResultBean.getErrorMsg())
                    .build();
        }
    }
}
