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

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.BeanUtil;
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.ProductionRecycledMaterialDto;
import com.sw.mes.yb.production.entity.ProductionRecycledMaterial;
import com.sw.mes.yb.production.service.ProductionRecycledMaterialService;
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.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
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;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/productionRecycledMaterial")
@Slf4j
@Api(description = "单晶回收料信息接口")
public class ProductionRecycledMaterialController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ProductionRecycledMaterialService productionRecycledMaterialService;

	@ApiOperation(value = "分页查询单晶回收料信息列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_EQ_lotNo", value = "炉次号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_sn", value = "单晶编号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_createTime", value = "开始时间（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "search_LTE_createTime", value = "结束时间（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<ProductionRecycledMaterialDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<ProductionRecycledMaterial> specification = DynamicSpecifications.bySearchFilter(request, ProductionRecycledMaterial.class);
    	Page<ProductionRecycledMaterial> page = productionRecycledMaterialService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<ProductionRecycledMaterialDto> 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<ProductionRecycledMaterialDto>> listAll(ServletRequest request) {
		Specification<ProductionRecycledMaterial> specification = DynamicSpecifications.bySearchFilter(request, ProductionRecycledMaterial.class);
		List<ProductionRecycledMaterial> productionRecycledMaterials = productionRecycledMaterialService.findByExampleSort(specification, null);
		List<ProductionRecycledMaterialDto> productionRecycledMaterialDtos = productionRecycledMaterials.stream()
					.map(productionRecycledMaterial -> toLazyDto(productionRecycledMaterial))
					.collect(Collectors.toList());
		return ResultGenerator.success(productionRecycledMaterialDtos);
	}

	@ApiOperation(value = "单晶回收料信息详细信息")
	@GetMapping("/{id}")
	public Result<ProductionRecycledMaterialDto> get(@PathVariable @ApiParam(value="单晶回收料信息id") Long id) {
		ProductionRecycledMaterial productionRecycledMaterial = productionRecycledMaterialService.get(id);
		if (null == productionRecycledMaterial)
			return ResultGenerator.fail("该单晶回收料信息不存在");
		return ResultGenerator.success(toEagerDto(productionRecycledMaterial));
	}

	@ApiOperation(value = "创建单晶回收料信息")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "单晶回收料信息对象") ProductionRecycledMaterialDto productionRecycledMaterialDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		ProductionRecycledMaterial productionRecycledMaterial = fromDto(productionRecycledMaterialDto);
		productionRecycledMaterial.setCreateTime(new Date());
		productionRecycledMaterial.setCreateBy(BaseContextHandler.getUsername());
		productionRecycledMaterialService.saveOrUpdateInfo(productionRecycledMaterial);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新单晶回收料信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "单晶回收料信息") ProductionRecycledMaterialDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            ProductionRecycledMaterial entity = productionRecycledMaterialService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ProductionRecycledMaterial entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			entity.setUpdateTime(new Date());
			entity.setUpdateUser(BaseContextHandler.getUsername());
			productionRecycledMaterialService.saveOrUpdateInfo(entity);
            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) {
			productionRecycledMaterialService.delete(id);
		}
		return ResultGenerator.success();
	}

	public ProductionRecycledMaterialDto toLazyDto(ProductionRecycledMaterial entity) {
		return modelMapper.map(entity, ProductionRecycledMaterialDto.class);
	}

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

	public ProductionRecycledMaterial fromDto(ProductionRecycledMaterialDto dto) {
		return modelMapper.map(dto, ProductionRecycledMaterial.class);
	}


}
