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.WarehouseInputRecordBillDto;
import com.sw.mes.store.entity.WarehouseInputRecordBill;
import com.sw.mes.store.service.WarehouseInputRecordBillService;
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/inputRecordBill")
@Slf4j
@Api(tags = "入库审核记录单接口")
public class WarehouseInputRecordBillController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseInputRecordBillService warehouseInputRecordBillService;

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

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

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

    @ApiOperation(value = "创建入库审核记录单")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "入库审核记录单对象") WarehouseInputRecordBillDto warehouseInputRecordBillDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseInputRecordBill warehouseInputRecordBill = fromDto(warehouseInputRecordBillDto);
        warehouseInputRecordBillService.saveOrUpdate(warehouseInputRecordBill);
        return ResultGenerator.success();
    }

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

    public WarehouseInputRecordBillDto toLazyDto(WarehouseInputRecordBill entity) {
        return modelMapper.map(entity, WarehouseInputRecordBillDto.class);
    }

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

    public WarehouseInputRecordBill fromDto(WarehouseInputRecordBillDto dto) {
        return modelMapper.map(dto, WarehouseInputRecordBill.class);
    }
}