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.excel.ExcelResult;
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.WarehouseInputRecordBillDetailDto;
import com.sw.mes.store.entity.WarehouseInputRecordBillDetail;
import com.sw.mes.store.listener.OutPutImportListener;
import com.sw.mes.store.service.WarehouseInputRecordBillDetailService;
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.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/warehouse/inputRecordBillDetail")
@Slf4j
@Api(tags = "入库审核记录单明细接口")
public class WarehouseInputRecordBillDetailController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseInputRecordBillDetailService warehouseInputRecordBillDetailService;

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

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

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

    @ApiOperation(value = "创建入库审核记录单明细")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "入库审核记录单明细对象") WarehouseInputRecordBillDetailDto warehouseInputRecordBillDetailDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        WarehouseInputRecordBillDetail warehouseInputRecordBillDetail = fromDto(warehouseInputRecordBillDetailDto);
        warehouseInputRecordBillDetailService.saveOrUpdate(warehouseInputRecordBillDetail);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新入库审核记录单明细")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "入库审核记录单明细") WarehouseInputRecordBillDetailDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        WarehouseInputRecordBillDetail entity = warehouseInputRecordBillDetailService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            WarehouseInputRecordBillDetail entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            warehouseInputRecordBillDetailService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }
    @ApiOperation(value = "根据物料号和批次号获取入库记录")
    @GetMapping("/getByMaterialCodeAndBatchNo")
    public Result<WarehouseInputRecordBillDetailDto> getByMaterialCodeAndBatchNo(@RequestParam String materialCode,
                                                                                 @RequestParam String batchNo ) {
        WarehouseInputRecordBillDetail warehouseInputRecordBillDetail =
                warehouseInputRecordBillDetailService.getByMaterialCodeAndBatchNo(materialCode,batchNo);
        if (null == warehouseInputRecordBillDetail) {
            return ResultGenerator.fail("该入库审核记录单明细不存在");
        }
        return ResultGenerator.success(toEagerDto(warehouseInputRecordBillDetail));
    }

    @ApiOperation(value = "删除入库审核记录单明细")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        warehouseInputRecordBillDetailService.removeByIds(Arrays.asList(ids));
        return ResultGenerator.success();
    }

    @ApiOperation(value = "导出入库审核记录接口")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response){
        try {
            QueryWrapper<WarehouseInputRecordBillDetail> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseInputRecordBillDetail.class);
            List<WarehouseInputRecordBillDetail> entities = warehouseInputRecordBillDetailService.list(queryWrapper);
            List<WarehouseInputRecordBillDetailDto> dtos = entities.stream()
                    .map(storeOutputBill -> toLazyDto(storeOutputBill))
                    .collect(Collectors.toList());
            ExcelUtil.exportExcel(dtos,"入库审核记录",WarehouseInputRecordBillDetailDto.class,response);

        } catch (Exception e) {
            log.error("导出入库审核记录接口:" + e);
            e.printStackTrace();
            throw new RuntimeException("入库审核记录历导出失败，错误信息：" + e.getMessage());
        }

    }
    @ApiOperation(value = "获取导入入库审核记录模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "入库审核记录", WarehouseInputRecordBillDetailDto.class, response);
    }

    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ExcelResult importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<WarehouseInputRecordBillDetailDto> warehouseInputRecordBillDetailDtoExcelResult =
                ExcelUtil.importExcel(file.getInputStream(), WarehouseInputRecordBillDetailDto.class, new OutPutImportListener(updateSupport));
        return warehouseInputRecordBillDetailDtoExcelResult;
    }
    public WarehouseInputRecordBillDetailDto toLazyDto(WarehouseInputRecordBillDetail entity) {
        return modelMapper.map(entity, WarehouseInputRecordBillDetailDto.class);
    }

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

    public WarehouseInputRecordBillDetail fromDto(WarehouseInputRecordBillDetailDto dto) {
        return modelMapper.map(dto, WarehouseInputRecordBillDetail.class);
    }
}