package com.sw.mes.yb.production.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.utils.*;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.enumvalue.EnumValuesServer;
import com.sw.mes.mmcs.service.MMcsInterfaceService;
import com.sw.mes.production.dto.DecompositionSchemeParam;
import com.sw.mes.production.dto.FormulaSchemeData;
import com.sw.mes.production.service.FormulaSchemeOutService;
import com.sw.mes.yb.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import com.sw.mes.yb.production.dto.*;
import com.sw.mes.yb.production.dto.AgainTask.AgainTaskDto;
import com.sw.mes.yb.production.dto.AgainTaskDetail.TaskDetailExportDto;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.InputFurnaceBurdenExport;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.InputFurnaceBurdenExportParam;
import com.sw.mes.yb.production.dto.LoadingTask.IngredientInfoDto;
import com.sw.mes.yb.production.dto.weightSplit.BucketWeightDto;
import com.sw.mes.yb.production.entity.*;
import com.sw.mes.yb.production.service.*;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.yb.production.dto.LoadingTask.AutoSuccessTaskDto;
import com.sw.mes.yb.production.dto.LoadingTask.LoadingTaskDto;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;


/**
* @Author 李儒
*/
@RestController
@RequestMapping("/processLoadingTask")
@Slf4j
@Api(description = "装料任务接口")
public class LoadingTaskController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private LoadingTaskService loadingTaskService;
	@Autowired
	private BlastFurnaceDetailService blastFurnaceDetailService;
	@Autowired
	private ProductionCircleRecipeService productionCircleRecipeService;
	@Autowired
	private ProductionCircleWeightService productionCircleWeightService;
    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;
    @Autowired
    private EquipmentService equipmentService;
	@Autowired
	private LoadingTaskLogService loadingTaskLogService;

	@Autowired
	private MMcsInterfaceService mMcsInterfaceService;
	@Autowired
	private DictionaryItemService dictionaryItemService;
	@Autowired
	private ProductionCircleRecipeDetailService productionCircleRecipeDetailService;
	@Autowired
	private LoadingTaskRecipeService loadingTaskRecipeService;
	@Autowired
	private ProductionScheduleService scheduleService;
	@Autowired
	private FormulaSchemeOutService formulaSchemeOutService;
	@Autowired
	private ProductionFurnaceMaterialSplitService splitService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "分页查询装料任务列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_area", value = "车间", dataType = "string", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<LoadingTaskDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<LoadingTask> specification = DynamicSpecifications.bySearchFilter(request, LoadingTask.class);
		/*String[] sort = {"delayedStartTime DESC"};
		Page<LoadingTask> page = loadingTaskService.findByExample(specification, PageUtil.createPageable(requestPage, sort));*/
		Page<LoadingTask> page = loadingTaskService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<LoadingTaskDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		// 补充排程信息
		for (LoadingTaskDto dto : dtos) {
			ProductionSchedule schedule = scheduleService.get(dto.getScheduleId());
			if (schedule == null) continue;
			dto.setScheduleStatus(schedule.getStatus());
			if (schedule.getStatus() == EnumValuesServer.ProductionScheduleStatus.未开始.getKey()
					|| schedule.getStatus() == EnumValuesServer.ProductionScheduleStatus.待备料.getKey()){
				dto.setIsCancel(true);
			}
		}
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}


	@SuppressWarnings("unchecked")
	@ApiOperation(value = "装料任务详细信息")
	@GetMapping("/{id}")
	public Result<LoadingTaskDto> get(@PathVariable @ApiParam(value="装料任务id") Long id) {
		LoadingTask loadingTask = loadingTaskService.get(id);
		if (null == loadingTask) {
            return ResultGenerator.fail("该装料任务不存在");
        }
		return ResultGenerator.success(toEagerDto(loadingTask));
	}


	@ApiOperation(value = "根据炉次号查询数据")
	@GetMapping("/getData")
	public Result<LoadingTask> getData(@ApiParam(value = "炉次号") String equipmentCode) {
		List<LoadingTask> loadingTasks = loadingTaskService.findByEquipmentCode(equipmentCode);
		loadingTasks.sort(Comparator.comparing(LoadingTask::getEtTime).reversed());
		List<LoadingTask> collect = loadingTasks.stream().filter(loadingTask -> !StringUtils.isBlank(loadingTask.getLotNo()) && loadingTask.getLotNo().equals(loadingTasks.get(0).getLotNo())).collect(Collectors.toList());
		if (loadingTasks == null) {
			return ResultGenerator.fail("未查询到此设备相关信息");
		} else {
			for (LoadingTask loadingTask : collect) {
				if(!loadingTask.getRawStatus().equals(AgainTaskDto.rawStatus_1)&&!loadingTask.getRawStatus().equals(AgainTaskDto.rawStatus_3)&&!loadingTask.getRawStatus().equals(AgainTaskDto.rawStatus_4)){
					return ResultGenerator.success(loadingTask);
				}
			}
		}
		return ResultGenerator.fail("当前设备为生产、自动完工或人工完工状态");
	}


    @ApiOperation(value = "根据设备号查询炉次号")
    @GetMapping("/getLotno")
    public Result<String> getLotno(@ApiParam(value = "设备号") String equipmentCode) {
        Equipment equipment = equipmentService.findByCode(equipmentCode);
        if (equipment == null) {
            return ResultGenerator.fail("设备号不存在");
        }
        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByEquipmentIdAndOrderTypeAndStatus(equipment.getId(), EnumValuesFactory.PlanProcessingOrderOrderType.炉次.getKey(), EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
        if (planProcessingOrder != null) {
            String code = planProcessingOrder.getCode();
            return ResultGenerator.success(code);
        } else {
            return ResultGenerator.fail(equipmentCode + "设备没有正在运行的炉次");
        }
    }


    @ApiOperation(value = "根据炉次号查询设备号")
    @GetMapping("/getEquipmentCode")
    public Result<String> getEquipmentCode(@ApiParam(value = "炉次号") String code) {
        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCodeAndOrderTypeAndStatus(code, EnumValuesFactory.PlanProcessingOrderOrderType.炉次.getKey(), EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
        if (planProcessingOrder != null) {
            String equipmentCode = planProcessingOrder.getEquipmentCode();
            return ResultGenerator.success(equipmentCode);
        } else {
            return ResultGenerator.fail("炉次号不存在");
        }
    }


    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "更换配方")
    @PostMapping("/updateCircleRecipe")
    public Result updateCircleRecipe(@RequestParam @ApiParam(value = "任务ID") Long taskId,@RequestParam @ApiParam(value = "配方ID") Long recipeId,@RequestParam @ApiParam(value = "重量ID") Long weigthId) {
        if (taskId == null || taskId<=0) {
            return ResultGenerator.fail("任务ID(taskId)不能为空");
        }

        if (recipeId == null || recipeId<=0) {
            return ResultGenerator.fail("配方ID(recipeId) 不能为空");
        }

        try {
            LoadingTask entity = loadingTaskService.get(taskId);
            if(entity==null) {
                return ResultGenerator.fail("任务不存在");
            } else if(!entity.getRawStatus().equals(LoadingTaskDto.rawStatus_0)) {
            	return ResultGenerator.fail("任务不在新建状态，无法更换配方");
            }

            ProductionCircleRecipe recipe = productionCircleRecipeService.get(recipeId);
            if(recipe==null) {
            	return ResultGenerator.fail("配方不存在");
            }

            ProductionCircleWeight weight = productionCircleWeightService.get(weigthId);
            if(weight==null) {
            	return ResultGenerator.fail("重量方案不存在");
            }

            entity.setRecipeId(recipe.getId());
            entity.setChangeRecipeTime(new Date());
            entity.setWeigthId(weigthId);
            entity.setChangeRecipeUserName(BaseContextHandler.getUsername());
			loadingTaskService.saveOrUpdate(entity);

//			//下发生产任务接口
//    		mMcsInterfaceService.issueMoInterface(entity);

			//装料任务记录
			loadingTaskLogService.saveByLoadingTask(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "重新装料(叫料)任务")
	@PostMapping("/repeatOpen")
	public Result repeatOpenTask(@ApiParam(value = "任务ID") @RequestParam Long id) {
		try {
			loadingTaskService.repeatOpenTask(id);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}


    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "退料任务")
	@PostMapping("/backTask")
	public Result backTask(@ApiParam(value = "任务ID") @RequestParam Long id,@ApiParam(value = "退料原因") @RequestParam String cause) {
		try {
			loadingTaskService.backTask(id, cause);
		}catch (Exception e){
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
    	return ResultGenerator.success();
	}


	@Jinko(value = "配料部分退料", author = "wxl")
	@ApiOperation(value = "配料部分退料")
	@PostMapping("/materialReturn")
	public Result materialReturn(@RequestBody @Valid @ApiParam(value = "部分退料对象") PartReturnMaterialDto dto) {
		try {
			loadingTaskService.materialReturn(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

	@Jinko(value = "配料部分退料", author = "wxl")
	@ApiOperation(value = "获取配料信息")
	@PostMapping("/findMaterialList")
	public Result findMaterialList(@ApiParam(value = "任务ID") @RequestParam Long id) {
		List<ProductionMaterialReturnRecordDto> productionMaterialReturnRecordDtos;
		try {
			productionMaterialReturnRecordDtos = loadingTaskService.findMaterialList(id);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success(productionMaterialReturnRecordDtos);
	}


    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "变更生产状态")
	@PostMapping("/changeStateProduction")
	public Result changeStateProduction(@ApiParam(value = "任务ID") @RequestParam Long id) {
		LoadingTask task = loadingTaskService.get(id);
		if(task.getRawStatus().equals(LoadingTaskDto.rawStatus_0)) {
			task.setRawStatus(LoadingTaskDto.rawStatus_1);
    		task.setUserName(BaseContextHandler.getUsername());
    		task.setOperationTime(new Date());
    		loadingTaskService.saveOrUpdate(task);

//    		//下发生产任务接口
//    		mMcsInterfaceService.issueMoInterface(task);

			//装料任务记录
			loadingTaskLogService.saveByLoadingTask(task);
    		return ResultGenerator.success();
		}else {
			return ResultGenerator.fail("非新建状态无法变更生产");
		}
	}


    @ApiOperation(value = "更新任务信息（机台号,类型）")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "任务信息") LoadingTaskDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }

        LoadingTask entity = loadingTaskService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }

        try {
        	entity.setEquipmentCode(dto.getEquipmentCode());
        	entity.setProductType(dto.getProductType());
        	loadingTaskService.saveOrUpdate(entity);

//        	//下发生产任务接口
//    		mMcsInterfaceService.issueMoInterface(entity);

			//装料任务记录
			loadingTaskLogService.saveByLoadingTask(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "变更自动完工状态  - 对外接口")
	@PostMapping("/changeStateAutoSuccess")
	public Result changeStateAutoSuccess(@Valid @RequestParam @ApiParam(value = "自动完工接口参数对象") AutoSuccessTaskDto dto, BindingResult bindingResult) {
		LoadingTask task = loadingTaskService.get(dto.getId());
		if(task.getRawStatus().equals(LoadingTaskDto.rawStatus_1)) {
			if(dto.getRawStatus().equals(AutoSuccessTaskDto.rawStatus_1) || dto.getRawStatus().equals(AutoSuccessTaskDto.rawStatus_2)) {
				task.setRawStatus(LoadingTaskDto.rawStatus_3);
	    		loadingTaskService.saveOrUpdate(task);

//	    		//下发生产任务接口
//	    		mMcsInterfaceService.issueMoInterface(task);

	    		blastFurnaceDetailService.addBlastFurnace(toEagerDto(task), dto.getDetails(),LoadingTaskDto.rawStatus_3,"自动完工");
				return ResultGenerator.success();
			}else {
				return ResultGenerator.fail("非法状态参数【1：正常完成；2：异常结束】");
			}

		}else {
			return ResultGenerator.fail("非生产态无法变更完成");
		}
	}


    @SuppressWarnings("rawtypes")
	@ApiOperation(value = "变更人工完工状态 - 对外接口 ")
	@PostMapping("/changeStateManualSuccess")
	public Result changeStateManualSuccess(@Valid @RequestParam @ApiParam(value = "人工完工接口参数对象") AutoSuccessTaskDto dto, BindingResult bindingResult) {
		LoadingTask task = loadingTaskService.get(dto.getId());
		if(task.getRawStatus().equals(LoadingTaskDto.rawStatus_1)) {
			if(dto.getRawStatus().equals(AutoSuccessTaskDto.rawStatus_1) || dto.getRawStatus().equals(AutoSuccessTaskDto.rawStatus_2)) {
	    		loadingTaskService.saveOrUpdate(task);

//	    		//下发生产任务接口
//	    		mMcsInterfaceService.issueMoInterface(task);

	    		blastFurnaceDetailService.addBlastFurnace(toEagerDto(task), dto.getDetails(),LoadingTaskDto.rawStatus_4,"手动完工");
				return ResultGenerator.success();
			}else {
				return ResultGenerator.fail("非法状态参数【1：正常完成；2：异常结束】");
			}

		}else {
			return ResultGenerator.fail("非生产态无法变更完成");
		}
	}


	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "取消装料任务")
	@PostMapping("/cancel")
	public Result cancelTask(@ApiParam(value = "任务ID") @RequestParam Long id,@ApiParam(value = "取消原因") @RequestParam String cause) {
		try {
			loadingTaskService.cancelTask(id,cause);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "获取坩埚高度")
	@PostMapping("/getDefaultCrucibleHeight")
	public Result<String> getDefaultCrucibleHeight(@ApiParam(value = "任务ID") @RequestParam Long id) {
		//TODO 后续eap上获取
		//目前获取设备号最新的数据
		LoadingTask loadingTask = loadingTaskService.get(id);
		String equipmentCode = loadingTask.getEquipmentCode();
		//获取最新的那条数据
		String defaultHeight = loadingTaskService.getLastOneHeight(equipmentCode);
		return ResultGenerator.success(defaultHeight);
	}


	@ApiOperation(value = "配料查询配料方案")
	@PostMapping("/getRecipeByLoadingTaskId")
	public Result<List<ProductionBucketRecipeRecordDto>> getRecipeByLoadingTaskId(@ApiParam(value = "任务ID") @RequestParam Long id,@ApiParam(value = "尺寸高度") @RequestParam String height) {
		/*String weight1 = dictionaryItemService.findValueByThemeValueAndItemName("SyggHeight",height);
		if(null == weight1){
			return ResultGenerator.fail("字典未配置数据");
		}
		BigDecimal weight = new BigDecimal(weight1);
		LoadingTask task = loadingTaskService.get(id);
		Long recipeId = task.getRecipeId();
		List <ProductionCircleRecipeDetail> productionCircleRecipeDetails = productionCircleRecipeDetailService.getProductionCircleRecipeDetailsByParam(recipeId,"%初始装料%");
		if(null == productionCircleRecipeDetails || productionCircleRecipeDetails.size() <= 0){
			return ResultGenerator.fail("该产品未绑定产品配方");
		}
		List<ProductionCircleRecipeDetailDto> dtos = productionCircleRecipeDetails.stream().map(temp-> modelMapper.map(temp, ProductionCircleRecipeDetailDto.class)).collect(Collectors.toList());
		List<ProductionBucketRecipeRecordDto> productionBucketRecipeRecordDtos = new ArrayList<>();
		for(ProductionCircleRecipeDetailDto temp:dtos){
			ProductionBucketRecipeRecordDto dto = new ProductionBucketRecipeRecordDto();
			Integer weightRatio = temp.getWeightRatio();
			if (weightRatio == 0){
				continue;
			}
			Map<String,Integer> map = calculateWeight(weightRatio,weight);
			dto.setWeight(map.get("weight"));
			dto.setBucketForty(map.get("bucketForty"));
			dto.setBucketTen(map.get("bucketTen"));
			dto.setRecipeKind(temp.getRecipeKind());
			dto.setSuppliesName(temp.getSuppliesName());
			dto.setSuppliesType(temp.getSuppliesType());
			dto.setGross(Integer.valueOf(weight.toString()));
			dto.setSuppliesCode(temp.getSuppliesCode());
			dto.setSuppliesDopant(temp.getSuppliesDopant());
			dto.setSuppliesGrainMax(temp.getSuppliesGrainMax());
			dto.setSuppliesGrainMin(temp.getSuppliesGrainMin());
			dto.setSuppliesResistanceMax(temp.getSuppliesResistanceMax());
			dto.setSuppliesResistanceMin(temp.getSuppliesResistanceMin());
			dto.setPriority(temp.getPriority());
			productionBucketRecipeRecordDtos.add(dto);
		}
		return ResultGenerator.success(productionBucketRecipeRecordDtos);*/
		return ResultGenerator.success();
	}



	@ApiOperation(value = "PC配料查询配料方案")
	@PostMapping("/getPcRecipeByLoadingTaskId")
	public Result<Map<String,List<ProductionBucketRecipeRecordDto>>> getPcRecipeByLoadingTaskId(@ApiParam(value = "任务ID") @RequestParam Long id,@ApiParam(value = "尺寸高度") @RequestParam String height) {
		Map<String,List<ProductionBucketRecipeRecordDto>> productionBucketRecipeRecordDtos = null;
		try {
			//productionBucketRecipeRecordDtos  = loadingTaskService.getRecipeByLoadingTaskId(id,height);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success(productionBucketRecipeRecordDtos);

	}


	@ApiOperation(value = "保存配料任务配方方案")
	@PostMapping("/saveLoadingRecipe")
	public Result saveLoadingRecipe(@Valid @RequestBody @ApiParam(value = "配料方案") List<LoadingTaskRecipeDto> dtos) {
		try {
			if(dtos == null||dtos.size() <= 0){
				return ResultGenerator.fail("无数据");
			}
			Long loadingTaskId = dtos.get(0).getLoadingTaskId();
			if(null == loadingTaskId){
				return ResultGenerator.fail("无配料任务id");
			}
			//TODO 保存坩埚尺寸
			loadingTaskRecipeService.deleteByLoadingTaskId(loadingTaskId);
			List<LoadingTaskRecipe> loadingTaskRecipes = new ArrayList<>();
			for(LoadingTaskRecipeDto dto:dtos){
				dto.setId(null);
				LoadingTaskRecipe entity = fromDto(dto);
				entity.setCreateBy(BaseContextHandler.getUsername());
				entity.setCreateTime(new Date());
				loadingTaskRecipes.add(entity);
			}
			loadingTaskRecipeService.saveAll(loadingTaskRecipes);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "查询配料任务配方方案")
	@GetMapping("/findLoadingRecipe")
	public Result findLoadingRecipe(@ApiParam(value = "任务ID") @RequestParam Long loadingTaskId) {
		List<LoadingTaskRecipe> loadingTaskRecipes = loadingTaskRecipeService.findByLoadingTaskId(loadingTaskId);
		if(loadingTaskRecipes == null || loadingTaskRecipes.size() <= 0){
			return ResultGenerator.success(null);
		}
		List<LoadingTaskRecipeDto> loadingTaskRecipeDtos = new ArrayList<>();
		for(LoadingTaskRecipe entity:loadingTaskRecipes){
			LoadingTaskRecipeDto dto = toLazyDto(entity);
			loadingTaskRecipeDtos.add(dto);
		}
		return ResultGenerator.success(loadingTaskRecipeDtos);
	}


	@ApiOperation(value = "查询配料任务重量方案")
	@GetMapping("/findWeightScheme")
	public Result findWeightScheme(@ApiParam(value = "任务ID") @RequestParam Long loadingTaskId) {
		LoadingTask task = loadingTaskService.get(loadingTaskId);
		if (task == null) return ResultGenerator.fail("未查询到配料任务");

		// 获取分桶数据
		List<ProductionFurnaceMaterialSplit> splitList = splitService.findByLotNoAndAgainNum(task.getLotNo(), 0);

		if (CollectionUtils.isEmpty(splitList)){
			// 获取桶分解方案
			DecompositionSchemeParam decompositionSchemeParam = new DecompositionSchemeParam();
			decompositionSchemeParam.setEquipmentCode(task.getEquipmentCode());
			decompositionSchemeParam.setProductModeCode(task.getProductCode());
			decompositionSchemeParam.setWeight(null);
			decompositionSchemeParam.setType(1);
			decompositionSchemeParam.setRepeatTimes(0);
			decompositionSchemeParam.setIsFillEnd(0);
			FormulaSchemeData formulaSchemeData;
			try {
				formulaSchemeData = formulaSchemeOutService.decompositionScheme(decompositionSchemeParam);
			}catch (Exception e){
				log.error("初装获取桶数分解方案：", e);
				return ResultGenerator.fail(e.getMessage());
			}
			if (ObjectUtils.isEmpty(formulaSchemeData)) {
				return ResultGenerator.fail("未获取到桶分解数据！");
			}

			// 保存桶分解数据
			splitList = new ArrayList<>();
			for (FormulaSchemeData.FormulaSchemeDataDetail schemeData : formulaSchemeData.getDetail()) {
				List<FormulaSchemeData.LoadingDetail> detailList = schemeData.getLoadingDetails();
				for (FormulaSchemeData.LoadingDetail detail : detailList) {
					ProductionFurnaceMaterialSplit split = new ProductionFurnaceMaterialSplit();
					split.setEquipmentCode(task.getEquipmentCode());
					split.setLotNo(task.getLotNo());
					split.setRawType(0);
					split.setAgainNum(0);
					split.setProductCode(task.getProductCode());
					split.setTaskId(task.getId());
					split.setSplitInfo(formulaSchemeData, schemeData, detail);
					splitList.add(split);
				}
			}

			// 更新桶分解记录数据
			splitService.deleteByTaskIdAndAgainNum(task.getId(), 0);
			splitService.saveAll(splitList);

			// 配料任务关联配方方案和重量方案
			task.setRecipeId(formulaSchemeData.getSchemeId());
			task.setWeigthId(formulaSchemeData.getWeightSchemeId());
			loadingTaskService.saveOrUpdate(task);
		}

		// 转换为页面展示数据
		List<BucketWeightDto> dtoList = new ArrayList<>();
		BucketWeightDto dto = new BucketWeightDto();
		dto.splitDetails2BucketWeightDtoList(splitList);
		dtoList.add(dto);

		return ResultGenerator.success(dtoList);
	}


	/**
	 * 查询装料(配料)明细表中坩埚信息
	 * @param lotNo
	 * @return
	 */
	@ApiOperation(value = "查询装料(配料)明细表中坩埚信息")
	@GetMapping("/findCrucibleInfoByLotNo")
	public Result<Map<String, Object>> findCrucibleInfoByLotNo(String lotNo) {
		return ResultGenerator.success(loadingTaskService.findCrucibleInfoByLotNo(lotNo));
	}

	/**
	 * 打印接口
	 */
	@ApiOperation(value = "根据配料任务id查询打印信息")
	@GetMapping("/findIngredientInfoById")
	public Result<IngredientInfoDto> findIngredientInfoById(@RequestParam("id") Long id) {
		return ResultGenerator.success(loadingTaskService.findIngredientInfoById(id));
	}
	private Map<String, Integer> calculateWeight(Integer weightRatio, BigDecimal weightBucket) {
		Map<String, Integer> map = new HashMap<>();
		//比例
		BigDecimal ratio = new BigDecimal(Integer.parseInt(weightRatio.toString()));
		BigDecimal tempRatio = ratio.divide(new BigDecimal("1000"));
		//算出配料重量(五舍六入)
		BigDecimal weight = weightBucket.multiply(tempRatio).setScale(0,BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal("10"));
		//取余
		BigDecimal[] result1 = weight.divideAndRemainder(new BigDecimal("40"));
		Integer bucketForty = Integer.parseInt(result1[0].toString());
		BigDecimal remainder = result1[1];
		BigDecimal[] result2 = remainder.divideAndRemainder(new BigDecimal("10"));
		Integer bucketTen = Integer.parseInt(result2[0].toString());
		map.put("weight",Integer.parseInt(weight.toString()));
		map.put("bucketForty",bucketForty);
		map.put("bucketTen",bucketTen);
		return map;
	}


	@ApiOperation(value = "配料任务导出")
	@GetMapping("/export")
	public void export(InputFurnaceBurdenExportParam param, HttpServletResponse response){
		if (StringUtils.isBlank(param.getSearch_GTE_operationTime()) || StringUtils.isBlank(param.getSearch_LTE_operationTime())){
			throw new RuntimeException("配料时间不能空");
		}
		List<Map<String, Object>> mapList = loadingTaskService.findTaskAndDetails(param);
		List<TaskDetailExportDto> list = mapList.stream()
				.map(item -> JSON.parseObject(JSON.toJSONString(item), TaskDetailExportDto.class))
				.collect(Collectors.toList());

		// 从线边仓补充物料信息
		// loadingTaskService.addMaterialInfoFromWarehouse(list);

		// 转换供应商编码
		for (TaskDetailExportDto dto : list) {
			DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("crucibleSupplier", dto.getFactoryBrand(), true);
			if (ObjectUtils.isEmpty(item)) continue;
			dto.setFactoryBrand(item.getValue());
		}

		try {
			EasyExcelUtils.write(response, TaskDetailExportDto.class, "配料任务及明细", "配料任务及明细", list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public LoadingTaskDto toLazyDto(LoadingTask entity) {
		return modelMapper.map(entity, LoadingTaskDto.class);
	}

	public LoadingTaskRecipeDto toLazyDto(LoadingTaskRecipe entity) {
		return modelMapper.map(entity, LoadingTaskRecipeDto.class);
	}

	public LoadingTaskRecipe fromDto(LoadingTaskRecipeDto entity) {
		return modelMapper.map(entity, LoadingTaskRecipe.class);
	}

	public LoadingTaskDto toEagerDto(LoadingTask entity) {
		LoadingTaskDto dto = modelMapper.map(entity, LoadingTaskDto.class);
		return dto;
	}

	public LoadingTask fromDto(LoadingTaskDto dto) {
		return modelMapper.map(dto, LoadingTask.class);
	}
}
