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

import com.sw.common.accessory.server.dto.ApplyRecordDto;
import com.sw.common.accessory.server.entity.ApplyRecord;
import com.sw.common.accessory.server.service.ApplyRecordService;
import com.sw.common.accessory.utils.ExcelUtil;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/applyRecord")
@Slf4j
@Api(tags = "辅料申请记录接口")
public class ApplyRecordController {
    @Autowired
    private ApplyRecordService applyRecordService;

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

    @ApiOperation(value = "获取所有辅料申请记录")
    @GetMapping("/listAll")
    public Result<List<ApplyRecordDto>> listAll(ServletRequest request) {
        Specification<ApplyRecord> specification = DynamicSpecifications.bySearchFilter(request, ApplyRecord.class);
        List<ApplyRecord> applyRecords = applyRecordService.findByExampleSort(specification, null);
        List<ApplyRecordDto> applyRecordDtos = applyRecords.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(applyRecordDtos);
    }

    @ApiOperation(value = "辅料申请记录详细信息")
    @GetMapping("/{id}")
    public Result<ApplyRecordDto> get(@PathVariable @ApiParam(value = "辅料申请记录id") Long id) {
        ApplyRecord applyRecord = applyRecordService.get(id);
        if (null == applyRecord) {
            return ResultGenerator.fail("该辅料申请记录不存在");
        }
        return ResultGenerator.success(toEagerDto(applyRecord));
    }

    @ApiOperation(value = "创建辅料申请记录")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "辅料申请记录对象") ApplyRecordDto applyRecordDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ApplyRecord applyRecord = fromDto(applyRecordDto);
        applyRecordService.saveOrUpdate(applyRecord);
        return ResultGenerator.success();
    }

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


    @ApiOperation(value = "导出辅料申请记录接口")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            Specification<ApplyRecord> specification = DynamicSpecifications.bySearchFilter(request, ApplyRecord.class);
            List<ApplyRecord> applyRecords = applyRecordService.findByExampleSort(specification, null);
            List<ApplyRecordDto> applyRecordDtos = applyRecords.stream()
                    .map(this::toLazyDto)
                    .collect(Collectors.toList());
            ExcelUtil.exportExcel(applyRecordDtos, "辅料申请记录", ApplyRecordDto.class, response);
        } catch (Exception e) {
            throw new RuntimeException("辅料申请记录导出失败，错误信息：" + e.getMessage());
        }
    }

    public ApplyRecordDto toLazyDto(ApplyRecord entity) {
        ApplyRecordDto applyRecordDto = new ApplyRecordDto();
        BeanUtils.copyProperties(entity, applyRecordDto);
        return applyRecordDto;
    }

    public ApplyRecordDto toEagerDto(ApplyRecord entity) {
        ApplyRecordDto applyRecordDto = new ApplyRecordDto();
        BeanUtils.copyProperties(entity, applyRecordDto);
        return applyRecordDto;
    }

    public ApplyRecord fromDto(ApplyRecordDto dto) {
        ApplyRecord applyRecord = new ApplyRecord();
        BeanUtils.copyProperties(dto, applyRecord);
        return applyRecord;
    }


}