package com.sw.mes.fb.checkout.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.service.CrystalMaterialRelationService;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.core.entity.CrystalLossRecord;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.CrystalLossRecordService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.SeedMassageDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.enums.SeedMassageEnum;
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.core.utils.DateUtil;
import com.sw.mes.fb.aio.entity.EapGrindingRack;
import com.sw.mes.fb.aio.service.EapGrindingRackService;
import com.sw.mes.fb.checkout.dao.LossEntryRecordDao;
import com.sw.mes.fb.checkout.dto.LossRecordInfoDto;
import com.sw.mes.fb.checkout.dto.PdaLossRecordDto;
import com.sw.mes.fb.checkout.entity.LossEntryRecord;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.LossEntryRecordService;
import com.sw.mes.fb.utils.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class LossEntryRecordServiceImpl extends BaseServiceImpl<LossEntryRecord> implements LossEntryRecordService {
    LossEntryRecordDao dao;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private WipStorageService wipStorageService;


    @Autowired
    private YbFeignClients ybFeignService;

    @Autowired
    private EapGrindingRackService eapGrindingRackService;

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

    @Override
    public void saveLossRecordByPda(PdaLossRecordDto pdaLossRecordDto) {

	    if (StringUtils.isBlank(pdaLossRecordDto.getSectionNo())){
	        throw new RuntimeException("单晶编号为空！");
        }
        List<LossRecordInfoDto> lossRecordInfoDtoList = pdaLossRecordDto.getLossRecordInfoDtoList();
        Assert.notNull(lossRecordInfoDtoList, "损耗记录不存在");

        BigDecimal lossLength = BigDecimal.ZERO;
        for (LossRecordInfoDto lossRecordInfoDto : pdaLossRecordDto.getLossRecordInfoDtoList()){
            lossLength = lossLength.add(lossRecordInfoDto.getLossLength());
        }
        //查询站点信息
        List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(pdaLossRecordDto.getSectionNo());
        Assert.notNull(wipStorageList, "在制品记录不存在");
        BigDecimal remainingLength =BigDecimal.ZERO;
        String processName = wipStorageList.get(0).getProcessName();
        String type = "单晶损耗";
        String ybSectionNo = "";
        //当前非方棒检验 属于报废整个单晶
        if (StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.毛棒截断.getValue()) || StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.圆棒截断.getValue()) ||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.粘圆棒.getValue()) ||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.圆棒检验.getValue())||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.磨倒.getValue())||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.开方.getValue())){
            if ( StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.磨倒.getValue())|| StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.开方.getValue())){
                type = "切方损耗";
                ybSectionNo = pdaLossRecordDto.getSectionNo();
            }
            //整个报废，结束工单
            wipStorageService.outStation(pdaLossRecordDto.getSectionNo(),"-2",null,false,"PDA记录损耗报废整根单晶！");
        } else if (StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.方棒检验.getValue()) ||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.方棒截断.getValue()) ||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.粘方棒.getValue()) ){
            FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(pdaLossRecordDto.getSectionNo());
            if (null == dataByFbSectionNo){
                throw new RuntimeException("方棒检验信息不存在！");
            }
            ybSectionNo = dataByFbSectionNo.getYbSectionNo();
            dataByFbSectionNo.setReducedLength(lossLength);
            fbCheckOutDataService.saveOrUpdate(dataByFbSectionNo);
            if (lossLength.compareTo(dataByFbSectionNo.getLength()) >= 0){
                //整个报废，结束工单
                wipStorageService.outStation(pdaLossRecordDto.getSectionNo(),"-2",null,false,"PDA记录损耗报废整根单晶！");
            }else {
                remainingLength = dataByFbSectionNo.getLength().subtract(lossLength);
            }
            type = "切方损耗";
        }
        //保存记录
        LossEntryRecord lossEntryRecord = modelMapper.map(pdaLossRecordDto, LossEntryRecord.class);
        lossEntryRecord.setCreateTime(new Date());
        if (StringUtils.isBlank(lossEntryRecord.getCreateUser())){
            lossEntryRecord.setCreateUser(BaseContextHandler.getUsername());
        }
        lossEntryRecord.setProcessName(processName);
        lossEntryRecord.setLossInfo(JSONObject.toJSONString(pdaLossRecordDto.getLossRecordInfoDtoList()));
        StringBuffer lossType = new StringBuffer();
        StringBuffer lossLengthNew = new StringBuffer();
        for (LossRecordInfoDto lossRecordInfoDto : pdaLossRecordDto.getLossRecordInfoDtoList()){
            lossType.append(lossRecordInfoDto.getLossType()).append(",");
            lossLengthNew.append(lossRecordInfoDto.getLossLength()).append(",");
        }
        if (lossType.length() > 0) {
            lossType.deleteCharAt(lossType.length() - 1);
        }
        if (lossLengthNew.length() > 0) {
            lossLengthNew.deleteCharAt(lossLengthNew.length() - 1);
        }

        lossEntryRecord.setLossType(lossType.toString());
        lossEntryRecord.setLossLength(lossLengthNew.toString());
        lossEntryRecord.setRemainingLength(remainingLength);
        //上报晶彩数据
        this.handleRobotSeedMessage(lossEntryRecord,type,ybSectionNo);

        this.saveOrUpdate(lossEntryRecord);

    }



    private void handleRobotSeedMessage(LossEntryRecord lossEntryRecord,String type,String ybSectionNo){
	    if (null == lossEntryRecord){
	        return;
        }
        StringBuffer content = new StringBuffer();
        content.append(". [MES推送]晶棒损耗:").append("\n");
        content.append(". ").append(lossEntryRecord.getSectionNo()).append("\n");
        content.append(".时间：").append(DateUtil.formatDate1(lossEntryRecord.getCreateTime())).append("\n");
        content.append(". ").append(type).append("\n");
        content.append(".损耗工序：").append(lossEntryRecord.getProcessName()).append("\n");
        content.append(".损耗原因：").append(lossEntryRecord.getLossType()).append("\n");
        content.append(".损耗长度：").append(lossEntryRecord.getLossLength()).append("\n");
        content.append(".剩余长度：").append(lossEntryRecord.getRemainingLength()).append("\n");
        content.append(".录入人：").append(lossEntryRecord.getCreateUser()).append("\n");
        content.append(".备注：").append("\n");

        SeedMassageDto seedMassageDto = new SeedMassageDto();
        ArrayList<String> sceneList = new ArrayList<>();
        ArrayList<String> groupNameList = new ArrayList<>();
        sceneList.add("prod");
        String groupName = "切方长度损耗实时推送群";
        groupNameList.add(groupName);
        seedMassageDto.setContent(String.valueOf(content.toString()));

        seedMassageDto.setGroupName(groupNameList);
        String source = "晶棒损耗";
        seedMassageDto.setSource(source);
        seedMassageDto.setScene(sceneList);
        seedMassageDto.setStatus(SeedMassageEnum.GROUP);
	    ybFeignService.robotSeedMessage(seedMassageDto);

        //处理损耗记录
        CrystalLossRecord crystalLossRecord = new CrystalLossRecord();
        crystalLossRecord.setSectionNo(lossEntryRecord.getSectionNo());
        if (lossEntryRecord.getSectionNo().length()>= 16){
            crystalLossRecord.setCrystalNo(lossEntryRecord.getSectionNo().substring(0,16));
        }
        crystalLossRecord.setLossLength(new BigDecimal(lossEntryRecord.getLossLength()));
        crystalLossRecord.setRemainLength(lossEntryRecord.getRemainingLength());
        crystalLossRecord.setRodLength(crystalLossRecord.getLossLength().add(crystalLossRecord.getRemainLength()));
        crystalLossRecord.setLossProcessName(lossEntryRecord.getProcessName());
        crystalLossRecord.setMajorCategories(type);
        crystalLossRecord.setLossType(lossEntryRecord.getLossType());
        crystalLossRecord.setCreateName(lossEntryRecord.getCreateUser());
        crystalLossRecord.setCreateTime(lossEntryRecord.getCreateTime());
        crystalLossRecord.setYbSectionNo(ybSectionNo);
        if (StringUtils.isNotBlank(ybSectionNo)){
            EapGrindingRack eapGrindingRack = eapGrindingRackService.findTopBySnOrderByIdDesc(ybSectionNo);
            crystalLossRecord.setRollMachine(eapGrindingRack.getEquipNo());
        }
        ybFeignService.handleCrystalLossRecord(crystalLossRecord);
    }
    @Override
    public Result getVerifyScrapLoss(PdaLossRecordDto pdaLossRecordDto) {

        String sectionNo = pdaLossRecordDto.getSectionNo();
        Assert.notNull(sectionNo, "单晶编号不能为空");
        List<LossRecordInfoDto> lossRecordInfoDtoList = pdaLossRecordDto.getLossRecordInfoDtoList();
        Assert.notNull(lossRecordInfoDtoList, "损耗记录不存在!");

        BigDecimal lossLength = BigDecimal.ZERO;
        for (LossRecordInfoDto lossRecordInfoDto : pdaLossRecordDto.getLossRecordInfoDtoList()){
            lossLength = lossLength.add(lossRecordInfoDto.getLossLength());
        }
        if (lossLength.compareTo( BigDecimal.ZERO) == 0){
            return ResultGenerator.fail("损耗长度长度为零，请先核对损耗长度！");
        }
        //查询站点信息
        List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(sectionNo);
        Assert.notNull(wipStorageList, "在制品记录不存在！");

        String processName = wipStorageList.get(0).getProcessName();
        //当前非方棒检验 属于报废整个单晶
        if (StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.方棒检验.getValue()) ||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.方棒截断.getValue()) ||
                StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.粘方棒.getValue()) ){
            FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(pdaLossRecordDto.getSectionNo());
            Assert.notNull(dataByFbSectionNo, "方棒检验信息不存在！");
            if (null != dataByFbSectionNo.getLength() && dataByFbSectionNo.getLength().compareTo(lossLength) <= 0){
                return ResultGenerator.success("当前节点为：" + processName +",是否报废当前晶段，晶段编号为：" + sectionNo);
            }
        }else {
            Result result = ybFeignService.verifyScrapLoss(processName, lossLength, sectionNo);
            if (null == result){
                return ResultGenerator.fail("损耗校验为空！");
            }else if ( ResultCode.SUCCESS.getCode() == result.getCode()){
                return ResultGenerator.success(result.getData());
            }else {
                return ResultGenerator.fail(result.getMessage());
            }
        }
        return ResultGenerator.success("当前节点为：" + processName + ",损耗总长度为："  + lossLength);
    }
}
