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


import com.sw.mes.base.factory.init.entity.CrystalMaterialRelation;
import com.sw.mes.base.factory.init.service.CrystalMaterialRelationService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.check.service.PieceCheckService;
import com.sw.mes.yb.pad.entity.SectionNoDetail;
import com.sw.mes.yb.pad.service.SectionNoDetailService;
import com.sw.mes.yb.production.dao.CrystalBatchOperationDao;
import com.sw.mes.yb.production.dto.BatchOperationDto;
import com.sw.mes.yb.production.dto.CrystalBatchInfoDto;
import com.sw.mes.yb.production.dto.CrystalBatchOperationCreateDto;
import com.sw.mes.yb.production.dto.CrystalBatchOperationDto;
import com.sw.mes.yb.production.entity.CrystalBatchOperation;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.service.CrystalBatchOperationService;
import com.sw.mes.yb.production.service.LongCrystalService;
import org.apache.commons.collections.CollectionUtils;
import org.modelmapper.ModelMapper;
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;
import java.util.Optional;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class CrystalBatchOperationServiceImpl extends BaseServiceImpl<CrystalBatchOperation> implements CrystalBatchOperationService {
    CrystalBatchOperationDao dao;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private LongCrystalService longCrystalService;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private SectionNoDetailService sectionNoDetailService;

    @Autowired
    private CrystalMaterialRelationService crystalMaterialRelationService;


    @Autowired
    private MaterialModelService materialModelService;


    @Autowired
    private PieceCheckService pieceCheckService;

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

    @Override
    public void batchOperateCrystalBatchOperation(BatchOperationDto batchOperationDto) {

	    if (null != batchOperationDto.getOperateStatus()){
            Date date = new Date();
            if (null == batchOperationDto.getLockTime()){
                batchOperationDto.setLockTime(date);
            }
            if (null == batchOperationDto.getUnlockTime()){
                batchOperationDto.setUnlockTime(date);
            }
            for (Long id : batchOperationDto.getIdList()){
                if (batchOperationDto.getOperateStatus() == 2){
                    this.delete(id);
                }else {
                    CrystalBatchOperation crystalBatchOperation = this.get(id);
                    if (null != crystalBatchOperation){
                        if (batchOperationDto.getOperateStatus() == 0){
                            crystalBatchOperation.setLockUser(batchOperationDto.getLockUser());
                            crystalBatchOperation.setLockTime(batchOperationDto.getLockTime());
                            crystalBatchOperation.setLockReason(batchOperationDto.getLockReason());
                            crystalBatchOperation.setLockRemark(batchOperationDto.getLockRemark());
                        }else if (batchOperationDto.getOperateStatus() == 1){
                            crystalBatchOperation.setUnlockUser(batchOperationDto.getUnlockUser());
                            crystalBatchOperation.setUnlockTime(batchOperationDto.getUnlockTime());
                            crystalBatchOperation.setUnlockReason(batchOperationDto.getUnlockReason());
                            crystalBatchOperation.setUnlockRemark(batchOperationDto.getUnlockRemark());
                            //解锁触发数据评级
                            if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "lockTriggerRating", true)){
                                this.handleUnlockRate(crystalBatchOperation);
                            }
                        }
                        crystalBatchOperation.setStatus(batchOperationDto.getOperateStatus());
                        this.saveOrUpdate(crystalBatchOperation);
                    }
                }
            }
           /* Optional.ofNullable(batchOperationDto.getIdList()).orElse(new ArrayList<>()).forEach((id)->{
                if (batchOperationDto.getOperateStatus() == 2){
                    this.delete(id);
                }else {
                    CrystalBatchOperation crystalBatchOperation = this.get(id);
                    if (null != crystalBatchOperation){
                        if (batchOperationDto.getOperateStatus() == 0){
                            crystalBatchOperation.setLockUser(batchOperationDto.getLockUser());
                            crystalBatchOperation.setLockTime(batchOperationDto.getLockTime());
                            crystalBatchOperation.setLockReason(batchOperationDto.getLockReason());
                            crystalBatchOperation.setLockRemark(batchOperationDto.getLockRemark());
                        }else if (batchOperationDto.getOperateStatus() == 1){
                            crystalBatchOperation.setUnlockUser(batchOperationDto.getUnlockUser());
                            crystalBatchOperation.setUnlockTime(batchOperationDto.getUnlockTime());
                            crystalBatchOperation.setUnlockReason(batchOperationDto.getUnlockReason());
                            crystalBatchOperation.setUnlockRemark(batchOperationDto.getUnlockRemark());
                        }
                        crystalBatchOperation.setStatus(batchOperationDto.getOperateStatus());
                        this.saveOrUpdate(crystalBatchOperation);
                    }
                }
            });*/
        }
    }

    private void handleUnlockRate(CrystalBatchOperation crystalBatchOperation){
	    if (null == crystalBatchOperation || StringUtils.isBlank(crystalBatchOperation.getSectionNo())){
	        return;
        }
	    if (StringUtils.equals(crystalBatchOperation.getSectionNo(),crystalBatchOperation.getCrystalNo())){
	        //锁定单晶
            List<SectionNoDetail> byCrystalNo = sectionNoDetailService.findByCrystalNo(crystalBatchOperation.getCrystalNo());
            if (CollectionUtils.isNotEmpty(byCrystalNo)){
                SectionNoDetail sectionNoDetail = byCrystalNo.get(0);
                if (StringUtils.isNotBlank(sectionNoDetail.getPieceNoEnd())){
                    pieceCheckService.saveInspectDataBaseInfo(sectionNoDetail.getPieceNoEnd());
                }else if (StringUtils.isNotBlank(sectionNoDetail.getPieceNoHead())){
                    pieceCheckService.saveInspectDataBaseInfo(sectionNoDetail.getPieceNoHead());
                }
            }
        }else {
	        //查询圆棒检验数据是否存在
            YbInspectData bySectionNo = ybInspectDataService.findBySectionNo(crystalBatchOperation.getSectionNo());
            if (null != bySectionNo){
                //判断是否为圆棒检验进站，否，不修改数据
                wipStorageService.selectWipStorage(crystalBatchOperation.getSectionNo(),  EnumValuesFactory.WipStorageCode.圆棒检验.getKey(), true);
                ybInspectDataService.handleDefaultOxygenAndCarbon(bySectionNo);
                ybInspectDataService.saveDataAndGrade(bySectionNo);
            }
        }
    }

    @Override
    public void batchCreateCrystalBatchOperation(CrystalBatchOperationCreateDto crystalBatchOperationCreateDto) {

	    if (CollectionUtils.isEmpty(crystalBatchOperationCreateDto.getBatchInfoDtoList())){
	        throw new RuntimeException("批次操作单晶信息集合为空！");
        }

	    if (null == crystalBatchOperationCreateDto.getLockTime()){
            crystalBatchOperationCreateDto.setLockTime(new Date());
        }
        for (CrystalBatchInfoDto crystalBatchInfoDto : crystalBatchOperationCreateDto.getBatchInfoDtoList()){
            //查询批次锁定是否存在
            CrystalBatchOperation crystalBatchOperationNew = dao.findBySectionNo(crystalBatchInfoDto.getSectionNo());
            if (null != crystalBatchOperationNew){
                throw new RuntimeException("批次操作单晶已存在，单晶编号为：" + crystalBatchInfoDto.getSectionNo());
            }
            CrystalBatchOperation crystalBatchOperation = modelMapper.map(crystalBatchInfoDto, CrystalBatchOperation.class);
            crystalBatchOperation.setLockReason(crystalBatchOperationCreateDto.getLockReason());
            crystalBatchOperation.setLockRemark(crystalBatchOperationCreateDto.getLockRemark());
            crystalBatchOperation.setLockUser(crystalBatchOperationCreateDto.getLockUser());
            crystalBatchOperation.setLockTime(crystalBatchOperationCreateDto.getLockTime());
            crystalBatchOperation.setStatus(0);
            this.saveOrUpdate(crystalBatchOperation);
        }
/*
	    Optional.ofNullable(crystalBatchOperationCreateDto.getBatchInfoDtoList()).orElse(new ArrayList<>()).forEach(crystalBatchInfoDto -> {
            CrystalBatchOperation crystalBatchOperation = modelMapper.map(crystalBatchInfoDto, CrystalBatchOperation.class);
            crystalBatchOperation.setLockReason(crystalBatchOperationCreateDto.getLockReason());
            crystalBatchOperation.setLockRemark(crystalBatchOperationCreateDto.getLockRemark());
            crystalBatchOperation.setLockUser(crystalBatchOperationCreateDto.getLockUser());
            crystalBatchOperation.setLockTime(crystalBatchOperationCreateDto.getLockTime());
            crystalBatchOperation.setStatus(0);
            this.saveOrUpdate(crystalBatchOperation);
        });*/
    }

    @Override
    public List<CrystalBatchInfoDto> getInfoBySectionNo(String sectionList) {

	    if (StringUtils.isBlank(sectionList)){
	        return null;
        }
	    List<CrystalBatchInfoDto> result = new ArrayList<>();
        String[] split = sectionList.split(",");
	    for(String section : split){
            List<WipStorage> byProcessingByOrderCode = wipStorageService.findByProcessingByOrderCode(section);
            if (CollectionUtils.isNotEmpty(byProcessingByOrderCode)){

                WipStorage wipStorage = byProcessingByOrderCode.get(0);
                String processName = wipStorage.getProcessName();
                YbInspectData ybInspectData = null;
                LongCrystal longCrystal = null;
                SectionNoDetail bySectionNo = sectionNoDetailService.findBySectionNo(section);
                if (null != bySectionNo){
                    ybInspectData = ybInspectDataService.findBySectionNo(section);
                    longCrystal = longCrystalService.findByCrystalNo(bySectionNo.getCrystalNo());
                }else {
                    longCrystal = longCrystalService.findByCrystalNo(section);
                }
                /*if (StringUtils.equals(EnumValuesFactory.WipStorageCode.方棒检验.getValue(),processName) || StringUtils.equals(EnumValuesFactory.WipStorageCode.圆棒检验.getValue(),processName)){
                    ybInspectData = ybInspectDataService.findBySectionNo(section);
                    longCrystal = longCrystalService.findByCrystalNo(section.substring(0,16));
                }else {
                    //去长晶棒获取信息
                    if (section.length() > 16){
                        longCrystal = longCrystalService.findByCrystalNo(section.substring(0,16));
                    }else {
                        longCrystal = longCrystalService.findByCrystalNo(section);
                    }
                }*/
                result.add(this.packageCrystalBatchOperationDto(longCrystal,ybInspectData,wipStorage));
            }
        }
        return result;
    }

    private CrystalBatchInfoDto packageCrystalBatchOperationDto(LongCrystal longCrystal,YbInspectData ybInspectData,WipStorage wipStorage){
        CrystalBatchInfoDto crystalBatchOperationDto = new CrystalBatchInfoDto();

        Boolean flagSqureMaterial = false;
        if (null != longCrystal){
            crystalBatchOperationDto.setCrystalNo(longCrystal.getCrystalNo());
            crystalBatchOperationDto.setSpecs(longCrystal.getSpecs());
            crystalBatchOperationDto.setMaterialCode(longCrystal.getProductCode());
            crystalBatchOperationDto.setMaterialName(longCrystal.getProductName());
            crystalBatchOperationDto.setAbbreviation(longCrystal.getSimpleName());
            crystalBatchOperationDto.setConductiveType(longCrystal.getConductiveType());
            crystalBatchOperationDto.setSpecs(longCrystal.getSpecs());
            crystalBatchOperationDto.setDopant(longCrystal.getDopant());
            crystalBatchOperationDto.setOrderNo(longCrystal.getOrderNo());
        }
        if (null != ybInspectData){
            crystalBatchOperationDto.setRecipeName(ybInspectData.getFormulation());
            crystalBatchOperationDto.setLevelCode(ybInspectData.getLevelCode());
            crystalBatchOperationDto.setProductLevel(ybInspectData.getProductLevel());
            crystalBatchOperationDto.setSectionNo(ybInspectData.getSectionNo());
            CrystalMaterialRelation crystalMaterialRelation = crystalMaterialRelationService.findBySectionNo(ybInspectData.getSectionNo());
            if (null != crystalMaterialRelation){
                crystalBatchOperationDto.setMaterialCode(crystalMaterialRelation.getMaterialCode());
                if (null != crystalMaterialRelation.getMaterialModelId()){
                    MaterialModel materialModel = materialModelService.get(crystalMaterialRelation.getMaterialModelId());
                    if (null != materialModel){
                        crystalBatchOperationDto.setMaterialName(materialModel.getName());
                    }
                    flagSqureMaterial = true;
                }
            }

        }
        if (null != wipStorage){
            crystalBatchOperationDto.setPosition(wipStorage.getProcessName());
            crystalBatchOperationDto.setSiteStatus(wipStorage.getStatus());
        }
        if (StringUtils.isBlank(crystalBatchOperationDto.getSectionNo()) && null != longCrystal){
            crystalBatchOperationDto.setSectionNo(longCrystal.getCrystalNo());
        }

        //处理料号数据
        if (!flagSqureMaterial && null != longCrystal){
            CrystalMaterialRelation crystalMaterialRelationC = crystalMaterialRelationService.findBySectionNo(longCrystal.getCrystalNo());
            if (null != crystalMaterialRelationC){
                if (null != crystalMaterialRelationC.getMaterialModelId()){
                    MaterialModel materialModel = materialModelService.get(crystalMaterialRelationC.getMaterialModelId());
                    if (null != materialModel){
                        crystalBatchOperationDto.setMaterialName(materialModel.getName());
                    }
                }
                crystalBatchOperationDto.setMaterialCode(crystalMaterialRelationC.getMaterialCode());
            }
        }


        return crystalBatchOperationDto;
    }

    @Override
    public CrystalBatchOperation findByCrystalNoAndStatus(String crystalNo, Integer status) {
        if (StringUtils.isNotBlank(crystalNo)){
            return dao.findByCrystalNoAndStatus(crystalNo,status);
        }
        return null;
    }

    @Override
    public CrystalBatchOperation findBySectionNoAndStatus(String sectionNo, Integer status) {
        if (StringUtils.isNotBlank(sectionNo)){
            return dao.findBySectionNoAndStatus(sectionNo,status);
        }
        return null;
    }

    @Override
    public void judgeCrystalNoIsLock(String crystalNo, String sectionNo, Boolean isCrystalBar) {
        if (isCrystalBar){
            if (StringUtils.isNotBlank(crystalNo)){
                CrystalBatchOperation byCrystalNoAndStatus = this.findByCrystalNoAndStatus(crystalNo, EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
                if (null != byCrystalNoAndStatus){
                    throw new BusinessException("晶棒处于锁定状态，" + byCrystalNoAndStatus.getLockReason() + ",请先解锁！");
                }
            }
        }else {
            if (null != sectionNo){
                CrystalBatchOperation bySectionNoAndStatus = this.findBySectionNoAndStatus(sectionNo, EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
                if (null != bySectionNoAndStatus){
                    throw new BusinessException("晶段处于锁定状态，" + bySectionNoAndStatus.getLockReason() + ",请先解锁！");
                }
                SectionNoDetail bySectionNo = sectionNoDetailService.findBySectionNo(sectionNo);
                if (null != bySectionNo && StringUtils.isNotBlank(bySectionNo.getCrystalNo())){
                    CrystalBatchOperation byCrystalNoAndStatus = this.findByCrystalNoAndStatus(bySectionNo.getCrystalNo(), EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
                    if (null != byCrystalNoAndStatus && StringUtils.equals(byCrystalNoAndStatus.getSectionNo(),byCrystalNoAndStatus.getCrystalNo())){
                        throw new BusinessException("晶棒处于锁定状态，" + byCrystalNoAndStatus.getLockReason() + ",请先解锁！");
                    }
                }
            }
        }
    }

    @Override
    public CrystalBatchOperation findBySectionNo(String sectionNo) {
        return dao.findBySectionNo(sectionNo);
    }
}
