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.ExcelUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.store.dto.WarehouseAllotRecordBillDetailDto;
import com.sw.mes.store.entity.WarehouseAllotRecordBillDetail;
import com.sw.mes.store.entity.WarehouseOutputRecordBillDetail;
import com.sw.mes.store.service.WarehouseAllotRecordBillDetailService;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/warehouse/allotRecordBillDetail")
@Slf4j
@Api(tags = "调拨审核记录单明细接口")
public class WarehouseAllotRecordBillDetailController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseAllotRecordBillDetailService warehouseAllotRecordBillDetailService;

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

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

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

    @ApiOperation(value = "创建调拨审核记录单明细")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "调拨审核记录单明细对象") WarehouseAllotRecordBillDetailDto warehouseAllotRecordBillDetailDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseAllotRecordBillDetail warehouseAllotRecordBillDetail = fromDto(warehouseAllotRecordBillDetailDto);
        warehouseAllotRecordBillDetailService.saveOrUpdate(warehouseAllotRecordBillDetail);
        return ResultGenerator.success();
    }

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

    @ApiOperation(value = "导出调拨审核记录接口")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            QueryWrapper<WarehouseAllotRecordBillDetail> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseAllotRecordBillDetail.class);
            List<WarehouseAllotRecordBillDetail> entities = warehouseAllotRecordBillDetailService.list(queryWrapper);
            List<WarehouseAllotRecordBillDetailDto> dtos = entities.stream()
                    .map(storeOutputBill -> toLazyDto(storeOutputBill))
                    .collect(Collectors.toList());
            ExcelUtil.exportExcel(dtos,"调拨审核记录",WarehouseAllotRecordBillDetailDto.class,response);
        } catch (Exception e) {
            throw new RuntimeException("调拨审核记录历导出失败，错误信息：" + e.getMessage());
        }
    }

    public WarehouseAllotRecordBillDetailDto toLazyDto(WarehouseAllotRecordBillDetail entity) {
        return modelMapper.map(entity, WarehouseAllotRecordBillDetailDto.class);
    }

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

    public WarehouseAllotRecordBillDetail fromDto(WarehouseAllotRecordBillDetailDto dto) {
        return modelMapper.map(dto, WarehouseAllotRecordBillDetail.class);
    }
}