
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.enums.InputBillTypeEnum;
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.CodeSenderUtils;
import com.sw.mes.core.utils.DynmaicQueryWrapper;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.store.dto.WarehouseInputBillDetailDto;
import com.sw.mes.store.dto.WarehouseInputBillDto;
import com.sw.mes.store.dto.WarehouseInputBillPdaBo;
import com.sw.mes.store.dto.WarehouseMaterialDto;
import com.sw.mes.store.entity.WarehouseInputBill;
import com.sw.mes.store.entity.WarehouseInputBillDetail;
import com.sw.mes.store.entity.WarehouseMaterial;
import com.sw.mes.store.service.WarehouseInputBillDetailService;
import com.sw.mes.store.service.WarehouseInputBillService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
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.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wupeng
 * @Description 线边仓-入库单
 * @Date 20:01 2023/7/26
 * @Param
 * @return
 **/
@RestController
@RequestMapping("/warehouse/inputBill")
@Slf4j
@Api(tags = "线边仓-入库单")
public class WarehouseInputBillController {

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private WarehouseInputBillService inputBillService;

    @Autowired
    private WarehouseInputBillDetailService detailService;

    @ApiOperation(value = "分页查询入库单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_code", value = "入库单编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_status", value = "入库单状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_createTime", value = "创建时间", dataType = "string", paramType = "query")
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<WarehouseInputBillDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        QueryWrapper<WarehouseInputBill> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseInputBill.class);
        Page<WarehouseInputBill> 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<WarehouseInputBill> listPage = inputBillService.page(page, queryWrapper);
        List<WarehouseInputBillDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage<WarehouseInputBillDto> responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "分页查询入库单-PDA")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_serialNo", value = "箱号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_traceid", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_batchNo", value = "批次号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialModelCode", value = "物料料号", dataType = "string", paramType = "query")
    })
    @GetMapping("/listByPagePda")
    public Result<ResponsePage<WarehouseInputBillDto>> listByPagePda(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Page<WarehouseInputBill> page = inputBillService.listByPagePda(request, requestPage);
        List<WarehouseInputBillDto> dtos = page.getRecords().stream()
                .map(entity -> toLazyDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "入库单详细信息")
    @GetMapping("/{id}")
    public Result<WarehouseInputBillDto> get(@PathVariable @ApiParam(value = "入库单id") Long id) {
        //查询入库单明细
        WarehouseInputBill warehouseInputBill = inputBillService.getById(id);
        WarehouseInputBillDto warehouseInputBillDto = modelMapper.map(warehouseInputBill, WarehouseInputBillDto.class);
        if (null == warehouseInputBill) {
            return ResultGenerator.fail("该对象不存在");
        }
        List<WarehouseInputBillDetail> billDetails = detailService.getByBillId(id);
        List<WarehouseInputBillDetailDto> dtos = billDetails.stream()
                .map(entity -> modelMapper.map(entity, WarehouseInputBillDetailDto.class))
                .collect(Collectors.toList());
        warehouseInputBillDto.setInputBillDetails(dtos);
        return ResultGenerator.success(warehouseInputBillDto);
    }
    @ApiOperation(value = "入库单退料详细信息")
    @GetMapping("/returnMaterial/{id}")
    public Result<WarehouseInputBillDto> returnMaterial(@PathVariable @ApiParam(value = "入库单id") Long id) {
        //查询入库单明细
        WarehouseInputBill warehouseInputBill = inputBillService.getById(id);
        WarehouseInputBillDto warehouseInputBillDto = modelMapper.map(warehouseInputBill, WarehouseInputBillDto.class);
        if (null == warehouseInputBill) {
            return ResultGenerator.fail("该对象不存在");
        }
        List<WarehouseInputBillDetail> billDetails = detailService.getByBillId(id);
        List<WarehouseInputBillDetailDto> dtos = billDetails.stream()
                .map(entity -> modelMapper.map(entity, WarehouseInputBillDetailDto.class))
                .collect(Collectors.toList());
        List<WarehouseInputBillDetailDto> result = dtos.stream().filter(e -> e.isReturnMaterial() != true).collect(Collectors.toList());
        warehouseInputBillDto.setInputBillDetails(result);
        return ResultGenerator.success(warehouseInputBillDto);
    }
    /**
     * 人工新建入库单
     **/
    @ApiOperation(value = "创建入库单")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "入库单对象") WarehouseInputBillDto inputBill, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            //保存入库单和入库明细
            inputBillService.saveInputBill(inputBill);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "入库单审核-拒收")
    @PostMapping("/rejection")
    public Result rejection(@RequestBody @Valid @ApiParam(value = "入库单对象") WarehouseInputBill inputBill, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return inputBillService.rejectApply(inputBill);
        } catch (Exception e) {
            return ResultGenerator.fail("拒收失败，失败原因：" + e.getMessage());
        }
    }

    @ApiOperation(value = "入库单审核-取消")
    @PostMapping("/cancel")
    public Result cancel(@RequestBody @Valid @ApiParam(value = "入库单对象") WarehouseInputBill inputBill, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            inputBillService.cancelApply(inputBill.getBillNo());
        } catch (Exception e) {
            return ResultGenerator.fail("拒收失败，失败原因：" + e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "入库单审核-接收")
    @PostMapping("/receive")
    public Result receive(@RequestBody @Valid @ApiParam(value = "入库单对象") WarehouseInputBill inputBill, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        //接收入库单以及明细，则物料明细需要进入库存，更新库存信息
        String billNo = inputBill.getBillNo();
        if (StringUtils.isBlank(billNo)) {
            return ResultGenerator.fail("单据号不能为空！");
        }
        try {
            //物料审核入库
            inputBillService.auditReceiveAtomic(inputBill);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }
    @ApiOperation(value = "入库单WMS退料")
    @PostMapping("/returnMaterialToWMS")
    public Result returnMaterialToWMS(@RequestBody @Valid @ApiParam(value = "入库单对象") WarehouseInputBill inputBill, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        //接收入库单以及明细，则物料明细需要进入库存，更新库存信息
        String billNo = inputBill.getBillNo();
        if (StringUtils.isBlank(billNo)) {
            return ResultGenerator.fail("单据号不能为空！");
        }
        if(StringUtils.isNotBlank(inputBill.getType())&&!inputBill.getType().equals(InputBillTypeEnum.原辅料入库.getValue())){
            return ResultGenerator.fail("退料单据类型不是原辅料入库,请检查数据！");
        }
        try {
            //入库单WMS退料生成对应的出库单
            inputBillService.returnMaterialToWMS(inputBill);
            //退料的明细在退料之后不需要在展示
            inputBill.getInputBillDetails().forEach(details-> details.setReturnMaterial(true));
            detailService.saveOrUpdateBatch(inputBill.getInputBillDetails());
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    /**
     * 第三方系统新建入库单，直接入库，无需审核
     **/
    @ApiOperation(value = "直接入库单")
    @PostMapping("/direct")
    public Result direct(@RequestBody @Valid @ApiParam(value = "入库单对象") WarehouseInputBillDto inputBill, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            //保存入库单和入库明细，设置自动入库
            inputBill.setAutoAudit(true);
            inputBillService.saveInputBill(inputBill);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    /**
     * 导入入库单，并自动审核
     **/
    @ApiOperation(value = "入库单导入")
    @PostMapping("/import")
    public Result orderImport(MultipartFile file) {
        try {
            inputBillService.importInputBill(file);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail("入库单导入失败，失败原因：" + e.getMessage());
        }
    }
    /**
     * 生成唯一码
     **/
    @ApiOperation(value = "生成唯一码")
    @GetMapping("/generateUniqueCode")
    public Result<List<String>> generateUniqueCode(@RequestParam Integer count) {
        List<String> codes = new ArrayList<>();
        try {
            for (int i = 0; i < count; i++) {
                String code = CodeSenderUtils.getNumber("MES",7);
                codes.add(code);
            }
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success(codes);
    }
    @ApiOperation(value = "通过箱号或者托号或者批次号获取入库明细")
    @GetMapping("/findWarehouseInputBillDetailsBySerialNoOrTraceIdOrBatchNo")
    public Result<List<WarehouseInputBillDetail>> findWarehouseInputBillDetailsBySerialNoOrTraceIdOrBatchNo(@RequestParam String code) {
        List<WarehouseInputBillDetail> warehouseInputBillDetailsBySerialNoOrTraceIdOrBatchNo = inputBillService.findWarehouseInputBillDetailsBySerialNoOrTraceIdOrBatchNo(code);
        return ResultGenerator.success(warehouseInputBillDetailsBySerialNoOrTraceIdOrBatchNo);
    }
    public WarehouseInputBillDto toLazyDto(WarehouseInputBill entity) {
        return modelMapper.map(entity, WarehouseInputBillDto.class);
    }

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

    public WarehouseInputBill fromDto(WarehouseInputBillDto dto) {
        return modelMapper.map(dto, WarehouseInputBill.class);
    }

}







