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

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 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.Map;
import java.util.stream.Collectors;
import com.sw.mes.yb.pad.entity.PieceDetail;
import com.sw.mes.yb.pad.dto.PieceDetailDto;
import com.sw.mes.yb.pad.service.PieceDetailService;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/PieceDetail")
@Slf4j
@Api(description = "PieceDetail接口")
public class PieceDetailController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private PieceDetailService pieceDetailService;

	@ApiOperation(value = "分页查询PieceDetail列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<PieceDetailDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<PieceDetail> specification = DynamicSpecifications.bySearchFilter(request, PieceDetail.class);
    	Page<PieceDetail> page = pieceDetailService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<PieceDetailDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有PieceDetail")
	@GetMapping("/listAll")
	public Result<List<PieceDetailDto>> listAll(ServletRequest request) {
		Specification<PieceDetail> specification = DynamicSpecifications.bySearchFilter(request, PieceDetail.class);
		List<PieceDetail> pieceDetails = pieceDetailService.findByExampleSort(specification, null);
		List<PieceDetailDto> pieceDetailDtos = pieceDetails.stream()
					.map(pieceDetail -> toLazyDto(pieceDetail))
					.collect(Collectors.toList());
		return ResultGenerator.success(pieceDetailDtos);
	}

	@ApiOperation(value = "PieceDetail详细信息")
	@GetMapping("/{id}")
	public Result<PieceDetailDto> get(@PathVariable @ApiParam(value="PieceDetailid") Long id) {
		PieceDetail pieceDetail = pieceDetailService.get(id);
		if (null == pieceDetail)
			return ResultGenerator.fail("该PieceDetail不存在");
		return ResultGenerator.success(toEagerDto(pieceDetail));
	}

	@ApiOperation(value = "创建PieceDetail")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "PieceDetail对象") PieceDetailDto pieceDetailDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		PieceDetail pieceDetail = fromDto(pieceDetailDto);
		pieceDetailService.saveOrUpdate(pieceDetail);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新PieceDetail")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "PieceDetail") PieceDetailDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            PieceDetail entity = pieceDetailService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            PieceDetail entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			pieceDetailService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

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

	@ApiOperation(value = "查询样品详情信息追溯")
	@GetMapping ("/queryProductionPieceDetail")
	public Result<List<Map<String,Object>>> queryProductionPieceDetail(@RequestParam(required = false) String pieceNo,
			@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) {
		List<Map<String,Object>> productionPieceDetailVos = pieceDetailService.queryProductionPieceDetail(pieceNo,startDate,endDate);
		return ResultGenerator.success(productionPieceDetailVos);
	}

	public PieceDetailDto toLazyDto(PieceDetail entity) {
		return modelMapper.map(entity, PieceDetailDto.class);
	}

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

	public PieceDetail fromDto(PieceDetailDto dto) {
		return modelMapper.map(dto, PieceDetail.class);
	}


}
