package com.sw.mes.inspect.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 com.sw.mes.inspect.dto.AutomaticInspectMiddleDto;
import com.sw.mes.inspect.entity.AutomaticInspectMiddle;
import com.sw.mes.inspect.service.AutomaticInspectMiddleService;
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.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/automaticInspectMiddle")
@Slf4j
@Api(description = "中间段自动检验接口")
public class AutomaticInspectMiddleController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AutomaticInspectMiddleService automaticInspectMiddleService;

	@ApiOperation(value = "分页查询中间段自动检验列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<AutomaticInspectMiddleDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<AutomaticInspectMiddle> specification = DynamicSpecifications.bySearchFilter(request, AutomaticInspectMiddle.class);
    	Page<AutomaticInspectMiddle> page = automaticInspectMiddleService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AutomaticInspectMiddleDto> 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<AutomaticInspectMiddleDto>> listAll(ServletRequest request) {
		Specification<AutomaticInspectMiddle> specification = DynamicSpecifications.bySearchFilter(request, AutomaticInspectMiddle.class);
		List<AutomaticInspectMiddle> automaticInspectMiddles = automaticInspectMiddleService.findByExampleSort(specification, null);
		List<AutomaticInspectMiddleDto> automaticInspectMiddleDtos = automaticInspectMiddles.stream()
					.map(automaticInspectMiddle -> toLazyDto(automaticInspectMiddle))
					.collect(Collectors.toList());
		return ResultGenerator.success(automaticInspectMiddleDtos);
	}

	@ApiOperation(value = "中间段自动检验详细信息")
	@GetMapping("/{id}")
	public Result<AutomaticInspectMiddleDto> get(@PathVariable @ApiParam(value="中间段自动检验id") Long id) {
		AutomaticInspectMiddle automaticInspectMiddle = automaticInspectMiddleService.get(id);
		if (null == automaticInspectMiddle)
			return ResultGenerator.fail("该中间段自动检验不存在");
		return ResultGenerator.success(toEagerDto(automaticInspectMiddle));
	}

	@ApiOperation(value = "创建中间段自动检验")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "中间段自动检验对象") AutomaticInspectMiddleDto automaticInspectMiddleDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		AutomaticInspectMiddle automaticInspectMiddle = fromDto(automaticInspectMiddleDto);
		automaticInspectMiddleService.saveOrUpdate(automaticInspectMiddle);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新中间段自动检验")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "中间段自动检验") AutomaticInspectMiddleDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            AutomaticInspectMiddle entity = automaticInspectMiddleService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            AutomaticInspectMiddle entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			automaticInspectMiddleService.saveOrUpdate(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 Integer[] ids) {
		for (Integer id : ids) {
				automaticInspectMiddleService.delete(id);
		}
		return ResultGenerator.success();
	}

	public AutomaticInspectMiddleDto toLazyDto(AutomaticInspectMiddle entity) {
		return modelMapper.map(entity, AutomaticInspectMiddleDto.class);
	}

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

	public AutomaticInspectMiddle fromDto(AutomaticInspectMiddleDto dto) {
		return modelMapper.map(dto, AutomaticInspectMiddle.class);
	}


}
