package com.sw.mes.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.DynmaicQueryWrapper;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.store.dto.WarehouseOutputRecordBillDto;
import com.sw.mes.store.entity.WarehouseOutputRecordBill;
import com.sw.mes.store.service.WarehouseOutputRecordBillService;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("//warehouse/outputRecordBill")
@Slf4j
@Api(tags = "出库审核记录单接口")
public class WarehouseOutputRecordBillController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseOutputRecordBillService warehouseOutputRecordBillService;

    @ApiOperation(value = "分页查询出库审核记录单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<WarehouseOutputRecordBillDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        QueryWrapper<WarehouseOutputRecordBill> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseOutputRecordBill.class);
        Page<WarehouseOutputRecordBill> page = new Page<>(requestPage.getPage(), requestPage.getRows());
        String orderDirection = requestPage.getOrderDirection();
        String orderField = requestPage.getOrderField();
        page.addOrder(RequestPage.ORDER_DIRECTION_DESC.equals(orderDirection) ? OrderItem.desc(orderField) : OrderItem.asc(orderField));
        Page<WarehouseOutputRecordBill> listPage = warehouseOutputRecordBillService.page(page, queryWrapper);
        List<WarehouseOutputRecordBillDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage<WarehouseOutputRecordBillDto> responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有出库审核记录单")
    @GetMapping("/listAll")
    public Result<List<WarehouseOutputRecordBillDto>> listAll(ServletRequest request) {
        QueryWrapper<WarehouseOutputRecordBill> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseOutputRecordBill.class);
        List<WarehouseOutputRecordBill> entities = warehouseOutputRecordBillService.list(queryWrapper);
        List<WarehouseOutputRecordBillDto> dtos = entities.stream()
                .map(storeOutputBill -> toLazyDto(storeOutputBill))
                .collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @ApiOperation(value = "出库审核记录单详细信息")
    @GetMapping("/{id}")
    public Result<WarehouseOutputRecordBillDto> get(@PathVariable @ApiParam(value = "出库审核记录单id") Integer id) {
        WarehouseOutputRecordBill warehouseOutputRecordBill = warehouseOutputRecordBillService.getById(id);
        if (null == warehouseOutputRecordBill) {
            return ResultGenerator.fail("该出库审核记录单不存在");
        }
        return ResultGenerator.success(toEagerDto(warehouseOutputRecordBill));
    }

    @ApiOperation(value = "创建出库审核记录单")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "出库审核记录单对象") WarehouseOutputRecordBillDto warehouseOutputRecordBillDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseOutputRecordBill warehouseOutputRecordBill = fromDto(warehouseOutputRecordBillDto);
        warehouseOutputRecordBillService.saveOrUpdate(warehouseOutputRecordBill);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新出库审核记录单")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "出库审核记录单") WarehouseOutputRecordBillDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        WarehouseOutputRecordBill entity = warehouseOutputRecordBillService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            WarehouseOutputRecordBill entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            warehouseOutputRecordBillService.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) {
        warehouseOutputRecordBillService.removeByIds(Arrays.asList(ids));
        return ResultGenerator.success();
    }

    public WarehouseOutputRecordBillDto toLazyDto(WarehouseOutputRecordBill entity) {
        return modelMapper.map(entity, WarehouseOutputRecordBillDto.class);
    }

    public WarehouseOutputRecordBillDto toEagerDto(WarehouseOutputRecordBill entity) {
        WarehouseOutputRecordBillDto dto = modelMapper.map(entity, WarehouseOutputRecordBillDto.class);
        return dto;
    }

    public WarehouseOutputRecordBill fromDto(WarehouseOutputRecordBillDto dto) {
        return modelMapper.map(dto, WarehouseOutputRecordBill.class);
    }
}