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

import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.InventoryManageInfo;
import com.sw.mes.base.system.entity.InventoryManageLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.InventoryManageInfoService;
import com.sw.mes.base.system.service.InventoryManageLogService;
import com.sw.mes.base.workinprocess.dto.CurrentWipStorageStatusDto;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.config.rabbit.WmsRatingResultsMsgProducer;
import com.sw.mes.core.annotation.ServiceLogs;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.pc.entity.Section;
import com.sw.mes.yb.pc.service.SectionService;
import com.sw.mes.yb.turnstore.entity.ProductionBindingTray;
import com.sw.mes.yb.turnstore.service.ProductionBindingTrayService;
import com.sw.mes.yb.wms.dto.*;
import com.sw.mes.yb.wms.service.RatingResultService;
import com.sw.mes.yb.wms.utils.RequestWmsDto;
import com.sw.mes.yb.wms.utils.RequestWmsUtils;
import com.sw.mes.yb.wms.utils.ResultWmsDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: GaoXinJian
 * @Date: 2022-03-08 16:28
 */
@Slf4j
@Service
public class RatingResultServiceImpl implements RatingResultService {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    private RequestWmsUtils RequestUtilsWms;
    @Autowired
    InventoryManageInfoService inventoryManageInfoService;
    @Autowired
    InventoryManageLogService inventoryManageLogService;
    @Autowired
    ProductionBindingTrayService productionBindingTrayService;
    @Autowired
    YbInspectDataService inspectDataBaseService;
    @Autowired
    @Lazy
    private FbFeignClients fbFeignClients;
    @Autowired
    private SectionService sectionService;
    @Autowired
    private WipStorageService wipStorageService;
    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Lazy
    @Autowired
    private WmsRatingResultsMsgProducer wmsRatingResultsMsgProducer;

    private final String rankResultUrl="/rankResult";
    private final String roundSNReverseUrl="/api/MES/roundSNReverse";
    private final String finshOrder="/api/MES/roundSNReverse";

    @Override
    @ServiceLogs(description = "圆棒评级结果下发wms")
    public ResultWmsDto ratingResult(RankResultDto rankResultDto) {
//        return RequestUtilsWms.postForWms(new RequestWmsDto(rankResultUrl,rankResultDto));
        ResultWmsDto resultWmsDto = null;
        DictionaryItem dictionaryItem = dictionaryItemService.findByThemeValueAndNameAndEnable("PushWmsRatingResult", "pushState", true);
        if(dictionaryItem == null || "1".equals(dictionaryItem.getValue()) || "3".equals(dictionaryItem.getValue())){
            wmsRatingResultsMsgProducer.sendMsgInspectData(rankResultDto);
            resultWmsDto = new ResultWmsDto(200, "", "");
        }

        if(dictionaryItem == null || "1".equals(dictionaryItem.getValue()) || "2".equals(dictionaryItem.getValue())){
            resultWmsDto = RequestUtilsWms.postForWms(new RequestWmsDto(rankResultUrl, rankResultDto, 2));
        }
        return resultWmsDto;
    }

    @Override
    public ResultWmsDto roundSNReverse(WmsRequest<RoundSNReverseDto> roundSNReverseDto) {
        return RequestUtilsWms.postForWms(new RequestWmsDto(roundSNReverseUrl,roundSNReverseDto.getBody()));
    }

