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.HeadTailMaterialRuleDto;
import com.sw.mes.yb.pc.entity.HeadTailMaterialRule;
import com.sw.mes.yb.pc.service.HeadTailMaterialRuleService;
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("/HeadTailMaterialRule")
@Slf4j
@Api(description = "头尾料分类规则接口")
public class HeadTailMaterialRuleController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private HeadTailMaterialRuleService headTailMaterialRuleService;

    @ApiOperation(value = "分页查询头尾料分类规则列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<HeadTailMaterialRuleDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<HeadTailMaterialRule> specification = DynamicSpecifications.bySearchFilter(request, HeadTailMaterialRule.class);
        Page<HeadTailMaterialRule> page = headTailMaterialRuleService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<HeadTailMaterialRuleDto> 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<HeadTailMaterialRuleDto>> listAll(ServletRequest request) {
        Specification<HeadTailMaterialRule> specification = DynamicSpecifications.bySearchFilter(request, HeadTailMaterialRule.class);
        List<HeadTailMaterialRule> headTailMaterialRules = headTailMaterialRuleService.findByExampleSort(specification, null);
        List<HeadTailMaterialRuleDto> headTailMaterialRuleDtos = headTailMaterialRules.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(headTailMaterialRuleDtos);
    }

    @ApiOperation(value = "头尾料分类规则详细信息")
    @GetMapping("/{id}")
    public Result<HeadTailMaterialRuleDto> get(@PathVariable @ApiParam(value = "头尾料分类规则id") Integer id) {
        HeadTailMaterialRule headTailMaterialRule = headTailMaterialRuleService.get(id);
        if (null == headTailMaterialRule) {
            return ResultGenerator.fail("该头尾料分类规则不存在");
        }
        return ResultGenerator.success(toEagerDto(headTailMaterialRule));
    }

    @ApiOperation(value = "创建头尾料分类规则")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "头尾料分类规则对象") HeadTailMaterialRuleDto ruleDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        //先查询后保存
        Integer count = headTailMaterialRuleService.findCountByBracketNo(ruleDto.getBracketNo());
        if (null != count) {
            return ResultGenerator.fail("相同的规则已存在,请重新配置");
        }
        HeadTailMaterialRule headTailMaterialRule = fromDto(ruleDto);
        headTailMaterialRuleService.saveOrUpdate(headTailMaterialRule);
        return ResultGenerator.success();
    }

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

    public HeadTailMaterialRuleDto toLazyDto(HeadTailMaterialRule entity) {
        return modelMapper.map(entity, HeadTailMaterialRuleDto.class);
    }

    public HeadTailMaterialRuleDto toEagerDto(HeadTailMaterialRule entity) {
        return modelMapper.map(entity, HeadTailMaterialRuleDto.class);
    }

    public HeadTailMaterialRule fromDto(HeadTailMaterialRuleDto dto) {
        return modelMapper.map(dto, HeadTailMaterialRule.class);
    }


}
