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

import com.sw.mes.base.system.entity.InventoryManageInfo;
import com.sw.mes.base.system.entity.InventoryManageLog;
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.core.annotation.ServiceLogs;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.entity.FbCheckOutData;
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.fb.checkout.dto.SpellValidationReturnDto;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.FbJoinService;
import com.sw.mes.fls.entity.ProductionBindingTray;
import com.sw.mes.fls.service.ProductionBindingTrayService;
import com.sw.mes.plan.dto.MatchOrderInfo;
import com.sw.mes.plan.service.FbProductionOrderService;
import com.sw.mes.wms.dto.*;
import com.sw.mes.wms.service.WmsToMesService;
import com.sw.mes.wms.utils.RequestWmsDto;
import com.sw.mes.wms.utils.RequestWmsUtils;
import com.sw.mes.wms.utils.ResultWmsDto;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: GaoXinJian
 * @Date: 2022-03-08 16:28
 */
@Slf4j
@Service
public class WmsToMesServiceImpl implements WmsToMesService {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private RequestWmsUtils requestWmsUtils;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private FbProductionOrderService fbProductionOrderService;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private InventoryManageLogService inventoryManageLogService;

    @Autowired
    private InventoryManageInfoService inventoryManageInfoService;
    /**
     * 托盘绑定service
     */
    @Autowired
    private ProductionBindingTrayService productionBindingTrayService;

    @Autowired
    private FbJoinService fbJoinService;

    @Autowired
    private YbFeignClients ybFeignClients;

    private final String returnAndCancel="/api/confirmCancelWarehousing";
    @Override
    public Result inventoryFeedback(FbInventoryFeedbackDto fbInventoryFeedbackDto) {
        List<String> crystalNoByTrayNo = productionBindingTrayService.findCrystalNoByTrayNo(fbInventoryFeedbackDto.getTrayNo());
        if (crystalNoByTrayNo == null || crystalNoByTrayNo.size() < 1 || crystalNoByTrayNo.get(0) == null || crystalNoByTrayNo.get(0).equals("")){
            return ResultGenerator.fail("托盘【"+fbInventoryFeedbackDto.getTrayNo()+"】,无对应晶段信息！");
        }
        String roundSn = crystalNoByTrayNo.get(0);
        //添加记录
        InventoryManageLog inventoryManageLog = toInventoryManageLog(fbInventoryFeedbackDto);
        inventoryManageLog.setCrystalType(1);
        inventoryManageLog.setRoundSn(roundSn);
        inventoryManageLog.setCreateBy("WMS推送");
        inventoryManageLog.setCreateTime(new Date());
        inventoryManageLogService.saveOrUpdate(inventoryManageLog);

        InventoryManageInfo inventoryManageInfo = inventoryManageInfoService.findOneByRoundSnAndCrystalTypeOrderByIdDesc(roundSn,1);
        if (inventoryManageInfo == null){
            inventoryManageInfo = new InventoryManageInfo();
        }
        FbRatingResultDto fbRatingResultDto = new FbRatingResultDto();
        switch (fbInventoryFeedbackDto.getMoveFlag()){
            case 1:
                break;
            case 2:
                inventoryManageInfo.setCrystalType(1);
                inventoryManageInfo.setRoundSn(roundSn);
                inventoryManageInfo.setTrayNo(fbInventoryFeedbackDto.getTrayNo());
                inventoryManageInfo.setStockCode(fbInventoryFeedbackDto.getStockCode());
                if (inventoryManageInfo.getId() == null){
                    inventoryManageInfo.setCreateBy("WMS推送");
                    inventoryManageInfo.setCreateTime(new Date());
                }else{
                    inventoryManageInfo.setUpdateBy("WMS推送");
                    inventoryManageInfo.setUpdateTime(new Date());
                }
                inventoryManageInfoService.saveOrUpdate(inventoryManageInfo);

                FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(roundSn);
                fbRatingResultDto = this.toInitDto(fbCheckOutData, null, null,null);

                break;
            case 3:
                break;
            case 4:
                if (inventoryManageInfo != null){
                    inventoryManageInfoService.delete(inventoryManageInfo.getId());
                }
                break;
        }


        return ResultGenerator.success(fbRatingResultDto);
    }


