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.*;
import com.sw.mes.store.dto.WarehouseOutputRecordBillDetailDto;
import com.sw.mes.store.entity.WarehouseOutputRecordBillDetail;
import com.sw.mes.store.service.WarehouseOutputRecordBillDetailService;
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.util.ObjectUtils;
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/outputRecordBillDetail")
@Slf4j
@Api(tags = "出库审核记录单明细接口")
public class WarehouseOutputRecordBillDetailController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseOutputRecordBillDetailService warehouseOutputRecordBillDetailService;

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

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

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

    @ApiOperation(value = "创建出库审核记录单明细")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "出库审核记录单明细对象") WarehouseOutputRecordBillDetailDto warehouseOutputRecordBillDetailDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseOutputRecordBillDetail warehouseOutputRecordBillDetail = fromDto(warehouseOutputRecordBillDetailDto);
        warehouseOutputRecordBillDetailService.saveOrUpdate(warehouseOutputRecordBillDetail);
        return ResultGenerator.success();
    }

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

    @ApiOperation(value = "通过物料编码查询出库记录")
    @GetMapping("/getOutputBillByMaterialCode")
    public Result<WarehouseOutputRecordBillDetailDto> getOutputBillByMaterialCode(@RequestParam String materialCode) {
        WarehouseOutputRecordBillDetail warehouseOutputRecordBillDetail =
                warehouseOutputRecordBillDetailService.getOutputBillByMaterialCode(materialCode);
        if (ObjectUtils.isEmpty(warehouseOutputRecordBillDetail)) {
            return ResultGenerator.fail("未查到物料【" + materialCode + "】的出库记录!");
        }
        WarehouseOutputRecordBillDetailDto eagerDto = toEagerDto(warehouseOutputRecordBillDetail);
        return ResultGenerator.success(eagerDto);
    }

    @ApiOperation(value = "通过唯一码查询出库记录")
    @GetMapping("/getOutputBillByUniqueCode")
    public Result<WarehouseOutputRecordBillDetailDto> getOutputBillByUniqueCode(@RequestParam String uniqueCode) {
        WarehouseOutputRecordBillDetail warehouseOutputRecordBillDetail =
                warehouseOutputRecordBillDetailService.getOutputBillByUniqueCode(uniqueCode);
        if (ObjectUtils.isEmpty(warehouseOutputRecordBillDetail)) {
            return ResultGenerator.fail("未查到唯一码【" + uniqueCode + "】的出库记录!");
        }
        WarehouseOutputRecordBillDetailDto eagerDto = toEagerDto(warehouseOutputRecordBillDetail);
        return ResultGenerator.success(eagerDto);
    }

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


    public WarehouseOutputRecordBillDetailDto toLazyDto(WarehouseOutputRecordBillDetail entity) {
        return modelMapper.map(entity, WarehouseOutputRecordBillDetailDto.class);
    }

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

    public WarehouseOutputRecordBillDetail fromDto(WarehouseOutputRecordBillDetailDto dto) {
        return modelMapper.map(dto, WarehouseOutputRecordBillDetail.class);
    }
}