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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.entity.FactoryModel;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.init.service.FactoryModelService;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.store.WarehouseOutputBillBo;
import com.sw.mes.core.dto.store.WarehouseOutputBillDetailBo;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.yb.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import com.sw.mes.yb.seed.dao.SeedMaterialsRecordDao;
import com.sw.mes.yb.seed.dto.SeedMaterialsRecordDto;
import com.sw.mes.yb.seed.dto.WarehouseInventoryDto;
import com.sw.mes.yb.seed.entity.SeedData;
import com.sw.mes.yb.seed.entity.SeedGroupBracket;
import com.sw.mes.yb.seed.entity.SeedGroupBracketDetails;
import com.sw.mes.yb.seed.entity.SeedMaterialsRecord;
import com.sw.mes.yb.seed.service.SeedGroupBracketDetailsService;
import com.sw.mes.yb.seed.service.SeedGroupBracketService;
import com.sw.mes.yb.seed.service.SeedMaterialsRecordService;
import com.sw.mes.yb.seed.service.SeedService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

@Service
public class SeedMaterialsRecordServiceImpl extends BaseServiceImpl<SeedMaterialsRecord> implements SeedMaterialsRecordService {
    SeedMaterialsRecordDao dao;
    @Autowired
    private ProductionScheduleService productionScheduleService;
    @Autowired
    private SeedService seedService;
    @Autowired
    private FactoryModelService factoryModelService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private StoreFeignClients storeFeignClients;
    @Autowired
    private SeedGroupBracketDetailsService seedGroupBracketDetailsService;
    @Autowired
    private SeedGroupBracketService seedGroupBracketService;

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