    public InventoryManageInfo toInventoryManageInfo(FbInventoryFeedbackDto entity) {
        return modelMapper.map(entity, InventoryManageInfo.class);
    }

    public InventoryManageLog toInventoryManageLog(FbInventoryFeedbackDto entity) {
        return modelMapper.map(entity, InventoryManageLog.class);
    }

    @Override
    public Result squareOrder(SquareOrderDto squareOrderDto) {
        SquareOrderResultDto resultDto = new SquareOrderResultDto();
        //查询检验数据库
        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(squareOrderDto.getFbSectionNo());
        resultDto.setFbSectionNo(squareOrderDto.getFbSectionNo());
        resultDto.setMatchFlag(1);
        //匹配订单编号
        OrderResultDto orderNo = getOrderNo(fbCheckOutData);
        if(orderNo != null){
            resultDto.setMatchFlag(0);
            resultDto.setOrderNo(orderNo.getOrderNo());
            resultDto.setProductId(orderNo.getProductId());
        }
        return ResultGenerator.success(resultDto);
    }


    /**
     * 匹配方棒订单编号
     * @param fbCheckOutData
     * @return
     */
    public OrderResultDto getOrderNo(FbCheckOutData fbCheckOutData){
        OrderResultDto orderResultDto = new OrderResultDto();
       if (fbCheckOutData != null) {
           //匹配料号
           MatchOrderInfo matchOrderInfo = fbProductionOrderService.matchOrder(fbCheckOutData.getFbSectionNo(), fbCheckOutData.getYbLevel() != null ? fbCheckOutData.getYbLevel() : fbCheckOutData.getProductLevel(), fbCheckOutData.getSpecification(),
                   fbCheckOutData.getConductionType(), fbCheckOutData.getDopant(), fbCheckOutData.getSticksCount(),
                   fbCheckOutData.getSticksCount() != null && fbCheckOutData.getSticksCount() > 1 ? fbCheckOutData.getSpellBarLength() : fbCheckOutData.getLength(),
                   fbCheckOutData.getOrderType(), fbCheckOutData.getCheckoutName(), fbCheckOutData.getProductLevelFb(), fbCheckOutData.getSectionType(),fbCheckOutData.getSideLengthRange());
           if (matchOrderInfo != null) {
               orderResultDto.setOrderNo(matchOrderInfo.getOrderNo());
               orderResultDto.setProductId(matchOrderInfo.getMaterialCode());
           }
       }
        return orderResultDto;
    }

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

    @Override
    public Result spellValidation(FbSpellValidationDto fbSpellValidationDto) {
        List<String> list = Arrays.asList(fbSpellValidationDto.getSectionNos().split(","));
        if (list == null || list.size() < 1){
            return ResultGenerator.fail("晶段编号组合异常，" + fbSpellValidationDto.getSectionNos());
        }
        Result<SpellValidationReturnDto> result = fbJoinService.spellValidation(list);
        if (result == null || result.getCode() == null || !result.getCode().equals(200)){
            return result;
        }

        return ResultGenerator.success();
    }

