package com.sw.common.accessory.server.controller;

import com.sw.common.accessory.server.dto.ReplacementRecordDto;
import com.sw.common.accessory.server.entity.ReplacementRecord;
import com.sw.common.accessory.server.service.ReplacementRecordService;
import com.sw.common.core.request.RequestPage;
import com.sw.common.core.response.ResponsePage;
import com.sw.common.core.response.Result;
import com.sw.common.core.response.ResultGenerator;
import com.sw.common.core.utils.BeanUtil;
import com.sw.common.mybatisplus.entity.Page;
import com.sw.common.mybatisplus.utils.DynamicSpecifications;
import com.sw.common.mybatisplus.utils.PageUtil;
import com.sw.common.mybatisplus.utils.Specification;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;


@RestController
@RequestMapping("/replacementRecord")
@Slf4j
@Api(tags = "辅料跟换记录接口")
public class ReplacementRecordController {
    @Autowired
    private ReplacementRecordService replacementRecordService;

    @ApiOperation(value = "分页查询辅料跟换记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ReplacementRecordDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<ReplacementRecord> specification = DynamicSpecifications.bySearchFilter(request, ReplacementRecord.class);
        Page<ReplacementRecord> page = replacementRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ReplacementRecordDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<ReplacementRecordDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有辅料跟换记录")
    @GetMapping("/listAll")
    public Result<List<ReplacementRecordDto>> listAll(ServletRequest request) {
        Specification<ReplacementRecord> specification = DynamicSpecifications.bySearchFilter(request, ReplacementRecord.class);
        List<ReplacementRecord> replacementRecords = replacementRecordService.findByExampleSort(specification, null);
        List<ReplacementRecordDto> replacementRecordDtos = replacementRecords.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(replacementRecordDtos);
    }

    @ApiOperation(value = "辅料跟换记录详细信息")
    @GetMapping("/{id}")
    public Result<ReplacementRecordDto> get(@PathVariable @ApiParam(value = "辅料跟换记录id") Long id) {
        ReplacementRecord replacementRecord = replacementRecordService.get(id);
        if (null == replacementRecord) {
            return ResultGenerator.fail("该辅料跟换记录不存在");
        }
        return ResultGenerator.success(toEagerDto(replacementRecord));
    }

    @ApiOperation(value = "创建辅料跟换记录")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "辅料跟换记录对象") ReplacementRecordDto replacementRecordDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ReplacementRecord replacementRecord = fromDto(replacementRecordDto);
        replacementRecordService.saveOrUpdate(replacementRecord);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新辅料跟换记录")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "辅料跟换记录") ReplacementRecordDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        ReplacementRecord entity = replacementRecordService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            ReplacementRecord entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            replacementRecordService.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) {
            replacementRecordService.delete(id);
        }
        return ResultGenerator.success();
    }

    public ReplacementRecordDto toLazyDto(ReplacementRecord entity) {
        ReplacementRecordDto replacementRecordDto = new ReplacementRecordDto();
        BeanUtils.copyProperties(entity, replacementRecordDto);
        return replacementRecordDto;
    }

    public ReplacementRecordDto toEagerDto(ReplacementRecord entity) {
        ReplacementRecordDto replacementRecordDto = new ReplacementRecordDto();
        BeanUtils.copyProperties(entity, replacementRecordDto);
        return replacementRecordDto;
    }

    public ReplacementRecord fromDto(ReplacementRecordDto dto) {
        ReplacementRecord replacementRecord = new ReplacementRecord();
        BeanUtils.copyProperties(dto, replacementRecord);
        return replacementRecord;
    }


}