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


import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
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.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.fls.dao.KfReturnMaterialDao;
import com.sw.mes.yb.fls.dto.KfReturnMaterialStatusDto;
import com.sw.mes.yb.fls.entity.KfReturnMaterial;
import com.sw.mes.yb.fls.service.KfReturnMaterialService;
import com.sw.mes.yb.fls.service.MesToFlsService;
import com.sw.mes.yb.fls.utils.ResultDto;
import com.sw.mes.yb.turnstore.entity.TurnstoreIn;
import com.sw.mes.yb.turnstore.entity.TurnstoreInItem;
import com.sw.mes.yb.turnstore.service.TurnstoreInItemService;
import com.sw.mes.yb.turnstore.service.TurnstoreInService;
import com.sw.mes.yb.turnstore.statics.EnumValues;
import com.sw.mes.yb.turnstore.statics.Utlis;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class KfReturnMaterialServiceImpl extends BaseServiceImpl<KfReturnMaterial> implements KfReturnMaterialService {
    KfReturnMaterialDao dao;

    @Autowired
    public void setDao(KfReturnMaterialDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    private TurnstoreInItemService turnstoreInItemService;
    @Autowired
    private WipStorageService wipStorageService;
    @Autowired
    private TurnstoreInService turnstoreInService;
    @Autowired
    private YbInspectDataService inspectDataBaseService;
    @Autowired
    private FbFeignClients fbFeignClients;
    @Autowired
    private MesToFlsService mesToFlsService;

    @Override
    public void confirm(KfReturnMaterial kfReturnMaterial) {
        //创建退料申请单
        String sectionNo = kfReturnMaterial.getSectionNo();
        String purpose = "0";
        String returnStation = "开方站";
        //添加判断非拒收单晶不能重复退料
        if (turnstoreInItemService.getIsReturnRecordBySectionNoList(Arrays.asList(sectionNo), purpose)) {
            throw new BusinessException("已申请或已入库的晶段不可重复退料！");
        }
        String stationKey = EnumValuesFactory.WipStorageCode.开方.getKey();
        //判断是否为方棒进站，否，不允许退站
        wipStorageService.selectWipStorage(sectionNo, stationKey, true);
        YbInspectData tempInspectDataBase = null;
        TurnstoreInItem resultTurnstoreInItem = null;
        if (StringUtils.equals(purpose, EnumValues.ReturnPurposeType.ROUND_ROD_INSPECTION.getValue())) {
            try {
                tempInspectDataBase = inspectDataBaseService.findBySectionNo(sectionNo);
                if (null == tempInspectDataBase) {
                    throw new BusinessException("周转库获取圆棒检验信息失败！");
                }
                //计算入库长度 入库重量
                resultTurnstoreInItem = setEntity(tempInspectDataBase, false, null);
                //入库长度=圆棒长度-细减长-崩晶线
                resultTurnstoreInItem.setInstoreLength(Utlis.getInstoreLength(resultTurnstoreInItem.getActualLength(), resultTurnstoreInItem.getFineCutLength(), resultTurnstoreInItem.getCollapseLine()));
                //入库重量
                resultTurnstoreInItem.setInstoreWeight(Utlis.getInstoreWeight(resultTurnstoreInItem.getProductTypeSecond(), resultTurnstoreInItem.getInstoreLength()));

            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("周转库获取晶棒检验信息失败！");
            }

        } else if (StringUtils.equals(purpose, EnumValues.ReturnPurposeType.SQUARE_ROD_INSPECTION.getValue())) {
            Result<FbCheckOutData> fbCheckOutDataByFbSectionNo = fbFeignClients.findFbCheckOutDataByFbSectionNo(sectionNo);
            if (fbCheckOutDataByFbSectionNo.getCode() == ResultCode.SUCCESS.getCode()) {
                FbCheckOutData fbCheckOutData = fbCheckOutDataByFbSectionNo.getData();
                if (null == fbCheckOutData) {
                    throw new BusinessException("周转库获取方棒检验信息失败！");
                }
                resultTurnstoreInItem = setEntity(null, true, fbCheckOutData);
            } else {
                throw new BusinessException(fbCheckOutDataByFbSectionNo.getMessage());
            }
        } else {
            throw new BusinessException("方棒退料去向存在问题！");
        }

        TurnstoreIn turnstoreIn = new TurnstoreIn();
        turnstoreIn.setPurpose(purpose);
        turnstoreIn.setReturnStation(returnStation);
        turnstoreIn.setType("方棒退料");
        List<TurnstoreInItem> items = new ArrayList<>();
        items.add(resultTurnstoreInItem);

        //添加判断，退回料修改需要判断是否存在申请入库和已入库的
        handleIsReturnRecordBySectionNoList(items, purpose);
        turnstoreInService.createIn(turnstoreIn, items);

        //修改退料状态为已确认
        kfReturnMaterial.setStatus("1");
        kfReturnMaterial.setUpdateTime(new Date());
        dao.save(kfReturnMaterial);

        //通知fls,呼叫agv
        KfReturnMaterialStatusDto kfReturnMaterialStatusDto = new KfReturnMaterialStatusDto();
        kfReturnMaterialStatusDto.setPort(kfReturnMaterial.getPort());
        kfReturnMaterialStatusDto.setResult(kfReturnMaterial.getStatus());
        kfReturnMaterialStatusDto.setRobotCode(kfReturnMaterial.getRobotCode());
        ResultDto resultDto = mesToFlsService.kfReturnMaterialStatusOut(kfReturnMaterialStatusDto);
        if (resultDto == null || resultDto.getStatus() == null || resultDto.getStatus() != 100){
            throw new BusinessException("通知smcs下料确认信息失败！" + resultDto.getMessage());
        }

    }


    public TurnstoreInItem setEntity(YbInspectData tempInspectDataBase, Boolean isFb, FbCheckOutData fbCheckOutData) {

        TurnstoreInItem entity = new TurnstoreInItem();
        if (isFb) {
            entity.setSectionNo(fbCheckOutData.getFbSectionNo());
            entity.setProductLevelSecond(fbCheckOutData.getExperiLevel());
            entity.setProductLevelExperiment(fbCheckOutData.getFbExperiLevel());
            entity.setProductTypeSecond(fbCheckOutData.getPlanSpecs());
            entity.setActualLength(fbCheckOutData.getLength());
            entity.setInstoreLength(fbCheckOutData.getInstoreLengthFb());
            entity.setActualWeight(fbCheckOutData.getWeight());
            entity.setInstoreWeight(fbCheckOutData.getTheoryWeightFb());
            entity.setSectionType(fbCheckOutData.getSpecification());
            entity.setReCheckType(fbCheckOutData.getReCheckType());
            entity.setBackCutType(null != fbCheckOutData.getRecutLength() && fbCheckOutData.getRecutLength().equals(0) ? "是" : "否");

        } else {
            entity.setSectionNo(tempInspectDataBase.getSectionNo());
            entity.setProductLevelSecond(tempInspectDataBase.getProductLevel());
            entity.setProductLevelExperiment(tempInspectDataBase.getProductLevelExperiment());
            entity.setProductTypeSecond(tempInspectDataBase.getProductTypeSecond());
            entity.setActualLength(tempInspectDataBase.getActualLength());
//            entity.setActualWeight(tempInspectDataBase.getActualWeight());
//            entity.setFineCutLength(tempInspectDataBase.getFineCutLength());
//            entity.setCollapseLine(tempInspectDataBase.getCollapseLine());
            entity.setSectionType(tempInspectDataBase.getSectionType());
            entity.setReCheckType(tempInspectDataBase.getReCheckType());
            entity.setBackCutType(null != tempInspectDataBase.getIsCutBack() && tempInspectDataBase.getIsCutBack().equals(1) ? "是" : "否");

        }
        return entity;
    }

    private void handleIsReturnRecordBySectionNoList(List<TurnstoreInItem> items, String purpose) {
        List<String> sectionNoList = Optional.ofNullable(items).orElse(new ArrayList<>()).stream().map(TurnstoreInItem::getSectionNo).collect(Collectors.toList());
        //添加判断非拒收单晶不能重复退料
        if (turnstoreInItemService.getIsReturnRecordBySectionNoList(sectionNoList, purpose)) {
            throw new RuntimeException("退库中，已申请或已入库的托号不可重复退料！");
        }
    }

}