    public  FbRatingResultDto toInitDto(FbCheckOutData fbCheckOutData , Integer sticksCount, BigDecimal spellBarLength, String sectionCompose){
        //初始封装数据
        DecimalFormat df2 = new DecimalFormat("#.##");
        FbRatingResultDto fbRatingResultDto = new FbRatingResultDto();
        //查询检验数据库
        if (fbCheckOutData != null) {
            FbRatingResultOfDto fbRatingResultOfDto = new FbRatingResultOfDto();
            fbRatingResultOfDto.setFbSectionNo(fbCheckOutData.getFbSectionNo());
            fbRatingResultOfDto.setSectionCompose(fbCheckOutData.getSectionCompose());
            if(sectionCompose != null) {
                fbRatingResultOfDto.setSectionCompose(sectionCompose);
                fbCheckOutData.setSectionCompose(sectionCompose);
            }
            fbRatingResultOfDto.setSpecification(fbCheckOutData.getSpecification());
            ProductionBindingTray productionBindingTray = productionBindingTrayService.getByCrystalNo(fbRatingResultOfDto.getFbSectionNo());
            if (productionBindingTray != null){
                fbRatingResultOfDto.setTrayNo(productionBindingTray.getTrayNo());
            }
            fbRatingResultOfDto.setSectionType(fbCheckOutData.getSectionType());
            fbRatingResultOfDto.setLength(fbCheckOutData.getLength());
            fbRatingResultOfDto.setWeight(fbCheckOutData.getWeight());
            fbRatingResultOfDto.setDiameterMax(fbCheckOutData.getDiameterMax());
            fbRatingResultOfDto.setDiameterMin(fbCheckOutData.getDiameterMin());

            Result<YbInspectDataDto> fbInfoById = ybFeignClients.getInspectDataBaseBySectionNo(fbCheckOutData.getYbSectionNo());
            if (fbInfoById != null && "200".equals(fbInfoById.getCode()) && fbInfoById.getData() != null) {
                fbRatingResultOfDto.setBevel(String.valueOf(fbInfoById.getData().getIsBevel()));
                fbRatingResultOfDto.setPn(fbInfoById.getData().getDopant());
                fbRatingResultOfDto.setDistortion(df2.format(fbInfoById.getData().getDistortion()));
            }
            fbRatingResultOfDto.setFbExperiLevel(fbCheckOutData.getFbExperiLevel());
            fbRatingResultOfDto.setDirect("");
            fbRatingResultOfDto.setProductRank(fbCheckOutData.getProductLevel());
            fbRatingResultOfDto.setMark("");

            fbRatingResultOfDto.setSticksCount(String.valueOf(fbCheckOutData.getSticksCount()));
            fbRatingResultOfDto.setSpellBarLength(fbCheckOutData.getSpellBarLength());
            if (sticksCount != null){
                fbRatingResultOfDto.setSticksCount(String.valueOf(sticksCount));
                fbCheckOutData.setSticksCount(sticksCount);
            }
            if (spellBarLength != null) {
                fbRatingResultOfDto.setSpellBarLength(spellBarLength);
                fbCheckOutData.setSpellBarLength(spellBarLength);
            }
            fbRatingResultOfDto.setProductLevel(fbCheckOutData.getProductLevel());
            fbRatingResultOfDto.setYbLevel(fbCheckOutData.getYbLevel());
            fbRatingResultOfDto.setProductLevelFb(fbCheckOutData.getProductLevelFb());
            fbRatingResultOfDto.setSecond("二类".equals(fbCheckOutData.getProductLevelFb()) ? "是" : "否");
            fbRatingResultOfDto.setEnterTime("");
            fbRatingResultOfDto.setReCheckType(fbCheckOutData.getReCheckType());

            fbRatingResultDto.setSn(fbCheckOutData.getFbSectionNo());
            fbRatingResultDto.setGrade(fbCheckOutData.getProductLevelFb());
            fbRatingResultDto.setResultOf(fbRatingResultOfDto);
            OrderResultDto orderResultDto = getOrderNo(fbCheckOutData);
            if (orderResultDto != null) {
                fbRatingResultDto.setProductId(orderResultDto.getProductId());
                fbRatingResultDto.setOrderNo(orderResultDto.getOrderNo());
            }
        }

        return fbRatingResultDto;
    }

    @Override
    @ServiceLogs(description = "方棒入库取消确认")
    public ResultWmsDto ReturnAndCancel(ReturnAndCancelDto returnAndCancelDto) {
        return requestWmsUtils.postForWms(new RequestWmsDto(returnAndCancel,returnAndCancelDto));
    }
}
