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

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

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.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.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.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.production.dto.ProductionCircleDosingListDto;
import com.sw.mes.yb.production.entity.ProductionCircleDosingList;
import com.sw.mes.yb.production.service.ProductionCircleDosingListService;

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("/productionCircleDosingList")
@Slf4j
@Api(description = "圆棒生产配料重量方案详情接口")
public class ProductionCircleDosingListController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ProductionCircleDosingListService productionCircleDosingListService;

	@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_productGrade", value = "产品等级", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_productName", value = "产品料号", dataType = "string", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<ProductionCircleDosingListDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		SearchFilter filter = new SearchFilter("del",Operator.EQ,0);//查询未删除的列表

		Specification<ProductionCircleDosingList> specification = DynamicSpecifications.bySearchFilter(request, ProductionCircleDosingList.class,filter);
		Page<ProductionCircleDosingList> page = productionCircleDosingListService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<ProductionCircleDosingListDto> dtos = page.getContent().stream()
				.map(entity -> toLazyDto(entity))
				.collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
		return ResultGenerator.success(responsePage);
	}

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

		Specification<ProductionCircleDosingList> specification = DynamicSpecifications.bySearchFilter(request, ProductionCircleDosingList.class,filter);
		List<ProductionCircleDosingList> productionCircleDosingLists = productionCircleDosingListService.findByExampleSort(specification, null);
		List<ProductionCircleDosingListDto> productionCircleDosingListDtos = productionCircleDosingLists.stream()
				.map(productionCircleDosingList -> toLazyDto(productionCircleDosingList))
				.collect(Collectors.toList());
		return ResultGenerator.success(productionCircleDosingListDtos);
	}

	@ApiOperation(value = "圆棒生产配料重量方案详情详细信息")
	@GetMapping("/{id}")
	public Result<ProductionCircleDosingListDto> get(@PathVariable @ApiParam(value="圆棒生产配料重量方案详情id") Long id) {
		ProductionCircleDosingList productionCircleDosingList = productionCircleDosingListService.get(id);
		if (null == productionCircleDosingList) {
            return ResultGenerator.fail("该圆棒生产配料重量方案详情不存在");
        }
		return ResultGenerator.success(toEagerDto(productionCircleDosingList));
	}

	@ApiOperation(value = "创建圆棒生产配料重量方案详情")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "圆棒生产配料重量方案详情") List<ProductionCircleDosingList> data) {
		if (data == null) {
            return ResultGenerator.fail("至少要有一条选择项");
        }
		try {
			//获取提交数据的产品料号
			List<String> list = data.stream().map(ProductionCircleDosingList::getProductName).collect(Collectors.toList());
			List<String> list1 = productionCircleDosingListService.getAllProductName();
			if(!Collections.disjoint(list,list1)){
				return ResultGenerator.fail("选中项含有已经创建配方");
			}
			for (ProductionCircleDosingList datum : data) {
				if (datum.getId() == null || datum.getId() ==0){
					datum.setUserId(BaseContextHandler.getUserID());
					datum.setUserName(BaseContextHandler.getUsername());
					datum.setCreateTime(new Date());
				}
				productionCircleDosingListService.saveOrUpdate(datum);
			}
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "更新圆棒生产配料重量方案详情")
	@PostMapping("/update")
	public Result update(@RequestBody @Valid @ApiParam(value = "圆棒生产配料重量方案详情") List<ProductionCircleDosingList> data) {
		if (data == null) {
            return ResultGenerator.fail("至少要有一条选择项");
        }
		try {
			for (ProductionCircleDosingList datum : data) {
				if (datum.getId() == null || datum.getId() ==0){
					datum.setUserId(BaseContextHandler.getUserID());
					datum.setUserName(BaseContextHandler.getUsername());
					datum.setCreateTime(new Date());
				}
				productionCircleDosingListService.saveOrUpdate(datum);
			}
			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) {
			productionCircleDosingListService.deleteDel(id);
		}
		return ResultGenerator.success();
	}

	@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) {

		productionCircleDosingListService.updateStatus(id,status);
		return ResultGenerator.success();
	}

	public ProductionCircleDosingListDto toLazyDto(ProductionCircleDosingList entity) {
		return modelMapper.map(entity, ProductionCircleDosingListDto.class);
	}

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

	public ProductionCircleDosingList fromDto(ProductionCircleDosingListDto dto) {
		return modelMapper.map(dto, ProductionCircleDosingList.class);
	}


}
