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

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

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

import cn.hutool.core.collection.CollectionUtil;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.production.entity.FormulaMaterialClass;
import com.sw.mes.production.service.FormulaMaterialClassService;
import com.sw.mes.yb.production.entity.ProductionFurnaceMaterialSplit;
import com.sw.mes.yb.production.service.ProductionFurnaceMaterialSplitService;
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.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.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.production.dto.BlastFurnaceDetail.BlastFurnaceAddDto;
import com.sw.mes.yb.production.dto.BlastFurnaceDetail.BlastFurnaceDetailDto;
import com.sw.mes.yb.production.dto.LoadingTask.LoadingTaskDto;
import com.sw.mes.yb.production.entity.BlastFurnaceDetail;
import com.sw.mes.yb.production.entity.LoadingTask;
import com.sw.mes.yb.production.service.BlastFurnaceDetailService;

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 李儒
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/processLoadingTask/processBlastFurnaceDetail")
@Slf4j
@Api(description = "装料任务/装料(配料)明细表接口")
public class BlastFurnaceDetailController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private BlastFurnaceDetailService blastFurnaceDetailService;

	@Autowired
	private FormulaMaterialClassService formulaMaterialClassService;

	@Autowired
	private ProductionFurnaceMaterialSplitService splitService;



	@ApiOperation(value = "获取所有装料(配料)明细表")
	@ApiParam(name = "search_EQ_blastFurnaceId",value = "装料任务Id (LoadingTask.id)",type = "Long",required = true)
	@GetMapping("/listAll")
	public Result<List<BlastFurnaceDetailDto>> listAll(ServletRequest request) {
		if (StringUtils.isEmpty(request.getParameter("search_EQ_blastFurnaceId"))){
			return ResultGenerator.fail("配料任务id不能为空");
		}
		Specification<BlastFurnaceDetail> specification = DynamicSpecifications.bySearchFilter(request, BlastFurnaceDetail.class);
		List<BlastFurnaceDetail> blastFurnaceDetails = blastFurnaceDetailService.findByExampleSort(specification, null);
		List<BlastFurnaceDetailDto> blastFurnaceDetailDtos = blastFurnaceDetails.stream()
					.map(blastFurnaceDetail -> toLazyDto(blastFurnaceDetail))
					.collect(Collectors.toList());
		return ResultGenerator.success(blastFurnaceDetailDtos);
	}

	@ApiOperation(value = "添加装料(配料)明细表")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "装料(配料)明细表对象") BlastFurnaceAddDto addDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}

		if(StringUtils.isBlank(addDto.getVehicleCode())) {
			return ResultGenerator.fail("请输入载具编号");
		}

		if (CollectionUtils.isEmpty(addDto.getBlastFurnaceDetailDtos())){
			return ResultGenerator.fail("投料明细不能为空");
		}

		if (ObjectUtils.isEmpty(addDto.getLoadingTaskDto().getRealWeight())
			|| addDto.getLoadingTaskDto().getRealWeight().compareTo(addDto.getLoadingTaskDto().getWeight()) > 0
			|| addDto.getLoadingTaskDto().getRealWeight().compareTo(new BigDecimal("0")) == 0){
			return ResultGenerator.fail("实际配料重量不符合规则，请检查！");
		}

		// 实际投料与复投重量一致
		if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "checkInputAllWeightMaterial", false)
				&& addDto.getLoadingTaskDto().getRealWeight().compareTo(addDto.getLoadingTaskDto().getWeight()) != 0) {
			return ResultGenerator.fail("实际配料重量必须等于当前任务配料总重量！");
		}

		// 物料分类及重量卡控
		List<BlastFurnaceDetailDto> detailDtoList = addDto.getBlastFurnaceDetailDtos();
		if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "checkMaterialClassAndWeight", false)){
			List<ProductionFurnaceMaterialSplit> splitList = splitService.findByLotNoAndAgainNum(addDto.getLoadingTaskDto().getLotNo(), 0);
			if (CollectionUtil.isEmpty(splitList)){
				throw new RuntimeException("未查询到关联的桶分解数据");
			}
			// 分桶数据分类重量
			Map<String, BigDecimal> classNameWeightMap = splitList.stream().collect(Collectors.toMap(ProductionFurnaceMaterialSplit::getMaterialClassName, ProductionFurnaceMaterialSplit::getMaterialWeight));
			Map<String, BigDecimal> inputClassNameWeightMap = new HashMap<>();
			for (BlastFurnaceDetailDto detailDto : detailDtoList) {
				if (detailDto.getMaterialName().contains("坩埚")) continue;
				List<FormulaMaterialClass> materialClassList = formulaMaterialClassService.findFormulaMaterialClassByMaterialCode(detailDto.getMaterialCode());
				if (CollectionUtils.isEmpty(materialClassList)){
					throw new RuntimeException("物料【"+detailDto.getMaterialCode()+"】未查询到关联的物料分类");
				}
				Set<String> materialClassNameSet = materialClassList.stream().map(FormulaMaterialClass::getName).collect(Collectors.toSet());

				boolean containSign = false;
				for (String materialClassName : materialClassNameSet) {
					if (ObjectUtils.isEmpty(classNameWeightMap.get(materialClassName))) continue;
					// 组织投料分类重量
					inputClassNameWeightMap.put(materialClassName, detailDto.getWeight());
					containSign = true;
				}
				if (!containSign){
					throw new RuntimeException("物料【"+detailDto.getMaterialCode()+"】所属分类【"+StringUtils.join(materialClassNameSet, ",")+"】不在物料搭配中");
				}
			}
			// 检查重量
			for (String cns : classNameWeightMap.keySet()) {
				BigDecimal inputWeight = inputClassNameWeightMap.get(cns);
				if (ObjectUtils.isEmpty(inputWeight)){
					throw new RuntimeException("物料搭配：物料分类【"+cns+"】没有实际投料");
				}
				if (classNameWeightMap.get(cns).compareTo(inputWeight) != 0){
					throw new RuntimeException("物料搭配：物料分类【"+cns+"】的搭配重量与实际投料重量不一致");
				}
			}
		}

		try {
			addDto.getLoadingTaskDto().setCarrierNo(addDto.getVehicleCode());	// 将载具编号设置到任务中
			blastFurnaceDetailService.addBlastFurnace(addDto.getLoadingTaskDto(), detailDtoList, LoadingTaskDto.rawStatus_4,BaseContextHandler.getUsername());
			return ResultGenerator.success();
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}


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

	public BlastFurnaceDetailDto toLazyDto(BlastFurnaceDetail entity) {
		return modelMapper.map(entity, BlastFurnaceDetailDto.class);
	}

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

	public BlastFurnaceDetail fromDto(BlastFurnaceDetailDto dto) {
		return modelMapper.map(dto, BlastFurnaceDetail.class);
	}


}
