package cn.ysk.cashier.controller.product;

import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.dto.product.StockQueryDto;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.service.product.StockService;
import cn.ysk.cashier.utils.BeanUtil;
import cn.ysk.cashier.vo.StockUpdateValueVO;
import cn.ysk.cashier.vo.StockUpdateWarnLineVO;
import cn.ysk.cashier.vo.StockV2Vo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@Api(tags = "库存管理")
@RequestMapping("/api/stock")
@Slf4j
public class StockController {

    private final StockService stockService;

    @ApiOperation("库存导出")
    @PostMapping(value = "download")
    public void exportTbOrderInfo(HttpServletResponse response, @RequestBody StockQueryDto criteria) throws IOException {
        stockService.download(criteria,response);
    }

    @ApiOperation("库存导出")
    @PostMapping(value = "download/v2")
    public void exportTbOrderInfoV2(HttpServletResponse response, @RequestBody StockQueryDto criteria) throws IOException {
        stockService.downloadV2(criteria,response);
    }

    @Log("库存导入")
    @PostMapping("/doImport")
    @ApiOperation("文件导入库存")
    public ResponseEntity<Object> importExcel(@RequestParam String shopId,@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (file.isEmpty()) {
            throw new BadRequestException("文件不能为空");
        }
        if (!fileName.contains("xls") && !fileName.contains("xlsx")) {
            throw new BadRequestException("文件格式不正确");
        }
        try {
            stockService.importExcel(shopId,file);
        } catch (Exception e) {
            log.error("文件导入库存异常：",e);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("库存导入")
    @PostMapping("/doImport/v2")
    @ApiOperation("文件导入库存")
    public ResponseEntity<Object> importExcelV2(@RequestParam String shopId,@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (file.isEmpty()) {
            throw new BadRequestException("文件不能为空");
        }
        if (!fileName.contains("xls") && !fileName.contains("xlsx")) {
            throw new BadRequestException("文件格式不正确");
        }
        try {
            stockService.importExcelV2(shopId,file);
        } catch (Exception e) {
            log.error("文件导入库存异常：",e);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping
    @ApiOperation("查询库存")
    public ResponseEntity<Object> queryTbProduct(StockQueryDto criteria,
                                                 @RequestParam(required = false, defaultValue = "0") Integer page,
                                                 @RequestParam(required = false, defaultValue = "10") Integer size){
        return new ResponseEntity<>(stockService.queryAll(criteria,page,size), HttpStatus.OK);
    }

    @GetMapping("/v2")
    @ApiOperation("查询库存")
    public ResponseEntity<Object> queryTbProductV2(StockQueryDto criteria,
                                                 @RequestParam(required = false, defaultValue = "0") Integer page,
                                                 @RequestParam(required = false, defaultValue = "10") Integer size){
        Page<StockV2Vo> stockV2Vos = stockService.queryAllV2(criteria, page, size);
        Map<String, Object> dataMap = BeanUtil.transBean2Map(stockV2Vos);
        if (stockV2Vos.getContent().isEmpty()) {
            dataMap.put("warnLine", 0);
        }else {
            StockV2Vo stockV2Vo = stockV2Vos.getContent().stream().filter(item -> item.getWarnLine() != null).findFirst().orElse(null);
            dataMap.put("warnLine", stockV2Vo != null ? stockV2Vo.getWarnLine() : 0);
        }
        return new ResponseEntity<>(dataMap, HttpStatus.OK);
    }


    @Log("商品库存 上下架商品")
    @PutMapping("/grounding")
    @ApiOperation("上下架商品")
    public ResponseEntity<Object> grounding(
            @RequestParam Integer shopId,
            @RequestParam Integer skuId,
            @RequestParam Boolean isGrounding
    ){
        stockService.grounding(shopId,skuId, isGrounding);
        return ResponseEntity.ok("success");
    }

    @GetMapping("/sku")
    @ApiOperation("查询库存")
    public ResponseEntity<Object> queryProductSku(String productId){
        return new ResponseEntity<>(stockService.queryProductSku(productId), HttpStatus.OK);
    }

    @GetMapping("/isStock")
    public ResponseEntity<Object> updateIsHot(
            @RequestParam String shopId,
            @RequestParam Integer proId,
            @RequestParam Integer isStock){
        stockService.updateIsStock(proId,shopId,isStock);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("商品库存 修改商品状态")
    @PutMapping("productStatus")
    public ResponseEntity<Object> updateProductStatus(@RequestBody StockUpdateValueVO updateValueVO) {
        stockService.updateProductStatus(updateValueVO);
        return new ResponseEntity<>("修改成功", HttpStatus.OK);
    }

    @PutMapping("warnLine")
    @ApiOperation("修改商品警告线")
    public ResponseEntity<Object> updateProductWarnLine(@RequestBody StockUpdateWarnLineVO stockUpdateWarnLineVO) {
        if (StrUtil.isBlank(stockUpdateWarnLineVO.getShopId()) || stockUpdateWarnLineVO.getWarnLine() == null || stockUpdateWarnLineVO.getWarnLine() <= 0) {
            throw new BadRequestException("参数有误");
        }
        stockService.updateProductWarnLine(stockUpdateWarnLineVO);
        return new ResponseEntity<>("修改成功", HttpStatus.OK);
    }

}
