package com.sw.mes.yb.mcs.service.impl;

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.dto.YbInspectDataToMcsDto;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.mcs.entity.CodingRecord;
import com.sw.mes.yb.mcs.event.EventPublishService;
import com.sw.mes.yb.mcs.event.RankResultEvent;
import com.sw.mes.yb.mcs.service.CodingRecordService;
import com.sw.mes.yb.mcs.service.PublishRankResultService;
import com.sw.mes.yb.plan.entity.PlanWaterLineManageRecord;
import com.sw.mes.yb.plan.service.PlanWaterLineManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PublishRankResultImpl implements PublishRankResultService {
    @Autowired
    @Lazy
    private FbFeignClients fbFeignClients;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private PlanWaterLineManageService planWaterLineManageService;

    @Autowired
    private DictionaryItemService dictionaryItemService;


    @Autowired
    @Qualifier("eventPublishService")
    private EventPublishService publishService;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    private CodingRecordService codingRecordService;
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void publishRankResult(RankResultDto rankResultDto) {
        try {

            /**
             * 匹配订单 - 匹配方棒已经排产的设备;
             * 评级-》圆棒评级，是否存在与方棒的圆棒评级关系表中
             * 长度是否满足订单的长度范围，规格，掺杂剂，型号是否满足
             *
             */
            SysLog syslog = null;
            try {
                //if ("正常".equals(rankResultDto.getGradeType())) {
//                PlanWaterLineManageRecord planWaterLineManageRecord = planWaterLineManageService.selectOneOrder(rankResultDto.getDopant(), rankResultDto.getConductiveType(), rankResultDto.getSpecs(), rankResultDto.getYbInspectDataToMcsDto().getProductType());
                PlanWaterLineManageRecord planWaterLineManageRecord = null;
                String ybLevel = "%" + rankResultDto.getProductRank() + "%";
                YbInspectData bySectionNo = ybInspectDataService.findBySectionNo(rankResultDto.getSectionNo());
                String resLevel = ybInspectDataService.getResistanceLevel(bySectionNo.getWRadialCentre());

                List<PlanWaterLineManageRecord> planWaterLineManageRecords = planWaterLineManageService.selectOrders(rankResultDto.getDopant(), rankResultDto.getConductiveType(), rankResultDto.getSpecs(),rankResultDto.getSideLengthRange(), ybLevel, "%" + resLevel + "%");
                 planWaterLineManageRecord = planWaterLineManageRecords.get(0);
//                if(null != planWaterLineManageRecords && planWaterLineManageRecords.size() > 0){
//                    for (PlanWaterLineManageRecord waterLineManageRecord : planWaterLineManageRecords) {
//                        String productType = rankResultDto.getYbInspectDataToMcsDto().getProductType();
//                        String[] split = waterLineManageRecord.getProductType().split(",");
//                        for (String s : split) {
//                            if(s.equals(productType)){
//                                planWaterLineManageRecord = waterLineManageRecord;
//                                break;
//                            }
//                        }
//                    }
//                }
                if (planWaterLineManageRecord != null) {
//                    rankResultDto.setOrderNo(planWaterLineManageRecord.getAufnr());
                    //更换下发的订单字段
                    rankResultDto.setWaterLineManageOrderNo(planWaterLineManageRecord.getAufnr());
                    YbInspectDataToMcsDto ybInspectDataToMcsDto = rankResultDto.getYbInspectDataToMcsDto();
                    //更换下发的订单字段
//                    ybInspectDataToMcsDto.setOrderNo(planWaterLineManageRecord.getAufnr());
                    ybInspectDataToMcsDto.setWaterLineManageOrderNo(planWaterLineManageRecord.getAufnr());
                    //todo  if(!StringUtils.isBlank(rankResultDto.getProductRank()) && rankResultDto.getProductRank().equals("晶昇A2") && !StringUtils.isBlank(rankResultDto.getSectionNo())){
//                        if(!StringUtils.isBlank(rankResultDto.getProductRank()) && rankResultDto.getProductRank().equals("A2") && !StringUtils.isBlank(rankResultDto.getSectionNo())){
//                            List<CodingRecord> codingRecordBySectionNo = codingRecordService.getCodingRecordBySectionNo(rankResultDto.getSectionNo());
//                            if(null != codingRecordBySectionNo && codingRecordBySectionNo.size() > 0){
//                                if(codingRecordBySectionNo.size() == 1 && (rankResultDto.getGradeType().equals("正常") || rankResultDto.getGradeType().equals("转规格"))){
//                                    rankResultDto.setGradeType("复测");
//                                    ybInspectDataToMcsDto.setGradeType("复测");
//                                }
//                            }
//                        }
                    rankResultDto.setYbInspectDataToMcsDto(ybInspectDataToMcsDto);
                }
                //}
            } catch (Exception e) {
                syslog = new SysLog();
                syslog.setResult(e.getMessage());
            }
            if (syslog != null) {
                syslog.setCreateTime(new Date());
                syslog.setType("error");
                syslog.setStatus(ResultCode.FAIL.getCode());
                syslog.setCreateUserId(BaseContextHandler.getUserID());
                syslog.setCreateUserName(BaseContextHandler.getUsername());
                syslog.setContent(JSON.toJSONString(rankResultDto));
                syslog.setMethodName("onApplicationEvent");
                syslog.setName("匹配方棒订单请求下发：" + rankResultDto.getSectionNo());
                syslog.setServerAddr("http://" + IpUtils.getLocalIP());
                syslog.setReqType("GET");
                syslog.setReqIp(IpUtils.getWebServiceReqIP());
                sysLogService.save(syslog);
            }

            //圆棒评级下发MCS信息中字段gradeType和type根据数据字典映射转换
            changeTypeForMcs(rankResultDto);

            publishService.publishEvent(new RankResultEvent(this, rankResultDto));
        } catch (Exception e) {
            log.error("圆棒评级下发出错：" + e.getMessage());
            e.printStackTrace();
        }
    }


    void changeTypeForMcs(RankResultDto rankResultDto){
        //圆棒评级下发MCS信息中字段gradeType和type根据数据字典映射转换
        List<DictionaryItem> itemList = dictionaryItemService.findItemByThemeValue("gradeTypeToType", true);
        Map<String, String> weightCoefficient = itemList.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue));
        String type = weightCoefficient.get(rankResultDto.getGradeType());
       /*注释美科业务逻辑 标棒最小长度 配置问题
        DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("standedLength", "标棒最小长度", true);
        BigDecimal standedLength = new BigDecimal(item.getValue());
        if (null != rankResultDto.getGradeType() && rankResultDto.getGradeType().equals("正常") && null != rankResultDto.getActualLength()){
            if (rankResultDto.getActualLength().compareTo(standedLength)>=0){
                rankResultDto.setType("标棒");
            }else {
                rankResultDto.setType("非标棒");
            }
        }else if (!rankResultDto.getGradeType().equals("正常")){
            rankResultDto.setType(type);
        }*/
    }


    @Override
    public void publishRankResult(YbInspectData inspectDataBase, BigDecimal actualWeight, BigDecimal theoryWeight) {
        if (actualWeight == null){
//            actualWeight = inspectDataBase.getActualWeight();
        }
        if (theoryWeight == null){
            theoryWeight = inspectDataBase.getTheoryWeight();
        }
        RankResultDto rankResultDto = new RankResultDto();
        YbInspectDataToMcsDto pinKuData = ybInspectDataService.getPinKuData(inspectDataBase, null);
        rankResultDto.setYbInspectDataToMcsDto(pinKuData);
        rankResultDto.setProductRank(inspectDataBase.getProductLevel());
        rankResultDto.setTestRank(inspectDataBase.getProductLevelExperiment());
        rankResultDto.setSectionNo(inspectDataBase.getSectionNo());
        //掺杂剂
        rankResultDto.setDopant(inspectDataBase.getDopant());
        //单晶规格
        rankResultDto.setSpecs(inspectDataBase.getProductTypeSecond());
        //导电型号
        rankResultDto.setConductiveType(inspectDataBase.getConductiveType());
        //单晶总长
        rankResultDto.setLength(inspectDataBase.getSpellBarLength());
        rankResultDto.setType(inspectDataBase.getSectionType());
        rankResultDto.setGradeType(inspectDataBase.getGradeType());
        rankResultDto.setActualLength(inspectDataBase.getActualLength());
        rankResultDto.setCrystalNo(inspectDataBase.getCrystalNo());
        rankResultDto.setData(inspectDataBase.getSectionType());
//        rankResultDto.setWareHouseLength(inspectDataBase.getWareHouseLength());
        rankResultDto.setActualWeight(actualWeight);
        rankResultDto.setTheoryWeight(theoryWeight);
        rankResultDto.setDiameterMin(inspectDataBase.getDiameterMin());
        rankResultDto.setDiameterMax(inspectDataBase.getDiameterMax());
//        rankResultDto.setDiameterJudge(inspectDataBase.getDiamDecide());
        rankResultDto.setDistortion(inspectDataBase.getDistortion());
        rankResultDto.setIsBevel(inspectDataBase.getIsBevel().toString());
//        rankResultDto.setFineDiameter(inspectDataBase.getFineDiameter());
//        rankResultDto.setFineCutLength(inspectDataBase.getFineCutLength());
        rankResultDto.setPiecewiseNum(inspectDataBase.getPiecewiseNum());
        rankResultDto.setSticksCount(inspectDataBase.getSticksCount());
        rankResultDto.setAgainNum(inspectDataBase.getAgainNum());
        rankResultDto.setHeadTailRecognition(inspectDataBase.getHeadTailRecognition());
//        rankResultDto.setIsSeeBottom(inspectDataBase.getIsSeeBottom());
//        rankResultDto.setLineMarking(inspectDataBase.getLineMarking());
        rankResultDto.setIsCutBack(inspectDataBase.getIsCutBack());
        this.publishRankResult(rankResultDto);
    }
}
