package com.sw.mes.itemclean.clean.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.*;
import com.sw.mes.itemclean.clean.domain.WashingPlan;
import com.sw.mes.itemclean.clean.dto.WashingPlanDto;
import com.sw.mes.itemclean.clean.mapper.WashingPlanMapper;
import com.sw.mes.itemclean.clean.service.WashingPlanService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.util.Date;
import java.util.List;
import java.util.stream.Collectors;



@RestController
@RequestMapping("/WashingPlan")
@Slf4j
@Api(tags = "洗料计划接口")
public class WashingPlanController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private WashingPlanService washingPlanService;

	@Autowired
	private WashingPlanMapper washingPlanMapper;

	@ApiOperation(value = "分页查询洗料计划列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<WashingPlanDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		//分页查询
		QueryWrapper<WashingPlan> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, WashingPlan.class);
		Page<WashingPlan> listPage = washingPlanService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
		List<WashingPlanDto> dtos = listPage.getRecords().stream()
				.map(entity -> toLazyDto(entity))
				.collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
		return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有洗料计划")
	@GetMapping("/listAll")
	public Result<List<WashingPlanDto>> listAll(ServletRequest request) {
		QueryWrapper<WashingPlan> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, WashingPlan.class);
		List<WashingPlan> materialBrokens = washingPlanService.list(queryWrapper);
		List<WashingPlanDto> materialBrokenDtos = materialBrokens.stream()
				.map(materialBroken -> toLazyDto(materialBroken))
				.collect(Collectors.toList());
		return ResultGenerator.success(materialBrokenDtos);
	}

	@ApiOperation(value = "洗料计划详细信息")
	@GetMapping("/{id}")
	public Result<WashingPlanDto> get(@PathVariable @ApiParam(value="洗料计划id") Integer id) {
		WashingPlan materialBroken = washingPlanService.getById(id);
		if (null == materialBroken)
			return ResultGenerator.fail("该对象不存在");
		return ResultGenerator.success(toEagerDto(materialBroken));
	}

	@ApiOperation(value = "创建洗料计划")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "洗料计划对象") WashingPlanDto washingPlanDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		washingPlanDto.setCreateTime(new Date());
		washingPlanDto.setCreateUser(BaseContextHandler.getUsername());
		WashingPlan washingPlan = fromDto(washingPlanDto);
		List<WashingPlanDto> washingPlanDtos = washingPlanService.queryListByParam(washingPlanDto);
		if(null != washingPlanDtos && washingPlanDtos.size() > 0){
			return ResultGenerator.fail("已存在物料名称为【" + washingPlanDto.getMaterialName() + "】，物料编号为【" + washingPlanDto.getMaterialCode() + "】的计划");
		}
		washingPlanService.saveOrUpdate(washingPlan);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新洗料计划")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "洗料计划") WashingPlanDto dto, BindingResult bindingResult) {
		if (bindingResult.hasErrors())
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		if (dto.getId() == null)
			return ResultGenerator.fail("id不能为空");
		WashingPlan entity = washingPlanService.getById(dto.getId());
		if (entity == null)
			return ResultGenerator.fail("原信息不存在");
		try {
			dto.setUpdateTime(new Date());
			dto.setUpdateUser(BaseContextHandler.getUsername());
			WashingPlan entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			washingPlanService.saveOrUpdate(entityfromFto);
			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 Integer[] ids) {
		for (Integer id : ids) {
			washingPlanMapper.deleteById(id);
		}
		return ResultGenerator.success();
	}

	public WashingPlanDto toLazyDto(WashingPlan entity) {
		return modelMapper.map(entity, WashingPlanDto.class);
	}

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

	public WashingPlan fromDto(WashingPlanDto dto) {
		return modelMapper.map(dto, WashingPlan.class);
	}


}