    @Override
    public Result inventoryFeedback(WmsRequest<Body> inventoryFeedbackDto) {
        //添加记录
        InventoryManageLog inventoryManageLog = toInventoryManageLog(inventoryFeedbackDto);
        inventoryManageLog.setCrystalType(0);
        inventoryManageLog.setCreateBy("WMS推送");
        inventoryManageLog.setCreateTime(new Date());
        inventoryManageLogService.saveOrUpdate(inventoryManageLog);

        InventoryManageInfo inventoryManageInfo = inventoryManageInfoService.findOneByRoundSnAndCrystalTypeOrderByIdDesc(inventoryFeedbackDto.getBody().getRoundSn(),0);
        if (inventoryManageInfo == null){
            inventoryManageInfo = new InventoryManageInfo();
        }
        inventoryManageInfo.setCrystalType(0);
        RatingResultDto ratingResultDto = new RatingResultDto();
        switch (inventoryFeedbackDto.getBody().getMoveFlag()){
            case 1:
                break;
            case 2:
                if (inventoryManageInfo.getId() == null){
                    inventoryManageInfo.setRoundSn(inventoryFeedbackDto.getBody().getRoundSn());
                    inventoryManageInfo.setStockCode(inventoryFeedbackDto.getBody().getStockCode());
                    inventoryManageInfo.setCreateBy("WMS推送");
                    inventoryManageInfo.setCreateTime(new Date());
                }else{
                    inventoryManageInfo.setUpdateBy("WMS推送");
                    inventoryManageInfo.setUpdateTime(new Date());
                }
                inventoryManageInfoService.saveOrUpdate(inventoryManageInfo);
                //查询托盘绑定信息
                ProductionBindingTray productionBindingTray = productionBindingTrayService.getByCrystalNo(inventoryFeedbackDto.getBody().getRoundSn());
                //查询检验数据库
                YbInspectData inspectDataBase = inspectDataBaseService.findBySectionNo(inventoryFeedbackDto.getBody().getRoundSn());
                if (inspectDataBase != null){
                    ratingResultDto.setSectionNo(inspectDataBase.getCrystalNo());
                    ratingResultDto.setRoundSn(inspectDataBase.getSectionNo());
                    ratingResultDto.setProductLevel(inspectDataBase.getProductLevel());
                    ratingResultDto.setProductLevelExperiment(inspectDataBase.getProductLevelExperiment());
                    ratingResultDto.setData(inspectDataBase.getSectionType());
                    ratingResultDto.setSectionType(inspectDataBase.getSectionType());
                    ratingResultDto.setProductType(inspectDataBase.getProductTypeSecond());
//                    ratingResultDto.setWareHouseLength(inspectDataBase.getWareHouseLength());
                    ratingResultDto.setActualLength(inspectDataBase.getActualLength());
                    ratingResultDto.setSpellBarLength(inspectDataBase.getSpellBarLength());
//                    ratingResultDto.setActualWeight(inspectDataBase.getActualWeight());
                    ratingResultDto.setTheoryWeight(inspectDataBase.getTheoryWeight());
                    ratingResultDto.setDiameterMin(inspectDataBase.getDiameterMin());
                    ratingResultDto.setDiameterMax(inspectDataBase.getDiameterMax());
//                    ratingResultDto.setDiameterJudge(inspectDataBase.getDiamDecide());
                    ratingResultDto.setDistortion(inspectDataBase.getDistortion());
                    ratingResultDto.setIsBevel(inspectDataBase.getIsBevel().toString());
                    ratingResultDto.setConductiveType(inspectDataBase.getConductiveType());
//                    ratingResultDto.setFineDiameter(inspectDataBase.getFineDiameter());
//                    ratingResultDto.setFineCutLength(inspectDataBase.getFineCutLength());
                    ratingResultDto.setPiecewiseNum(inspectDataBase.getPiecewiseNum());
                    ratingResultDto.setAgainNum(inspectDataBase.getAgainNum());
                    ratingResultDto.setHeadTailRecognition(inspectDataBase.getHeadTailRecognition());
//                    ratingResultDto.setIsSeeBottom(inspectDataBase.getIsSeeBottom());
//                    ratingResultDto.setLineMarking(inspectDataBase.getLineMarking());
                    String orderNo = getOrderNo(inspectDataBase);
//                    ratingResultDto.setIsCutBack(inspectDataBase.getIsCutBack());
                    ratingResultDto.setOrderNo(orderNo);
                    if (inspectDataBase.getSticksCount() != null && inspectDataBase.getSticksCount() > 1) {
                        //查询粘圆棒整棒信息
                        Section section = sectionService.findBySectionNo(inspectDataBase.getSectionNo());
                        if (section != null){
                            ratingResultDto.setActualWeight(section.getActualWeight());
                            ratingResultDto.setTheoryWeight(section.getTheoryWeight());
                        }
                    }
                }
                if (productionBindingTray != null){
                    ratingResultDto.setTrayCode(productionBindingTray.getTrayNo());
                }
                //查询当前站点
                try {
                Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(inventoryFeedbackDto.getBody().getRoundSn());
                    if (currentWipStorageStatusDtoResult.getCode() == ResultCode.SUCCESS.getCode() && currentWipStorageStatusDtoResult.getData() != null) {
                        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
                        ratingResultDto.setWipStorage(currentWipStorageStatusDto.getWipStorageCodeName() + ":" + currentWipStorageStatusDto.getWipStorageStatusName());
                    }
                }catch(Exception e){

                }

//                //入库解锁晶棒（由wms调用）
//                OrderLockDto orderLockDto = new OrderLockDto();
//                OrderLockBodyDto orderLockBodyDto = new OrderLockBodyDto();
//                orderLockBodyDto.setLock(0);
//                orderLockBodyDto.setRoundSns(inventoryFeedbackDto.getBody().getRoundSn());
//                orderLockDto.setBody(orderLockBodyDto);
//                this.dealLockOrder(orderLockDto);
                break;
            case 3:
                break;
            case 4:
                if (inventoryManageInfo != null && inventoryManageInfo.getId() != null){
                    inventoryManageInfoService.delete(inventoryManageInfo.getId());
                }
                break;
            case 5:
                if (inventoryManageInfo != null && inventoryManageInfo.getId() != null){
                    inventoryManageInfoService.delete(inventoryManageInfo.getId());
                }
                break;
            case 6:
                if (inventoryManageInfo != null && inventoryManageInfo.getId() != null){
                    inventoryManageInfoService.delete(inventoryManageInfo.getId());
                }
                break;
        }

        return ResultGenerator.success(ratingResultDto);
    }


