package com.sw.mes.yb.seed.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.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.seed.dto.SeedDataDto;
import com.sw.mes.yb.seed.dto.SeedPaintingLineDto;
import com.sw.mes.yb.seed.entity.SeedData;
import com.sw.mes.yb.seed.entity.SeedPaintingLine;
import com.sw.mes.yb.seed.service.SeedPaintingLineService;
import io.swagger.annotations.*;
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.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
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("/seed/decisionRule")
@Api(description = "籽晶判定规则接口")
@Transactional
public class SeedPaintingLineController {

    @Autowired
    private SeedPaintingLineService seedPaintingLineService;

    @Autowired
    ModelMapper modelMapper;

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


    @GetMapping("/listAll")
    @ApiOperation(value = "查询籽晶判定规则信息列表")
    public Result<List<SeedPaintingLineDto>> listAll(ServletRequest request) {
        Specification<SeedPaintingLine> specification = DynamicSpecifications.bySearchFilter(request, SeedPaintingLine.class);
        List<SeedPaintingLine> seedPaintingLines = seedPaintingLineService.findByExampleSort(specification, null);
        List<SeedPaintingLineDto> dtos = seedPaintingLines.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询籽晶判定规则")
    public Result<SeedPaintingLineDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedPaintingLine seedPaintingLine = seedPaintingLineService.get(id);
        if (ObjectUtils.isEmpty(seedPaintingLine)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedPaintingLine));
    }

    @ApiOperation(value = "创建籽晶判定规则")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "SeedDataDto的对象") SeedPaintingLineDto seedPaintingLineDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedPaintingLine seedPaintingLine = seedPaintingLineService.findByRuleName(seedPaintingLineDto.getRuleName());
        if(!ObjectUtils.isEmpty(seedPaintingLine)){
            return ResultGenerator.fail("规则名称已存在,请重新输入!");
        }
        seedPaintingLineDto.setCreateUser(BaseContextHandler.getUsername());
        seedPaintingLineDto.setCreateTime(new Date());
        seedPaintingLineService.saveOrUpdate(fromDto(seedPaintingLineDto));
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新籽晶判定规则")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedDataDto的对象") SeedPaintingLineDto seedPaintingLineDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedPaintingLine seedPaintingLine = seedPaintingLineService.findByRuleName(seedPaintingLineDto.getRuleName());
        if(ObjectUtils.isEmpty(seedPaintingLine)){
            return ResultGenerator.fail("规则不存在,请检查数据!");
        }
        seedPaintingLineDto.setUpdateUser(BaseContextHandler.getUsername());
        seedPaintingLineDto.setUpdateTime(new Date());
        seedPaintingLineService.saveOrUpdate(fromDto(seedPaintingLineDto));
        return ResultGenerator.success();
    }

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

    @GetMapping("/findByRuleName")
    @ApiOperation(value = "通过规则名称查询籽晶判定规则")
    public Result<SeedPaintingLineDto> getById(@RequestParam @ApiParam(value = "ruleName") String ruleName) {
        SeedPaintingLine seedPaintingLine = seedPaintingLineService.findByRuleName(ruleName);
        if (ObjectUtils.isEmpty(seedPaintingLine)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedPaintingLine));
    }

    public SeedPaintingLineDto toLazyDto(SeedPaintingLine entity) {
        SeedPaintingLineDto seedPaintingLineDto = new SeedPaintingLineDto();
        BeanUtils.copyProperties(entity, seedPaintingLineDto);
        return seedPaintingLineDto;
    }

    public SeedPaintingLineDto toEagerDto(SeedPaintingLine entity) {
        SeedPaintingLineDto seedPaintingLineDto = new SeedPaintingLineDto();
        BeanUtils.copyProperties(entity,seedPaintingLineDto);
        return seedPaintingLineDto;
    }

    public SeedPaintingLine fromDto(SeedPaintingLineDto dto) {
        SeedPaintingLine seedPaintingLine = new SeedPaintingLine();
        BeanUtils.copyProperties(dto,seedPaintingLine);
        return seedPaintingLine;
    }
}
