package com.sw.mes.grade.controller;

import com.alibaba.fastjson.JSON;
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.grade.dto.RuleTestDataDto;
import com.sw.mes.grade.dto.RuleTestLogDto;
import com.sw.mes.grade.entity.RuleTestData;
import com.sw.mes.grade.service.RuleTestDataService;
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.Map;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/ruleTestData")
@Slf4j
@Api(description = "评级测试记录数据接口")
public class RuleTestDataController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private RuleTestDataService ruleTestDataService;

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

    @ApiOperation(value = "分页查询评级测试记录数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "version", value = "版本", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "grade", value = "评级", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "sectionNo", value = "晶段sn", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "评级状态", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPageDetail")
    public Result<ResponsePage<RuleTestLogDto>> listByPageDetail(@RequestParam(required = false) String version, @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate,
                                                                 @RequestParam(required = false) String grade, @RequestParam(required = false) String sectionNo, @RequestParam(required = false) Integer status,
                                                                 RequestPage requestPage) {requestPage.setOrderField(null);
        Page<Map<String, Object>> page = ruleTestDataService.listByPageV2(version, startDate, endDate,  grade ,  sectionNo, status, PageUtil.createPageable(requestPage));
        List<RuleTestLogDto> ruleTestLogDtos = JSON.parseArray(JSON.toJSONString(page.getContent()), RuleTestLogDto.class);
        ResponsePage responsePage = new ResponsePage(ruleTestLogDtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

	@ApiOperation(value = "获取所有评级测试记录数据")
	@GetMapping("/listAll")
	public Result<List<RuleTestDataDto>> listAll(ServletRequest request) {
		Specification<RuleTestData> specification = DynamicSpecifications.bySearchFilter(request, RuleTestData.class);
		List<RuleTestData> ruleTestDatas = ruleTestDataService.findByExampleSort(specification, null);
		List<RuleTestDataDto> ruleTestDataDtos = ruleTestDatas.stream()
					.map(ruleTestData -> toLazyDto(ruleTestData))
					.collect(Collectors.toList());
		return ResultGenerator.success(ruleTestDataDtos);
	}

	@ApiOperation(value = "评级测试记录数据详细信息")
	@GetMapping("/{id}")
	public Result<RuleTestDataDto> get(@PathVariable @ApiParam(value="评级测试记录数据id") Integer id) {
		RuleTestData ruleTestData = ruleTestDataService.get(id);
		if (null == ruleTestData)
			return ResultGenerator.fail("该评级测试记录数据不存在");
		return ResultGenerator.success(toEagerDto(ruleTestData));
	}

	@ApiOperation(value = "创建评级测试记录数据")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "评级测试记录数据对象") RuleTestDataDto ruleTestDataDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		RuleTestData ruleTestData = fromDto(ruleTestDataDto);
		ruleTestDataService.saveOrUpdate(ruleTestData);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新评级测试记录数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "评级测试记录数据") RuleTestDataDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            RuleTestData entity = ruleTestDataService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            RuleTestData entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			ruleTestDataService.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 Long[] ids) {
		for (Long id : ids) {
				ruleTestDataService.delete(id);
		}
		return ResultGenerator.success();
	}

	public RuleTestDataDto toLazyDto(RuleTestData entity) {
		return modelMapper.map(entity, RuleTestDataDto.class);
	}

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

	public RuleTestData fromDto(RuleTestDataDto dto) {
		return modelMapper.map(dto, RuleTestData.class);
	}


}
