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

import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.entity.SearchFilter;
import com.sw.mes.core.entity.SearchFilter.Operator;
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.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.mmcs.service.MMcsInterfaceService;
import com.sw.mes.yb.production.dto.ProductionCircleRecipeDetailDto;
import com.sw.mes.yb.production.dto.ProductionCircleRecipeDetailVo;
import com.sw.mes.yb.production.dto.ProductionCircleRecipeDto;
import com.sw.mes.yb.production.entity.ProductionCircleDosingList;
import com.sw.mes.yb.production.entity.ProductionCircleRecipe;
import com.sw.mes.yb.production.entity.ProductionCircleRecipeDetail;
import com.sw.mes.yb.production.service.ProductionCircleDosingListService;
import com.sw.mes.yb.production.service.ProductionCircleRecipeDetailService;
import com.sw.mes.yb.production.service.ProductionCircleRecipeService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/productionCircleRecipe")
@Slf4j
@Api(description = "配方管理")
public class ProductionCircleRecipeController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ProductionCircleRecipeService productionCircleRecipeService;

	@Autowired
	private ProductionCircleRecipeDetailService productionCircleRecipeDetailService;

	@Autowired
	private ProductionCircleDosingListService productionCircleDosingListService;

	@Autowired
	private MMcsInterfaceService mMcsInterfaceService;

	@ApiOperation(value = "分页查询配方列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "search_EQ_status", value = "状态", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_recipeName", value = "配方名称", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_version", value = "配方版本", dataType = "string", paramType = "query"),
	})
	@RequestMapping(value = "/listByPage", method= RequestMethod.GET)
	public Result<ResponsePage<ProductionCircleRecipe>> listByPage(ServletRequest request, RequestPage page) {

		SearchFilter filter = new SearchFilter("del",Operator.EQ,0);//查询未删除的列表

		Specification<ProductionCircleRecipe> specification = DynamicSpecifications.bySearchFilter(request, ProductionCircleRecipe.class,filter);
		List<ProductionCircleRecipe> obj = productionCircleRecipeService.findByExample(specification, page);
		ResponsePage responsePage = new ResponsePage(obj, page.getTotal());
		return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有生产配方列表")
	@GetMapping("/recipeNameListAll")
	public Result<List<String>> recipeNameListAll(ServletRequest request) {
		List<String> list = productionCircleRecipeService.recipeNameListAll();
		if (list.size() > 0){
			return ResultGenerator.success(list);
		}else {
			return ResultGenerator.fail("配方暂无数据");
		}
	}

	@ApiOperation(value = "获取所有生产配方列表")
	@GetMapping("/listAll")
	public Result<List<ProductionCircleRecipeDto>> listAll(ServletRequest request) {
		SearchFilter filter = new SearchFilter("del",Operator.EQ,0);//查询未删除的列表

		Specification<ProductionCircleRecipe> specification = DynamicSpecifications.bySearchFilter(request, ProductionCircleRecipe.class,filter);
		List<ProductionCircleRecipe> productionCircleRecipes = productionCircleRecipeService.findByExampleSort(specification, null);
		List<ProductionCircleRecipeDto> productionCircleRecipeDtos = productionCircleRecipes.stream()
				.map(productionCircleRecipe -> toLazyDto(productionCircleRecipe))
				.collect(Collectors.toList());
		return ResultGenerator.success(productionCircleRecipeDtos);
	}

	@ApiOperation(value = "圆棒生产配方主体信息")
	@GetMapping("/{id}")
	public Result<ProductionCircleRecipeDto> get(@PathVariable @ApiParam(value="圆棒生产配料列表id") Long id) {
		ProductionCircleRecipe productionCircleRecipe = productionCircleRecipeService.get(id);
		if (null == productionCircleRecipe) {
            return ResultGenerator.fail("该圆棒生产配料列表不存在");
        }
		return ResultGenerator.success(toEagerDto(productionCircleRecipe));
	}

	@ApiOperation(value = "创建圆棒生产配方")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "圆棒生产配料列表对象") ProductionCircleRecipeDto productionCircleRecipeDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		ProductionCircleRecipe productionCircleRecipe = fromDto(productionCircleRecipeDto);
		productionCircleRecipe.setUserId(BaseContextHandler.getUserID());
		productionCircleRecipe.setUserName(BaseContextHandler.getUsername());
		productionCircleRecipe.setCreateTime(new Date());
		productionCircleRecipeService.saveOrUpdate(productionCircleRecipe);


		return ResultGenerator.success();
	}

	@ApiOperation(value = "创建圆棒生产配方详情记录")
	@PostMapping("/createDetail")
	public Result create(@RequestBody @Valid @ApiParam(value = "创建圆棒生产配方详情记录") List<ProductionCircleRecipeDetail> data) {

		if (0 == data.size()) {
            return ResultGenerator.fail("添加数据不能为空");
        }
		ProductionCircleRecipe productionCircleRecipe = new ProductionCircleRecipe();
		productionCircleRecipe.setRecipeName(data.get(0).getRecipeName());
		productionCircleRecipe.setRecipeCode(data.get(0).getRecipeCode());
		productionCircleRecipe.setVersion(data.get(0).getVersion() + 1);
		productionCircleRecipe.setUserId(BaseContextHandler.getUserID());
		productionCircleRecipe.setUserName(BaseContextHandler.getUsername());
		productionCircleRecipe.setCreateTime(new Date());
		productionCircleRecipeService.saveOrUpdate(productionCircleRecipe);
		for (ProductionCircleRecipeDetail datum : data) {
			datum.setId(null);
			datum.setVersion(datum.getVersion() + 1);
			productionCircleRecipeDetailService.saveOrUpdate(datum);
		}

		//MMCS 下发物料配方接口   异步,已完整try捕捉
		//mMcsInterfaceService.mcsRecipeToMmcs();

		return ResultGenerator.success();
	}


	@ApiOperation(value = "圆棒生产配料列表详情详细信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "recipeName", value = "配方名称", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "recipeCode,", value = "版本code", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "version", value = "版本", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/getRecipeDetailsById")
	public Result<List> getRecipeDetailsById(String recipeName,String recipeCode,Integer version) {
		List<ProductionCircleRecipeDetailVo> map = productionCircleRecipeDetailService.getRecipeDetailsById(recipeName,recipeCode,version);
		if (0 == map.size()) {
            return ResultGenerator.fail("该圆棒生产配料列表详情不存在");
        }
		return ResultGenerator.success(map);
	}

	@ApiOperation(value = "更改生产配料状态")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "生产配料id", value = "id", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "当前状态", value = "status", dataType = "integer", paramType = "query"),
	})
	@PostMapping("/updateStatus")
	public Result updateStatus(@RequestParam Long id, @RequestParam Integer status) {

		Result result = productionCircleRecipeService.updateStatus(id, status);

		//MMCS 下发物料配方接口   异步,已完整try捕捉
		//mMcsInterfaceService.mcsRecipeToMmcs();

		return result;
	}


	@ApiOperation(value = "更新圆棒生产配料列表详情")
	@PostMapping("/updateDetail")
	public Result updateDetail(@RequestBody @Valid @ApiParam(value = "更新圆棒生产配料列表详情") List<ProductionCircleRecipeDetail> data) {
		if (data == null) {
            return ResultGenerator.fail("最少也要添加一条物料信息");
		}
		try {
			ProductionCircleRecipe productionCircleRecipe = new ProductionCircleRecipe();
			Integer newestVersion = 0;
			if (StringUtils.isNotBlank(data.get(0).getRecipeName()) && StringUtils.isNotBlank(data.get(0).getRecipeCode())) {
				if (0 == (data.get(0).getVersion())) {
					//版本初始位0,代表新增
					ProductionCircleRecipe recipe = productionCircleRecipeService.getRecipeByProductCodeOrRecipeName(data.get(0).getRecipeName(), data.get(0).getRecipeCode());
					if (null != recipe) {
						return ResultGenerator.fail("已经存在该配料名称或编码,请校验重新输入");
					}
				}else{
					newestVersion = productionCircleRecipeService.getNewestVersion(data.get(0).getRecipeName(),data.get(0).getRecipeCode());
				}
			} else {
				return ResultGenerator.fail("请输入正确的配料名称或编码,不允许为空字符");
			}
			productionCircleRecipe.setRecipeName(data.get(0).getRecipeName());
			productionCircleRecipe.setRecipeCode(data.get(0).getRecipeCode());
			//查出目前的最新版本号
			if(null == newestVersion){
				newestVersion = 0;
			}
			productionCircleRecipe.setVersion(newestVersion+1);
			productionCircleRecipe.setUserId(BaseContextHandler.getUserID());
			productionCircleRecipe.setUserName(BaseContextHandler.getUsername());
			productionCircleRecipe.setCreateTime(new Date());
			productionCircleRecipeService.saveOrUpdate(productionCircleRecipe);
			for (ProductionCircleRecipeDetail datum : data) {
				if (null == datum.getWeightRatio() || datum.getWeightRatio() < 0 || datum.getWeightRatio() > 100) {
					return ResultGenerator.fail("请重新校对重量配比");
				}
				//添加父Id
				datum.setRecipeId(productionCircleRecipe.getId());
				datum.setId(null);
				datum.setVersion(newestVersion+1);
				productionCircleRecipeDetailService.saveOrUpdate(datum);
			}

			//MMCS 下发物料配方接口   异步,已完整try捕捉
			//mMcsInterfaceService.mcsRecipeToMmcs();

			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}


	@ApiOperation(value = "更新圆棒生产配方列表")
	@PostMapping("/update")
	public Result update(@RequestBody @Valid @ApiParam(value = "圆棒生产配料列表") ProductionCircleRecipeDto dto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
		if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
		ProductionCircleRecipe entity = productionCircleRecipeService.get(dto.getId());
		if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
		try {
			ProductionCircleRecipe fto = fromDto(dto);
			fto.setUserId(BaseContextHandler.getUserID());
			fto.setUserName(BaseContextHandler.getUsername());
			fto.setVersion(fto.getVersion()+1);
			fto.setCreateTime(new Date());
			fto.setId(null);
			productionCircleRecipeService.saveOrUpdate(fto);
			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) {
			List<ProductionCircleDosingList> list = productionCircleDosingListService.getObjectByRecipeOId(id);
			if (list != null && list.size() > 0){
				return ResultGenerator.fail("该配方已经在产品中，不可以删除");
			}else {
				ProductionCircleRecipe obj = productionCircleRecipeService.get(id);
				if (obj != null){
					productionCircleRecipeService.deleteAll(obj.getRecipeName(),obj.getRecipeCode(),obj.getVersion());
				}
				productionCircleRecipeService.deleteDel(id);
			}
		}


		//MMCS 下发物料配方接口   异步,已完整try捕捉
		//mMcsInterfaceService.mcsRecipeToMmcs();

		return ResultGenerator.success();
	}

	@ApiOperation(value = "圆棒生产配方根据配方id获取信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "配方id", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "weightId", value = "重量方案id", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/getRecipeDetailById")
	public Result<List> getRecipeDetailById(Long id, Long weightId) {
		List<ProductionCircleRecipeDetailVo> map = productionCircleRecipeDetailService.getRecipeDetailById(id, weightId);
		if (0 == map.size()) {
			return ResultGenerator.fail("该圆棒生产配料列表详情不存在");
		}
		return ResultGenerator.success(map);
	}

	@ApiOperation(value = "获取所有生产,循环,配方详细信息的物料类型列表")
	@GetMapping("/recipeTypeListAll")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "recipeType", value = "物料类型", dataType = "String", paramType = "query"),
	})
	public Result<List<String>> recipeTypeListAll(String recipeType) {

		List<String> list = productionCircleRecipeDetailService.getSuppliesTypeByParam(recipeType);
		if (list.size() > 0) {
			return ResultGenerator.success(list);
		} else {
			return ResultGenerator.fail("暂时未配置物料类型");
		}
	}

	public ProductionCircleRecipeDto toLazyDto(ProductionCircleRecipe entity) {
		return modelMapper.map(entity, ProductionCircleRecipeDto.class);
	}

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

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

	public ProductionCircleRecipe fromDto(ProductionCircleRecipeDto dto) {
		return modelMapper.map(dto, ProductionCircleRecipe.class);
	}

}
