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.WarehouseAllotRecordBillDto;
import com.sw.mes.store.entity.WarehouseAllotRecordBill;
import com.sw.mes.store.service.WarehouseAllotRecordBillService;
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/allotRecordBill")
@Slf4j
@Api(tags = "调拨审核记录单接口")
public class WarehouseAllotRecordBillController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseAllotRecordBillService warehouseAllotRecordBillService;

    @ApiOperation(value = "分页查询调拨审核记录单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<WarehouseAllotRecordBillDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        QueryWrapper<WarehouseAllotRecordBill> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseAllotRecordBill.class);
        Page<WarehouseAllotRecordBill> 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<WarehouseAllotRecordBill> listPage = warehouseAllotRecordBillService.page(page, queryWrapper);
        List<WarehouseAllotRecordBillDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage<WarehouseAllotRecordBillDto> responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

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

    @ApiOperation(value = "调拨审核记录单详细信息")
    @GetMapping("/{id}")
    public Result<WarehouseAllotRecordBillDto> get(@PathVariable @ApiParam(value = "调拨审核记录单id") Integer id) {
        WarehouseAllotRecordBill warehouseAllotRecordBill = warehouseAllotRecordBillService.getById(id);
        if (null == warehouseAllotRecordBill) {
            return ResultGenerator.fail("该调拨审核记录单不存在");
        }
        return ResultGenerator.success(toEagerDto(warehouseAllotRecordBill));
    }

    @ApiOperation(value = "创建调拨审核记录单")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "调拨审核记录单对象") WarehouseAllotRecordBillDto warehouseAllotRecordBillDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseAllotRecordBill warehouseAllotRecordBill = fromDto(warehouseAllotRecordBillDto);
        warehouseAllotRecordBillService.saveOrUpdate(warehouseAllotRecordBill);
        return ResultGenerator.success();
    }

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

    public WarehouseAllotRecordBillDto toLazyDto(WarehouseAllotRecordBill entity) {
        return modelMapper.map(entity, WarehouseAllotRecordBillDto.class);
    }

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

    public WarehouseAllotRecordBill fromDto(WarehouseAllotRecordBillDto dto) {
        return modelMapper.map(dto, WarehouseAllotRecordBill.class);
    }
}