    @Override
    public Result create(SeedMaterialsRecordDto materialsRecordDto) {
        List<Integer> status = new ArrayList<>();
        status.add(1);
        status.add(4);
        status.add(5);
        //通过设备编号查询排查，获取炉次号及工单号
        ProductionSchedule dataByDeviceNo = productionScheduleService.findDataByDeviceNo(materialsRecordDto.getDeviceCode(), status);
        if (ObjectUtils.isEmpty(dataByDeviceNo)) {
            return ResultGenerator.fail("未查询炉台【" + materialsRecordDto.getDeviceCode() + "】的相关排程信息!");
        }
        String batchNo = "";
        String warehouseCode = "";
        String warehouseName = "";
        //获取籽晶对象
        SeedGroupBracketDetails seedGroupBracketDetails = seedGroupBracketDetailsService.findBySeedCode(materialsRecordDto.getSeedCode());
        if(!ObjectUtils.isEmpty(seedGroupBracketDetails)){
            SeedGroupBracket seedGroupBracket = seedGroupBracketService.get(seedGroupBracketDetails.getParentId());
            if(!ObjectUtils.isEmpty(seedGroupBracket)){
                batchNo = seedGroupBracket.getSeedDayBatchNo();
            }
        }else {
            return ResultGenerator.fail("为获取到【" + materialsRecordDto.getSeedCode() + "】的组托明细信息!");
        }
        SeedData seedData = seedService.findByCode(materialsRecordDto.getSeedCode());
        if (ObjectUtils.isEmpty(seedData)) {
            return ResultGenerator.fail("未查询到相关编码【" + materialsRecordDto.getSeedCode() + "】籽晶数据!");
        }
        if (seedData.getDeleted().equals(true)) {
            return ResultGenerator.fail("该籽晶编码【" + materialsRecordDto.getSeedCode() + "】已被领用!");
        }
        if(seedData.getWorkShopCode().equals("SXLJ2015")){
            warehouseCode = "P32F";
            warehouseName = "籽晶现场2仓";
        }else {
            warehouseCode = "P31F";
            warehouseName = "籽晶现场1仓";
        }
        //获取设备信息
        Equipment equipment = equipmentService.findByCode(materialsRecordDto.getDeviceCode());
        if (ObjectUtils.isEmpty(equipment)) {
            return ResultGenerator.fail("未查询到相关设备【" + materialsRecordDto.getDeviceCode() + "】信息!");
        }
        //获取工厂模型
        FactoryModel factoryModel = factoryModelService.findByCode(equipment.getArea());
        if (ObjectUtils.isEmpty(factoryModel)) {
            return ResultGenerator.fail("未查询到相关工厂模型!");
        }
        //获取库存信息
        Result inventory = storeFeignClients.getByMaterialAndBatchNoAndWarehouseCode(batchNo,seedData.getMaterialCode(), warehouseCode);
        if (inventory.getCode().equals(200)) {
            if (ObjectUtils.isEmpty(inventory.getData())) {
                return ResultGenerator.fail("未查询到相关库存数据!");
            }
            WarehouseInventoryDto inventoryDto = JSONObject.parseObject(JSON.toJSONString(inventory.getData()), WarehouseInventoryDto.class);
            if (inventoryDto.getQuantity().compareTo(new BigDecimal(0)) <= 0) {
                return ResultGenerator.fail("该库位库存量不足!");
            }
            SeedMaterialsRecordDto seedMaterialsRecordDto = new SeedMaterialsRecordDto();
            seedMaterialsRecordDto.setSeedCode(seedData.getSeedCode());
            seedMaterialsRecordDto.setBillCode(dataByDeviceNo.getProductionOrder().getAufnr());
            seedMaterialsRecordDto.setDeviceCode(materialsRecordDto.getDeviceCode());
            seedMaterialsRecordDto.setDeviceBatch(dataByDeviceNo.getLotNo());
            seedMaterialsRecordDto.setWorkshopId(factoryModel.getId());
            seedMaterialsRecordDto.setWorkshopName(factoryModel.getName());
            seedMaterialsRecordDto.setMaterialCode(seedData.getMaterialCode());
            seedMaterialsRecordDto.setRethrowsNumber(materialsRecordDto.getRethrowsNumber());
            seedMaterialsRecordDto.setCreateBy(BaseContextHandler.getUsername());
            seedMaterialsRecordDto.setCreateDate(new Date());
            SeedMaterialsRecord seedMaterialsRecord = fromDto(seedMaterialsRecordDto);
            this.saveOrUpdate(seedMaterialsRecord);
            WarehouseOutputBillBo warehouseOutputBillBo = new WarehouseOutputBillBo();
            warehouseOutputBillBo.setType("籽晶领用");
            warehouseOutputBillBo.setAutoAudit(true);
            warehouseOutputBillBo.setCreateUserId(BaseContextHandler.getUserID());
            warehouseOutputBillBo.setCreateUserName(BaseContextHandler.getUsername());
            warehouseOutputBillBo.setDestination("车间");
            List<WarehouseOutputBillDetailBo> warehouseOutputBillDetailBos = new ArrayList<>();
            WarehouseOutputBillDetailBo warehouseOutputBillDetailBo = new WarehouseOutputBillDetailBo();
            warehouseOutputBillDetailBo.setRequireCount(new BigDecimal(1));
            warehouseOutputBillDetailBo.setOutputCount(new BigDecimal(1));
            warehouseOutputBillDetailBo.setWarehouseCode(warehouseCode);
            warehouseOutputBillDetailBo.setWarehouseName(warehouseName);
            warehouseOutputBillDetailBo.setBatchNo(batchNo);
            warehouseOutputBillDetailBo.setMaterialModelCode(seedData.getMaterialCode());
            warehouseOutputBillDetailBo.setMaterialModelName(seedData.getMaterialName());
            warehouseOutputBillDetailBo.setCreateUserId(warehouseOutputBillBo.getCreateUserId());
            warehouseOutputBillDetailBo.setCreateUserName(warehouseOutputBillBo.getCreateUserName());
            warehouseOutputBillDetailBo.setCrystalNo(seedData.getBatchNo());
            warehouseOutputBillDetailBos.add(warehouseOutputBillDetailBo);
            warehouseOutputBillBo.setOutputBillDetails(warehouseOutputBillDetailBos);
            Result<String> result = storeFeignClients.outputApply(warehouseOutputBillBo);
            if (result.getCode().equals(200)) {
                seedData.setDeleted(true);
                seedService.saveOrUpdate(seedData);
                return ResultGenerator.success();
            } else {
                return ResultGenerator.fail("籽晶领用失败!");
            }
        } else {
            return ResultGenerator.fail(inventory.getMessage());
        }
    }

    public SeedMaterialsRecord fromDto(SeedMaterialsRecordDto dto) {
        SeedMaterialsRecord seedMaterialsRecord = new SeedMaterialsRecord();
        BeanUtils.copyProperties(dto, seedMaterialsRecord);
        return seedMaterialsRecord;
    }
}
