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


import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.fb.checkout.entity.FbCheckOutRecord;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.FbCheckOutRecordService;
import com.sw.mes.fb.productChangeRecord.dao.ProductChangeRecordDao;
import com.sw.mes.fb.productChangeRecord.dto.ProductChangeBatchDto;
import com.sw.mes.fb.productChangeRecord.entity.ProductChangeRecord;
import com.sw.mes.fb.productChangeRecord.service.ProductChangeRecordService;
import com.sw.mes.fb.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class ProductChangeRecordServiceImpl extends BaseServiceImpl<ProductChangeRecord> implements ProductChangeRecordService {
    ProductChangeRecordDao dao;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private FbCheckOutRecordService fbCheckOutRecordService;




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

    @Override
    public ProductChangeBatchDto getBatchInfo(String sectionNoList) {

	    if (StringUtils.isBlank(sectionNoList)){
	        throw new RuntimeException("传入参数为空!");
        }
	    List<String> sectionNoListResult = new ArrayList<>();
        String[] split = sectionNoList.split(",");
        for (String sectionNoStr : split) {
            if (StringUtils.isNotBlank(sectionNoStr)){
                sectionNoListResult.add(sectionNoStr.trim());
            }
        }
        FbCheckOutData fbCheckOutDataPre = null;

        Integer index = 0;
        ProductChangeBatchDto productChangeBatchDto = new ProductChangeBatchDto();
        productChangeBatchDto.setSectionNoList(sectionNoListResult);

	    for (String sectionNo : sectionNoListResult){
            FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(sectionNo);
            if (null == fbCheckOutData){
                throw new RuntimeException("晶段：【" + sectionNo + "】,方棒检验不存在，禁止变更!");
            }
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(sectionNo);
            if (null == planProcessingOrder){
                throw new RuntimeException("晶段：【" + sectionNo + "】,加工工单不存在，禁止变更!");
            }
            if (planProcessingOrder.getStatus() != EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey()){
                throw new RuntimeException("晶段：【" + sectionNo + "】,加工工单非加工中，禁止变更!");
            }
            if (index == 0){
                fbCheckOutDataPre = fbCheckOutData;
            }
            if (!StringUtils.equals(fbCheckOutDataPre.getZorientationind(),fbCheckOutData.getZorientationind())){
                throw new RuntimeException("晶段：【" + sectionNo + "、" + fbCheckOutDataPre.getFbSectionNo()  + "】，订单标识不一致，禁止变更!");
            }
            productChangeBatchDto.setPreZorientationind(fbCheckOutData.getZorientationind());
            productChangeBatchDto.setPreBtchNo(fbCheckOutData.getBatchNo());
            productChangeBatchDto.setPreLevelCode(fbCheckOutData.getLevelCode());
            productChangeBatchDto.setPreOrderNo(fbCheckOutData.getOrderNo());
            productChangeBatchDto.setPreMaterialCode(fbCheckOutData.getMaterialCode());
            productChangeBatchDto.setSimpleName(fbCheckOutData.getAbbreviation());
            if (StringUtils.isBlank(productChangeBatchDto.getPreMaterialName()) && StringUtils.isNotBlank(productChangeBatchDto.getPreMaterialCode())){
                MaterialModel materialModel = materialModelService.findByCode(productChangeBatchDto.getPreMaterialCode());
                if (null != materialModel){
                    productChangeBatchDto.setPreMaterialName(materialModel.getName());
                }
            }
            index++;
        }
        return productChangeBatchDto;
    }

    @Override
    public void batchCreate(ProductChangeBatchDto productChangeBatchDto) {
        if (null == productChangeBatchDto || CollectionUtils.isEmpty(productChangeBatchDto.getSectionNoList())){
            throw new RuntimeException("传入参数为空!");
        }
        if (StringUtils.isBlank(productChangeBatchDto.getReplaceCharacter())){
            throw new RuntimeException("替换的字符为空!");
        }
        productChangeBatchDto.setOrderNo(productChangeBatchDto.getPreOrderNo());
       /* if (StringUtils.isBlank(productChangeBatchDto.getOrderNo())){
            throw new RuntimeException("替换的工单号为空!");
        }*/

        if (StringUtils.isBlank(productChangeBatchDto.getMaterialCode())){
            throw new RuntimeException("替换的物料编号为空!");
        }
        MaterialModel materialModel = materialModelService.findByCode(productChangeBatchDto.getMaterialCode());
        if(null == materialModel){

            throw new RuntimeException("替换物料编号：【" + productChangeBatchDto.getMaterialCode() + "】，物理模型不存在!");
        }

        if (StringUtils.isBlank(productChangeBatchDto.getZorientationind())){
            throw new RuntimeException("替换的工单定向标识为空!");
        }

       /* if (StringUtils.isBlank(productChangeBatchDto.getLevelCode())){
            throw new RuntimeException("替换的等级码为空!");
        }*/
        Date date = new Date();
        String username = BaseContextHandler.getUsername();
        for (String sectionNo : productChangeBatchDto.getSectionNoList()) {

            FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(sectionNo);
            if (null == fbCheckOutData) {
                throw new RuntimeException("提交晶段：【" + sectionNo + "】,方棒检验不存在，禁止变更!");
            }
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(sectionNo);
            if (null == planProcessingOrder){
                throw new RuntimeException("提交晶段：【" + sectionNo + "】,加工工单不存在，禁止变更!");
            }
            if (planProcessingOrder.getStatus() != EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey()){
                throw new RuntimeException("提交晶段：【" + sectionNo + "】,加工工单非加工中，禁止变更!");
            }
            List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(sectionNo);
            if(CollectionUtils.isEmpty(wipStorageList)){
                throw new RuntimeException("提交晶段：【" + sectionNo + "】,在制品记录不存在，禁止变更!");
            }
            WipStorage wipStorage = wipStorageList.get(0);
            if (!StringUtils.equals(EnumValuesFactory.WipStorageCode.方棒检验.getValue(), wipStorage.getProcessName())){
                throw new RuntimeException("提交晶段：【" + sectionNo + "】,当前站点非方棒检验，禁止变更!");
            }

            FbCheckOutRecord fbCheckOutRecord = fbCheckOutRecordService.findFbCheckOutRecord(sectionNo);
            if (null == fbCheckOutRecord) {
                throw new RuntimeException("提交晶段：【" + sectionNo + "】,方棒检验不存在，禁止变更!");
            }

            StringBuilder sectionNoNew = new StringBuilder(sectionNo);
            sectionNoNew.replace(1, 2, productChangeBatchDto.getReplaceCharacter());

            String batchNo = fbCheckOutData.getBatchNo();
            StringBuilder batchNoNew =  new StringBuilder(fbCheckOutData.getBatchNo());
            batchNoNew.replace(1, 2, productChangeBatchDto.getReplaceCharacter());

            StringBuilder ybSectionNoNew =  new StringBuilder(fbCheckOutData.getYbSectionNo());
            ybSectionNoNew.replace(1, 2, productChangeBatchDto.getReplaceCharacter());

            fbCheckOutData.setFbSectionNo(sectionNoNew.toString());
            fbCheckOutData.setYbSectionNo(ybSectionNoNew.toString());
            fbCheckOutData.setBatchNo(batchNoNew.toString());
            fbCheckOutData.setLevelCodePre(fbCheckOutData.getLevelCode());
            fbCheckOutData.setMaterialCodePre(fbCheckOutData.getMaterialCode());
            fbCheckOutData.setMaterialCode(productChangeBatchDto.getMaterialCode());
            fbCheckOutData.setZorientationind(productChangeBatchDto.getZorientationind());
            fbCheckOutData.setLevelCode(productChangeBatchDto.getLevelCode());
            fbCheckOutData.setUpdateUser(username);
            fbCheckOutData.setUpdateTime(date);
            fbCheckOutData.setReplaceCharacter(productChangeBatchDto.getReplaceCharacter());
            //fbCheckOutDataService.saveOrUpdate(fbCheckOutData);

            fbCheckOutRecordService.saveDataAndGrade(fbCheckOutData, "");
            planProcessingOrder.setCode(sectionNoNew.toString());
            planProcessingOrderService.saveOrUpdate(planProcessingOrder);
            wipStorage.setProcessingOrderCode(sectionNoNew.toString());
            wipStorageService.saveOrUpdate(wipStorage);
            fbCheckOutRecord.setFbSectionNo(sectionNoNew.toString());
            fbCheckOutRecord.setYbSectionNo(ybSectionNoNew.toString());
            fbCheckOutRecord.setBatchNo(batchNoNew.toString());
            fbCheckOutRecord.setZorientationind(productChangeBatchDto.getZorientationind());
            fbCheckOutRecord.setLevelCodePre(fbCheckOutRecord.getLevelCode());
            fbCheckOutRecord.setMaterialCodePre(fbCheckOutRecord.getMaterialCode());
            fbCheckOutRecord.setLevelCode(productChangeBatchDto.getLevelCode());
            fbCheckOutRecord.setMaterialCode(productChangeBatchDto.getMaterialCode());
            fbCheckOutRecord.setReplaceCharacter(productChangeBatchDto.getReplaceCharacter());
            fbCheckOutRecord.setUpdateTime(date);
            fbCheckOutRecord.setUpdateUser(username);
            fbCheckOutRecordService.saveOrUpdate(fbCheckOutRecord);

            ProductChangeRecord productChangeRecord = new ProductChangeRecord();
            BeanUtil.copyProperties(productChangeBatchDto, productChangeRecord, "id");
            productChangeRecord.setSectionNo(sectionNoNew.toString());
            productChangeRecord.setPreSectionNo(sectionNo);
            productChangeRecord.setBatchNo(batchNoNew.toString());
            productChangeRecord.setPreBatchNo(batchNo);
            productChangeRecord.setCreateName(username);
            productChangeRecord.setCreateTime(date);
            this.saveOrUpdate(productChangeRecord);
        }
    }
}
