package com.sw.mes.yb.pc.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.yb.pc.dto.SideSkinCodingRuleDto;
import com.sw.mes.yb.pc.entity.SideSkinCodingRule;
import com.sw.mes.yb.pc.service.SideSkinCodingRuleService;
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("/SideSkinCodingRule")
@Slf4j
@Api(description = "边皮打码规则接口")
public class SideSkinCodingRuleController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private SideSkinCodingRuleService sideSkinCodingRuleService;

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

    @ApiOperation(value = "获取所有边皮打码规则")
    @GetMapping("/listAll")
    public Result<List<SideSkinCodingRuleDto>> listAll(ServletRequest request) {
        Specification<SideSkinCodingRule> specification = DynamicSpecifications.bySearchFilter(request, SideSkinCodingRule.class);
        List<SideSkinCodingRule> sideSkinCodingRules = sideSkinCodingRuleService.findByExampleSort(specification, null);
        List<SideSkinCodingRuleDto> sideSkinCodingRuleDtos = sideSkinCodingRules.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(sideSkinCodingRuleDtos);
    }

    @ApiOperation(value = "边皮打码规则详细信息")
    @GetMapping("/{id}")
    public Result<SideSkinCodingRuleDto> get(@PathVariable @ApiParam(value = "边皮打码规则id") Integer id) {
        SideSkinCodingRule sideSkinCodingRule = sideSkinCodingRuleService.get(id);
        if (null == sideSkinCodingRule) {
            return ResultGenerator.fail("该边皮打码规则不存在");
        }
        return ResultGenerator.success(toEagerDto(sideSkinCodingRule));
    }

    @ApiOperation(value = "创建边皮打码规则")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "边皮打码规则对象") SideSkinCodingRuleDto ruleDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        //先查询后保存
        Integer count = sideSkinCodingRuleService.findCountBySkinName(ruleDto.getSkinName());
        if (null != count) {
            return ResultGenerator.fail("相同的规则已存在,请重新配置");
        }
        SideSkinCodingRule sideSkinCodingRule = fromDto(ruleDto);
        sideSkinCodingRuleService.saveOrUpdate(sideSkinCodingRule);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新边皮打码规则")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "边皮打码规则") SideSkinCodingRuleDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        SideSkinCodingRule entity = sideSkinCodingRuleService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            SideSkinCodingRule entityFromFto = fromDto(dto);
            BeanUtils.copyProperties(entityFromFto, entity, BeanUtil.getIgnoreProperties(entityFromFto, null, null));
            sideSkinCodingRuleService.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) {
            sideSkinCodingRuleService.delete(id);
        }
        return ResultGenerator.success();
    }

    public SideSkinCodingRuleDto toLazyDto(SideSkinCodingRule entity) {
        return modelMapper.map(entity, SideSkinCodingRuleDto.class);
    }

    public SideSkinCodingRuleDto toEagerDto(SideSkinCodingRule entity) {
        return modelMapper.map(entity, SideSkinCodingRuleDto.class);
    }

    public SideSkinCodingRule fromDto(SideSkinCodingRuleDto dto) {
        return modelMapper.map(dto, SideSkinCodingRule.class);
    }

}
