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

import com.sw.common.accessory.server.dto.ApplyRecordDto;
import com.sw.common.accessory.server.dto.ReturnRecordDto;
import com.sw.common.accessory.server.entity.ApplyRecord;
import com.sw.common.accessory.server.entity.ReturnRecord;
import com.sw.common.accessory.server.service.ReturnRecordService;
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;


/**
 * @author zhaowenjie
 */
@RestController
@RequestMapping("/returnRecord")
@Slf4j
@Api(tags = "辅料退库记录接口")
public class ReturnRecordController {

    @Autowired
    private ReturnRecordService returnRecordService;

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

    @ApiOperation(value = "获取所有辅料退库记录")
    @GetMapping("/listAll")
    public Result<List<ReturnRecordDto>> listAll(ServletRequest request) {
        Specification<ReturnRecord> specification = DynamicSpecifications.bySearchFilter(request, ReturnRecord.class);
        List<ReturnRecord> returnRecords = returnRecordService.findByExampleSort(specification, null);
        List<ReturnRecordDto> returnRecordDtos = returnRecords.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(returnRecordDtos);
    }

    @ApiOperation(value = "辅料退库记录详细信息")
    @GetMapping("/{id}")
    public Result<ReturnRecordDto> get(@PathVariable @ApiParam(value = "辅料退库记录id") Long id) {
        ReturnRecord returnRecord = returnRecordService.get(id);
        if (null == returnRecord) {
            return ResultGenerator.fail("该辅料退库记录不存在");
        }
        return ResultGenerator.success(toEagerDto(returnRecord));
    }

    @ApiOperation(value = "创建辅料退库记录")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "辅料退库记录对象") ReturnRecordDto returnRecordDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ReturnRecord returnRecord = fromDto(returnRecordDto);
        returnRecordService.saveOrUpdate(returnRecord);
        return ResultGenerator.success();
    }

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

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

    public ReturnRecordDto toLazyDto(ReturnRecord entity) {
        ReturnRecordDto returnRecordDto = new ReturnRecordDto();
        BeanUtils.copyProperties(entity, returnRecordDto);
        return returnRecordDto;
    }

    public ReturnRecordDto toEagerDto(ReturnRecord entity) {
        ReturnRecordDto returnRecordDto = new ReturnRecordDto();
        BeanUtils.copyProperties(entity, returnRecordDto);
        return returnRecordDto;
    }

    public ReturnRecord fromDto(ReturnRecordDto dto) {
        ReturnRecord returnRecord = new ReturnRecord();
        BeanUtils.copyProperties(dto, returnRecord);
        return returnRecord;
    }


}