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


import cn.hutool.core.collection.CollectionUtil;
import com.sw.mes.base.workinprocess.dto.PdaProcessLogDto;
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.ProcessLogService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.dto.ProductionPaintingLineDetailDto1;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.yb.pad.entity.ProductionBackCuttingRecord;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.entity.ReCut;
import com.sw.mes.yb.pad.service.FbReCutService;
import com.sw.mes.yb.pad.service.PdaProcessService;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
import com.sw.mes.yb.pad.service.ProductionRecutService;
import com.sw.mes.yb.production.entity.CrystalBatchOperation;
import com.sw.mes.yb.production.service.CrystalBatchOperationService;
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.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class PdaProcessServiceImpl  implements PdaProcessService {


    @Autowired
    ProcessLogService processLogService;

    @Autowired
    WipStorageService wipStorageService;

    @Autowired
    ProductionRecutService productionRecutService;

    @Autowired
    ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FbReCutService fbReCutService;

    @Autowired
    private CrystalBatchOperationService crystalBatchOperationService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Override
    public PdaProcessLogDto findByProcessingOrderCode(String code) {

        PdaProcessLogDto dto;
        dto = processLogService.findLogByProcessingOrderCode(code);
        if(null == dto){
            throw new BusinessException("未查到过站信息！");
        }
        //List<Map<String, Object>> maps = processLogService.findByProcessingOrderCode(code);

        List<Map<String, Object>> ybMaps = processLogService.findByYbProcessingOrderCode(code);
        if (CollectionUtil.isNotEmpty(ybMaps)) {
            Map<String, Object> map = ybMaps.get(0);
            if (map.get("ybWeight") != null) {
                dto.setYbWeight(map.get("ybWeight").toString());
            }
            if (map.get("ybLength") != null) {
                dto.setYbLength(map.get("ybLength").toString());
            }
            if (map.get("ybLevel") != null) {
                dto.setYbLevel(map.get("ybLevel").toString());
            }

        }

        List<Map<String, Object>> fbMaps = processLogService.findByFbProcessingOrderCode(code);
        if (CollectionUtil.isNotEmpty(fbMaps)) {
            Map<String, Object> map = fbMaps.get(0);
            if (map.get("fbWeight") != null) {
                dto.setFbWeight(map.get("fbWeight").toString());
            }
            if (map.get("fbLength") != null) {
                dto.setFbLength(map.get("fbLength").toString());
            }
            if (map.get("fbLevel") != null) {
                dto.setFbLevel(map.get("fbLevel").toString());
            }
        }


      /*  Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(code);
        if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException("查询站点信息失败");
        }
        if (currentWipStorageStatusDtoResult.getData() == null) {
            throw new BusinessException("站点信息为空");
        }*/
        List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(code);
        if (CollectionUtils.isEmpty(wipStorageList)){
            throw new BusinessException("站点信息为空");
        }
        WipStorage wipStorage = wipStorageList.get(0);
        List<ProductionPaintingLineDetailDto1> detailDto1s = new ArrayList<>();
//        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
        if ((wipStorage.getProcessName().equals(EnumValuesFactory.WipStorageCode.圆棒截断.getKey())
                && wipStorage.getStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey())
        ) {
            ProductionBackCuttingRecord record = productionRecutService.findBySegmentNo(code);
            if(null != record){
                dto.setCutReason(record.getCause());
                List<ProductionPaintingLineDetail> details = productionPaintingLineDetailService.findByOperateReversecutDrawId(record.getId());
                if(CollectionUtil.isNotEmpty(details)){
                    detailDto1s = details.stream()
                            .map(entity -> toLazyDto(entity))
                            .collect(Collectors.toList());

                }
                dto.setPaintingLineDetailDto1s(detailDto1s);
            }

        }else if ((wipStorage.getProcessName().equals(EnumValuesFactory.WipStorageCode.方棒截断.getKey())
                && wipStorage.getStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey())
        ) {
            ReCut reCut  = fbReCutService.findReCutInfoBySectionNo(code);
            if(null != reCut){
                dto.setCutReason(reCut.getReason());
                List<ProductionPaintingLineDetail> details = productionPaintingLineDetailService.findByOperateRecutDrawIdFb(reCut.getId());
                if(CollectionUtil.isNotEmpty(details)){
                    detailDto1s = details.stream()
                            .map(entity -> toLazyDto(entity))
                            .collect(Collectors.toList());

                }
                dto.setPaintingLineDetailDto1s(detailDto1s);
            }

        }

        //处理返切长度和返切原因
        ProductionBackCuttingRecord productionBackCuttingRecord = productionRecutService.findBySectionNo(code);
        if (null != productionBackCuttingRecord){
            dto.setCutReason(productionBackCuttingRecord.getCause());
            if (null != productionBackCuttingRecord.getBarLength() && null != productionBackCuttingRecord.getBackLength()){
                dto.setCutLength(productionBackCuttingRecord.getBarLength().subtract(productionBackCuttingRecord.getBackLength()));
                dto.setRemainLength(productionBackCuttingRecord.getBackLength());
            }
        }

        ReCut reCutNew  = fbReCutService.findReCutInfoBySectionNo(code);
        if (null != reCutNew){
            dto.setCutReason(reCutNew.getReason());
            dto.setCutLength(reCutNew.getRecutLength());
            if (null != reCutNew.getSegmentNoLength() && null != reCutNew.getRecutLength()){
                dto.setRemainLength(reCutNew.getSegmentNoLength().subtract(reCutNew.getRecutLength()));
            }
        }
        //查询工单状态
        PlanProcessingOrder byCode = planProcessingOrderService.findByCode(code);
        if (null != byCode){
            switch (byCode.getStatus()){
                case 0:
                    dto.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.待加工.getValue());
                    break;
                case 1:
                    dto.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getValue());
                    break;
                case 2:
                    dto.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工完成.getValue());
                    break;
                case 3:
                    dto.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.入库完成.getValue());
                    break;
                case 4:
                    dto.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.已作废.getValue());
                    break;
                case 5:
                    dto.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.组托.getValue());
                    break;
                default:
                    break;
            }

        }

        CrystalBatchOperation byCrystalNoAndStatus = crystalBatchOperationService.findByCrystalNoAndStatus(code, EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
        if(null != byCrystalNoAndStatus){
            dto.setLockReason(byCrystalNoAndStatus.getLockReason());
        }else {
            CrystalBatchOperation bySectionNoAndStatus = crystalBatchOperationService.findBySectionNoAndStatus(code, EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
            if(null != bySectionNoAndStatus){
                dto.setLockReason(bySectionNoAndStatus.getLockReason());
            }
        }

        return dto;
    }

    private ProductionPaintingLineDetailDto1 toLazyDto(ProductionPaintingLineDetail entity) {
        return modelMapper.map(entity,ProductionPaintingLineDetailDto1.class);
    }
}
