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

import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
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.context.BaseContextHandler;
import com.sw.mes.core.enums.EnumValuesFactory;
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.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.mqtt.service.NotificationService;
import com.sw.mes.production.entity.ProductionAgainTaskRecipe;
import com.sw.mes.production.service.ProductionAgainTaskRecipeService;
import com.sw.mes.yb.ipc.service.impl.MaterialOperationClickServiceImpl;
import com.sw.mes.yb.production.dto.AgainTaskDetail.AgainTaskDetailDto;
import com.sw.mes.yb.production.dto.AgainTaskDetail.AgainTaskDetailUpdate;
import com.sw.mes.yb.production.dto.AgainTaskDetail.AgainTaskInstoreDto;
import com.sw.mes.yb.production.dto.*;
import com.sw.mes.yb.production.dto.LoadingTask.FillingTaskVo;
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 io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
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.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/processAgainTaskDetail")
@Slf4j
@Api(description = "复投任务明细接口")
public class AgainTaskDetailController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AgainTaskDetailService againTaskDetailService;

	@Autowired
	private ProductionCircleRecipeService productionCircleRecipeService;
	@Autowired
	private ProductionCircleWeightService productionCircleWeightService;

	@Autowired
	private AgainTaskService againTaskService;

	@Autowired
	private NotificationService notificationService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;
    @Autowired
    private EquipmentService equipmentService;
	@Autowired
	private ProductionAgainTaskRecipeService productionAgainTaskRecipeService;

	@Autowired
	private ProductionFurnaceMaterialSplitService splitService;

	@Autowired
	private ProductionCircleRecipeDetailService productionCircleRecipeDetailService;

	@Autowired
	private FillingTaskRecipeService fillingTaskRecipeService;

	@Autowired
	private InputFurnaceBurdenService inputFurnaceBurdenService;


	@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<AgainTaskDetailDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<AgainTaskDetail> specification = DynamicSpecifications.bySearchFilter(request, AgainTaskDetail.class);
		/*String[] sort = {"againTime DESC"};
		Page<AgainTaskDetail> page = againTaskDetailService.findByExample(specification, PageUtil.createPageable(requestPage, sort));*/
		Page<AgainTaskDetail> page = againTaskDetailService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AgainTaskDetailDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		if (dtos.size()>0){
			this.addThreeNum(dtos);
		}
		if(!CollectionUtils.isEmpty(dtos)){
			for (AgainTaskDetailDto dto : dtos) {
				AgainTask againTask = againTaskService.get(dto.getAgainTaskId());
				if(null != againTask){
					dto.setRemark(againTask.getRemark());
					dto.setTrialType(againTask.getTrialType());
				}

				// 补充桶信息
				setBucketInfo(dto);
			}
		}
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}


	@ApiOperation(value = "分页查询PDA复投任务明细列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@PostMapping("/pdaListByPage")
	public Result<ResponsePage<AgainTaskDetailDto>> pdaListByPage(@RequestBody AgainTaskDetailDto againTaskDetailDto,@ApiIgnore RequestPage requestPage) {
    	Page<AgainTaskDetail> page = againTaskDetailService.findByPdaPage(againTaskDetailDto, PageUtil.createPageable(requestPage));
		List<AgainTaskDetailDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}




	@ApiOperation(value = "满料入库送走")
	@PostMapping("/instore")
	public Result instore(@RequestBody @Valid @ApiParam(value = "满料入库送人对象") AgainTaskInstoreDto againTaskInstoreDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			againTaskDetailService.instoreOperation(againTaskInstoreDto);
			return ResultGenerator.success();
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "取消任务")
	@PostMapping("/cancelTask")
	public Result cancelTask(@ApiParam(value = "任务ID") Long id,@ApiParam(value = "取消原因") String operationCause) {
		try {
			againTaskDetailService.cancelTask(id,operationCause);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}


	@ApiOperation(value = "检查灌料顺序")
	@GetMapping("/checkTaskOrder")
	public Result checkTaskOrder(@ApiParam(value = "灌料任务ID") Long id) {
		if (ObjectUtils.isEmpty(id)) return ResultGenerator.fail("灌料任务ID不能为空");
		String result = againTaskDetailService.checkTaskOrder(id);
		if (StringUtils.isNotBlank(result)){
			return ResultGenerator.fail(result);
		}
		return ResultGenerator.success();
	}


	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "更换配方")
    @PostMapping("/updateCircleRecipe")
    public Result updateCircleRecipe(@ApiParam(value = "任务ID") Long taskId,@ApiParam(value = "配方ID") Long recipeId,@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) 不能为空");
        }

        if (weigthId == null || weigthId<=0) {
            return ResultGenerator.fail("重量方案ID(weigthId) 不能为空");
        }

        try {
        	AgainTaskDetail entity = againTaskDetailService.get(taskId);
            if(entity==null) {
                return ResultGenerator.fail("任务不存在");
            } else if(!entity.getRawStatus().equals(AgainTaskDetailDto.rawStatus_0)) {
            	return ResultGenerator.fail("任务不在新建状态，无法更换配方");
            }
			//如果复投的任务有保存复投任务方案则不允许修改
		  	Long againTaskId = entity.getAgainTaskId();
			List<ProductionAgainTaskRecipe>  productionAgainTaskRecipe = productionAgainTaskRecipeService.findByAgainTaskId(againTaskId);
			if(productionAgainTaskRecipe != null && productionAgainTaskRecipe.size() > 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("重量方案不存在");
            }
			List<AgainTaskDetail> againTaskDetails = againTaskDetailService.findByAgainTaskId(againTaskId);
            if(againTaskDetails != null && againTaskDetails.size() > 0){
				for(AgainTaskDetail detail:againTaskDetails){
					detail.setRecipeId(recipeId);
					detail.setWeigthId(weigthId);
					detail.setChangeRecipeTime(new Date());
					detail.setChangeRecipeUserName(BaseContextHandler.getUsername());
					againTaskDetailService.saveOrUpdate(detail);
				}
			}

          //发送MQTT通知
            MaterialOperationClickServiceImpl.sendAgainTaskDetailMessage(entity, notificationService);

            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 {
			againTaskDetailService.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,
						   @ApiParam(value = "退料桶(1:左桶,2:右桶,3:全部)") @RequestParam Integer bucket) {
		try {
			againTaskDetailService.backTask(id, cause, bucket);
		} catch (Exception e) {
			log.error("退料任务", e);
			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 {
			againTaskDetailService.materialReturn(dto);
		} catch (Exception e) {
			log.error("灌料部分退料", e);
			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 = againTaskDetailService.findMaterialList(id);
		} catch (Exception e) {
			log.error("获取灌料信息", e);
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success(productionMaterialReturnRecordDtos);
	}


	@ApiOperation(value = "更新复投任务明细")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "复投任务明细") AgainTaskDetailUpdate dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        try {

        	againTaskDetailService.updateInfo(dto,dto.getInputFurnaceDetailDtos());

            return ResultGenerator.success();
        } catch (Exception e) {
			log.error("更新复投任务明细", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @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("炉次号不存在");
        }
    }

	@ApiOperation(value = "获取所有复投任务明细")
	@GetMapping("/listAll")
	public Result<List<AgainTaskDetailDto>> listAll(ServletRequest request) {
		Specification<AgainTaskDetail> specification = DynamicSpecifications.bySearchFilter(request, AgainTaskDetail.class);
		List<AgainTaskDetail> againTaskDetails = againTaskDetailService.findByExampleSort(specification, null);
		List<AgainTaskDetailDto> againTaskDetailDtos = againTaskDetails.stream()
					.map(againTaskDetail -> toLazyDto(againTaskDetail))
					.collect(Collectors.toList());
		return ResultGenerator.success(againTaskDetailDtos);
	}

	@ApiOperation(value = "复投任务明细详细信息")
	@GetMapping("/{id}")
	public Result<AgainTaskDetailDto> get(@PathVariable @ApiParam(value="复投任务明细id") Long id) {
		AgainTaskDetail againTaskDetail = againTaskDetailService.get(id);
		if (null == againTaskDetail) {
            return ResultGenerator.fail("该复投任务明细不存在");
        }
		return ResultGenerator.success(toEagerDto(againTaskDetail));
	}

	@ApiOperation(value = "删除复投任务明细")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
		for (Long id : ids) {
			againTaskDetailService.delete(id);
		}
		return ResultGenerator.success();
	}




	@ApiOperation(value = "根据灌料任务Id获取该任务的配料方案")
	@GetMapping("/pdaGetProductionBucketRecipeRecords")
	public Result<List<ProductionBucketVo>> pdaGetProductionBucketRecipeRecords(@ApiParam(value = "taskDetailId", type = "query") @RequestParam Long id) {
		List<ProductionBucketVo> dtoVo = new ArrayList<>();
		/*AgainTaskDetail taskDetail = againTaskDetailService.get(id);
		Long recipeId = taskDetail.getRecipeId();
		Integer againNum = taskDetail.getAgainNum();
		List<ProductionCircleRecipeDetail> productionCircleRecipeDetails;
		//是不是完结复投
		if(taskDetail.getIsDone() == 1){
			productionCircleRecipeDetails = productionCircleRecipeDetailService.getProductionCircleRecipeDetailsByParamAccurate(recipeId,"0");
		}else {
			productionCircleRecipeDetails = productionCircleRecipeDetailService.getProductionCircleRecipeDetailsByParam(recipeId, "%" + againNum.toString() + "%");
		}
		if(null == productionCircleRecipeDetails || productionCircleRecipeDetails.size() <= 0){
            return ResultGenerator.fail("该产品未绑定产品配方");
        }
		List<ProductionCircleRecipeDetailDto> dtos = productionCircleRecipeDetails.stream().map(temp-> modelMapper.map(temp, ProductionCircleRecipeDetailDto.class)).collect(Collectors.toList());
        String weight = taskDetail.getTaskWeigths();
        String painNum = taskDetail.getPailNum();
        String[] weights = weight.split(",");
        String[] painNums = painNum.split(",");
		for(int i = 0;i < weights.length; i++){
			ProductionBucketVo vo = new ProductionBucketVo();
			Integer weightBucket = Integer.valueOf(weights[i]);
			vo.setWeight(weightBucket);
			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,weightBucket);
				dto.setId(temp.getId());
				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.setBucketNum(Integer.valueOf(painNums[i]));
				dto.setGross(weightBucket);
				productionBucketRecipeRecordDtos.add(dto);
			}
			vo.setProductionBucketRecipeRecordDtos(productionBucketRecipeRecordDtos);
			dtoVo.add(vo);
		}*/
		return ResultGenerator.success(dtoVo);
	}


	@ApiOperation(value = "根据灌料任务Id获取该任务的配料方案")
	@GetMapping("/pcGetProductionBucketRecipeRecords")
	public Result<List<ProductionBucketDto>> pcGetProductionBucketRecipeRecords(@ApiParam(value = "taskDetailId", type = "query") @RequestParam Long id) {
		List<ProductionBucketDto> dtoVo = new ArrayList<>();
		AgainTaskDetail taskDetail = againTaskDetailService.get(id);
		Long recipeId = taskDetail.getRecipeId();
		Integer againNum = taskDetail.getAgainNum();
		List<ProductionCircleRecipeDetail> productionCircleRecipeDetails;
		//是不是完结复投
		if(taskDetail.getIsDone() == 1){
			productionCircleRecipeDetails = productionCircleRecipeDetailService.getProductionRecipeDetailsByParam(recipeId,"0");
		}else {
			productionCircleRecipeDetails = productionCircleRecipeDetailService.getProductionRecipeDetailsByParam(recipeId, "%" + againNum.toString() + "%");
		}
		if(null == productionCircleRecipeDetails || productionCircleRecipeDetails.size() <= 0){
			return ResultGenerator.fail("该产品未绑定产品配方");
		}
		Map<String, List<ProductionCircleRecipeDetail>> map1 = productionCircleRecipeDetails.stream().collect(Collectors.groupingBy(ProductionCircleRecipeDetail::getRecipeKind));
		String weight = taskDetail.getTaskWeigths();
		String painNum = taskDetail.getPailNum();
		String[] weights = weight.split(",");
		String[] painNums = painNum.split(",");
		for(int i = 0;i < weights.length; i++){
			ProductionBucketDto vo = new ProductionBucketDto();
			Integer weightBucket = Integer.valueOf(weights[i]);
			vo.setWeight(weightBucket);
			Set set = map1.keySet();
			Iterator iterator = set.iterator();
			Map<String,List<ProductionBucketRecipeRecordDto>> map2 =  new HashMap<>();
			while (iterator.hasNext()) {
				String key = iterator.next().toString();
				List<ProductionCircleRecipeDetail> entitys = map1.get(key);
				List<ProductionCircleRecipeDetailDto> dtos = entitys.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){
						break;
					}
					Map<String,Integer> map = calculateWeight(weightRatio,weightBucket);
					dto.setWeight(map.get("weight"));
					dto.setBucketForty(map.get("bucketForty"));
					dto.setBucketTen(map.get("bucketTen"));
					dto.setId(temp.getId());
					dto.setRecipeKind(temp.getRecipeKind());
					dto.setSuppliesName(temp.getSuppliesName());
					dto.setSuppliesType(temp.getSuppliesType());
					dto.setBucketNum(Integer.valueOf(painNums[i]));
					dto.setGross(weightBucket);
					productionBucketRecipeRecordDtos.add(dto);
				}
				if(productionBucketRecipeRecordDtos.size()>0) {
					map2.put(key, productionBucketRecipeRecordDtos);
				}
			}
			vo.setProductionBucketRecipeRecordDtos(map2);
			dtoVo.add(vo);
		}
		return ResultGenerator.success(dtoVo);
	}

	@ApiOperation(value = "保存灌料任务配方方案")
	@PostMapping("/saveFillingRecipe")
	public Result saveFillingRecipe(@RequestBody @Valid @ApiParam(value = "配料方案") List<FillingTaskRecipeDto> dtos) {
		try {
			if(dtos == null||dtos.size() <= 0){
				return ResultGenerator.fail("无数据");
			}
			Long againTaskDetailId = dtos.get(0).getAgainTaskDetailId();
			if(null == againTaskDetailId){
				return ResultGenerator.fail("无灌料任务id");
			}
			fillingTaskRecipeService.deleteByAgainTaskDetailId(againTaskDetailId);
			List<FillingTaskRecipe> fillingTaskRecipes = new ArrayList<>();
			for(FillingTaskRecipeDto dto:dtos){
				dto.setId(null);
				FillingTaskRecipe entity = fromDto(dto);
				entity.setCreateBy(BaseContextHandler.getUsername());
				entity.setCreateTime(new Date());
				fillingTaskRecipes.add(entity);
			}
			fillingTaskRecipeService.saveAll(fillingTaskRecipes);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "查询灌料任务配方方案")
	@GetMapping("/findFillingRecipe")
	public Result findFillingRecipe(@ApiParam(value = "任务ID") @RequestParam Long againTaskDetailId) {
		List<FillingTaskRecipe> fillingTaskRecipes = fillingTaskRecipeService.findByAgainTaskDetailId(againTaskDetailId);
		if(fillingTaskRecipes == null || fillingTaskRecipes.size() <= 0){
			return ResultGenerator.success(null);
		}
		List<FillingTaskRecipeDto> fillingTaskRecipeDtos = new ArrayList<>();
		for(FillingTaskRecipe entity:fillingTaskRecipes){
			FillingTaskRecipeDto dto = toLazyDto(entity);
			fillingTaskRecipeDtos.add(dto);
		}
		List<FillingTaskVo> fillingTaskVos = new ArrayList<>();
		List<FillingTaskRecipeDto> fillingTaskRecipeDtos1 = new ArrayList<>();
		//合金
		FillingTaskVo fillingTaskVo1 = new FillingTaskVo();
		fillingTaskVo1.setAlloyName("合金");
		for(FillingTaskRecipeDto entity:fillingTaskRecipeDtos){
			if(entity.getSuppliesType().contains("合金")){
				fillingTaskVo1.setAlloyName(entity.getSuppliesType());
				fillingTaskVo1.setAlloyWeight(entity.getWeight());
			}else{
				fillingTaskRecipeDtos1.add(entity);
			}
		}
		fillingTaskVos.add(fillingTaskVo1);
		Map<Integer,List<FillingTaskRecipeDto>> stringListMap = fillingTaskRecipeDtos1.stream().collect(Collectors.groupingBy(entity-> entity.getBucketNum()));
		Set set = stringListMap.keySet();
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			Integer key = Integer.valueOf(iterator.next().toString());
			List<FillingTaskRecipeDto> fillingTaskRecipeDtoList = stringListMap.get(key);
			FillingTaskVo fillingTaskVo = new FillingTaskVo();
			fillingTaskVo.setWeight(fillingTaskRecipeDtoList.get(0).getGross());
			fillingTaskVo.setProductionBucketRecipeRecordDtos(fillingTaskRecipeDtoList);
			fillingTaskVos.add(fillingTaskVo);
		}
		return ResultGenerator.success(fillingTaskVos);
	}

	@ApiOperation(value = "查询灌料任务配方方案V1")
	@GetMapping("/findFillingRecipeV1")
	public Result findFillingRecipeV1(@ApiParam(value = "任务ID") @RequestParam Long againTaskDetailId) {
		RecipeDto recipeDto = null;
		try {
			// recipeDto = againTaskDetailService.findFillingRecipe(againTaskDetailId);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success(recipeDto);
	}


	@ApiOperation(value = "查询灌料任务重量方案")
	@GetMapping("/findWeightScheme")
	public Result findWeightScheme(@ApiParam(value = "任务ID") @RequestParam Long againTaskDetailId) {
		AgainTaskDetail taskDetail = againTaskDetailService.get(againTaskDetailId);
		if (taskDetail == null) return ResultGenerator.fail("灌料任务不存在");

		// 查询数据，封装为页面需要数据
		List<BucketWeightDto> dtoList = new ArrayList<>();
		String[] bucketIndexArr = taskDetail.getPailNum().split(",");
		for (String bucketIndex : bucketIndexArr) {
			List<ProductionFurnaceMaterialSplit> splitList = splitService.findByBucketIndex(
					taskDetail.getAgainTaskId(), taskDetail.getAgainNum(), Integer.valueOf(bucketIndex));
			if (splitList == null || splitList.size() == 0) continue;

			BucketWeightDto dto = new BucketWeightDto();
			dto.splitDetails2BucketWeightDtoList(splitList);
			dtoList.add(dto);
		}

		return ResultGenerator.success(dtoList);
	}


	@ApiOperation(value = "保存灌料任务配方方案V1")
	@PostMapping("/saveFillingRecipeV1")
	public Result saveFillingRecipeV1(@RequestBody @Valid @ApiParam(value = "配料方案") RecipeSaveDto dtoes) {
		try {
			againTaskDetailService.saveFillingRecipeV1(dtoes);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

	/**
	 * 打印接口
	 */
	@ApiOperation(value = "根据灌料任务id查询打印信息")
	@GetMapping("/findIngredientInfoById")
	public Result<IngredientInfoDto> findIngredientInfoById(@RequestParam("id") Long id) {
		return ResultGenerator.success(againTaskDetailService.findIngredientInfoById(id));
	}

	List<AgainTaskDetailDto> addThreeNum (List<AgainTaskDetailDto> dtos){
		for (AgainTaskDetailDto dto : dtos) {
			//本次复投任务
			AgainTask againTask = againTaskService.get(dto.getAgainTaskId());
			if (null != againTask && null != againTask.getAgainNum()){
				if (againTask.getAgainNum() == 1){
					//锅内剩余
					dto.setPotLeftWeight(new BigDecimal(0));
					//上次加完
					dto.setLastTimeWeight(new BigDecimal(0));
					//本次加完
					dto.setThisTimeWeight(againTask.getAgainWeigth());
				}else {
					if (null != againTask.getLotNo()){
						//上次复投任务
						AgainTask byLotNoAndAgainNum = againTaskService.getByLotNoAndAgainNum(againTask.getAgainNum(), againTask.getLotNo());
						if (null != byLotNoAndAgainNum){
							//锅内剩余
							dto.setPotLeftWeight(againTask.getSurplusWeigth());
							if (null != byLotNoAndAgainNum.getSurplusWeigth() && null != byLotNoAndAgainNum.getAgainWeigth()){
								//上次加完
								dto.setLastTimeWeight(byLotNoAndAgainNum.getSurplusWeigth().add(byLotNoAndAgainNum.getAgainWeigth()));
							}
							if (null != againTask.getSurplusWeigth() && null!= againTask.getAgainWeigth()){
								//本次加完
								dto.setThisTimeWeight(againTask.getSurplusWeigth().add(againTask.getAgainWeigth()));
							}
						}
					}
				}
			}
		}
		return dtos;
	}


	private Map<String, Integer> calculateWeight(Integer weightRatio, Integer weightBucket) {
		Map<String, Integer> map = new HashMap<>();
		//总重
		BigDecimal weightBucket1 = new BigDecimal(Integer.parseInt(weightBucket.toString()));
		//比例
		BigDecimal ratio = new BigDecimal(Integer.parseInt(weightRatio.toString()));
		BigDecimal tempRatio = ratio.divide(new BigDecimal("1000"));
		//算出配料重量(五舍六入)
		BigDecimal weight = weightBucket1.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;
	}

	// 补充桶信息
	private void setBucketInfo(AgainTaskDetailDto dto){
		InputFurnaceBurden burden = inputFurnaceBurdenService.findTopByAgainTaskDetailId(dto.getId());
		if (!ObjectUtils.isEmpty(burden)){
			dto.setLeftCode(burden.getLeftCode());
			dto.setLeftWeight(burden.getLeftWeight());
			dto.setLeftBack(burden.getLeftBack());
			dto.setRightCode(burden.getRightCode());
			dto.setRightWeight(burden.getRightWeight());
			dto.setRightBack(burden.getRightBack());
		}
	}

	public AgainTaskDetailDto toLazyDto(AgainTaskDetail entity) {
		return modelMapper.map(entity, AgainTaskDetailDto.class);
	}

	public FillingTaskRecipeDto toLazyDto(FillingTaskRecipe entity) {
		return modelMapper.map(entity, FillingTaskRecipeDto.class);
	}

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

	public AgainTaskDetail fromDto(AgainTaskDetailDto dto) {
		return modelMapper.map(dto, AgainTaskDetail.class);
	}

	public FillingTaskRecipe fromDto(FillingTaskRecipeDto dto) {
		return modelMapper.map(dto, FillingTaskRecipe.class);
	}


}
