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.WarehouseAllotBillDetailDto;
import com.sw.mes.store.entity.WarehouseAllotBillDetail;
import com.sw.mes.store.service.WarehouseAllotBillDetailService;
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/allotBillDetail")
@Slf4j
@Api(tags = "调拨单明细接口")
public class WarehouseAllotBillDetailController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseAllotBillDetailService warehouseAllotBillDetailService;

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

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

    @ApiOperation(value = "调拨单明细详细信息")
    @GetMapping("/{id}")
    public Result<WarehouseAllotBillDetailDto> get(@PathVariable @ApiParam(value = "调拨单明细id") Integer id) {
        WarehouseAllotBillDetail warehouseAllotBillDetail = warehouseAllotBillDetailService.getById(id);
        if (null == warehouseAllotBillDetail) {
            return ResultGenerator.fail("该调拨单明细不存在");
        }
        return ResultGenerator.success(toEagerDto(warehouseAllotBillDetail));
    }

    @ApiOperation(value = "创建调拨单明细")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "调拨单明细对象") WarehouseAllotBillDetailDto warehouseAllotBillDetailDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseAllotBillDetail warehouseAllotBillDetail = fromDto(warehouseAllotBillDetailDto);
        warehouseAllotBillDetailService.saveOrUpdate(warehouseAllotBillDetail);
        return ResultGenerator.success();
    }

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

    public WarehouseAllotBillDetailDto toLazyDto(WarehouseAllotBillDetail entity) {
        return modelMapper.map(entity, WarehouseAllotBillDetailDto.class);
    }

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

    public WarehouseAllotBillDetail fromDto(WarehouseAllotBillDetailDto dto) {
        return modelMapper.map(dto, WarehouseAllotBillDetail.class);
    }
}