    public InventoryManageInfo toInventoryManageInfo(WmsRequest<Body> entity) {
        return modelMapper.map(entity.getBody(), InventoryManageInfo.class);
    }

    public InventoryManageLog toInventoryManageLog(WmsRequest<Body> entity) {
        return modelMapper.map(entity.getBody(), InventoryManageLog.class);
    }

    @Override
    public Result squareOrder(WmsRequest<SquareOrderBodyDto>  squareOrderDto) {
        SquareOrderResultDto resultDto = new SquareOrderResultDto();
        //查询检验数据库
        YbInspectData inspectDataBase = inspectDataBaseService.findBySectionNo(squareOrderDto.getBody().getRoundSn());
        resultDto.setRoundSn(squareOrderDto.getBody().getRoundSn());
        resultDto.setMatchFlag(1);
        //匹配订单编号
        String orderNo = getOrderNo(inspectDataBase);
        if(StringUtils.isNotEmpty(orderNo)){
            resultDto.setMatchFlag(0);
            resultDto.setOrderNo(orderNo);
        }
        return ResultGenerator.success(resultDto);
    }


    /**
     * 匹配订单编号（方棒）
     * @param inspectDataBase
     * @return
     */
    public String getOrderNo(YbInspectData inspectDataBase){
       String orderNo = null;
        if (inspectDataBase != null){
            RankResultDto rankResultDto = new RankResultDto();
            rankResultDto.setSectionNo(inspectDataBase.getSectionNo());
            rankResultDto.setProductRank(inspectDataBase.getProductLevel());
            rankResultDto.setTestRank(inspectDataBase.getProductLevelExperiment());
            rankResultDto.setType(inspectDataBase.getSectionType());
            rankResultDto.setGradeType(inspectDataBase.getGradeType());
            rankResultDto.setSpecs(inspectDataBase.getProductTypeSecond());
            rankResultDto.setConductiveType(inspectDataBase.getConductiveType());
            rankResultDto.setDopant(inspectDataBase.getDopant());
            if(inspectDataBase.getSticksCount() != null &&inspectDataBase.getSticksCount() > 1){
                rankResultDto.setLength(inspectDataBase.getSpellBarLength());
            }else{
                rankResultDto.setLength(inspectDataBase.getActualLength());
            }
            if ("标棒".equals(rankResultDto.getType()) && "正常".equals(rankResultDto.getGradeType())) {
                Result<String> result = fbFeignClients.findProductionScheduleCodePro(rankResultDto);
                if (result.getCode() == ResultCode.SUCCESS.getCode() && result.getData() != null && StringUtils.isNotBlank(result.getData())) {
                    orderNo = result.getData();
                }
            }
        }
        return orderNo;
    }

    @Override
    public Result dealLockOrder(WmsRequest<OrderLockBodyDto> orderLockDto) {
        String[] roundSns = orderLockDto.getBody().getRoundSns().split(",");
        for (String sectionNo : roundSns){
            //查询当前站点
            Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(sectionNo);
            if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
                throw new BusinessException("查询站点信息失败");
            }
            if (currentWipStorageStatusDtoResult.getData() == null) {
                throw new BusinessException("站点信息为空");
            }
            CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
            //锁定
            if (orderLockDto.getBody().getLock() != null && orderLockDto.getBody().getLock().equals(1)){
                if (currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.圆棒检验.getKey())
                        && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.已进站.getKey()
                ) {
                    //过站到粘圆棒进站状态（用于卡控自动状态下，以生成拼棒订单后仍然自动评级）
                    wipStorageService.outStation(sectionNo, "E", EnumValuesFactory.WipStorageStatus.已进站.getKey());
                }
            //解锁
            }else if(orderLockDto.getBody().getLock() != null && orderLockDto.getBody().getLock().equals(0)){
                if (currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.粘圆棒.getKey())
                        && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.已进站.getKey()
                ){
//                    InspectDataBase inspectDataBase = inspectDataBaseService.findBySectionNo(sectionNo);
//                    if (inspectDataBase.getSticksCount() != null && inspectDataBase.getSticksCount() <= 1){
                    wipStorageService.outStation(sectionNo, "A", EnumValuesFactory.WipStorageStatus.已进站.getKey());
//                    }
                }
            }else {
                throw new BusinessException("状态标识错误！" + orderLockDto.getBody().getLock());
            }
        }
        return ResultGenerator.success();
    }
}
