
package com.tmerclub.cloud.product.controller.multishop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.tmerclub.cloud.api.multishop.feign.ShopUserFeignClient;
import com.tmerclub.cloud.api.multishop.vo.ShopUserVO;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.constant.StockBillType;
import com.tmerclub.cloud.common.product.constant.StockType;
import com.tmerclub.cloud.common.product.vo.StockBillLogItemVO;
import com.tmerclub.cloud.common.product.vo.StockBillLogVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.ExcelUtil;
import com.tmerclub.cloud.product.bo.mongo.MongoStockBillLogBO;
import com.tmerclub.cloud.product.dto.StockBillLogDTO;
import com.tmerclub.cloud.product.service.StockBillLogService;
import com.tmerclub.cloud.product.vo.StockBillInLogExcelVO;
import com.tmerclub.cloud.product.vo.StockBillLogExcelVO;
import com.tmerclub.cloud.product.vo.StockBillOutLogExcelVO;
import com.tmerclub.cloud.product.vo.mongo.MongoStockBillLogVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 出入库明细
 *
 * @author lhd
 * @date 2022-06-22 17:14:22
 */
@RestController("multishopStockBillLogController")
@RequestMapping("/m/stock_bill_log")
@Tag(name = "出入库明细")
public class StockBillLogController {

    @Autowired
    private StockBillLogService stockBillLogService;

    @DubboReference
    private ShopUserFeignClient shopUserFeignClient;

    @GetMapping("/page")
    @Operation(summary = "获取出入库明细列表", description = "分页获取出入库明细列表")
    public ServerResponseEntity<PageVO<MongoStockBillLogBO>> page(@Valid PageDTO pageDTO, StockBillLogDTO stockBillLogDTO) {
        stockBillLogDTO.setShopId(AuthUserContext.get().getTenantId());
        PageVO<MongoStockBillLogBO> stockBillLogPage = stockBillLogService.page(pageDTO, stockBillLogDTO);
        return ServerResponseEntity.success(stockBillLogPage);
    }

    @GetMapping("/info/{stockBillLogId}")
    @Operation(summary = "获取出入库明细", description = "根据stockBillLogId获取出入库明细")
    public ServerResponseEntity<MongoStockBillLogVO> getByStockBillLogId(@PathVariable("stockBillLogId") Long stockBillLogId) {
        return ServerResponseEntity.success(stockBillLogService.getByStockBillLogId(stockBillLogId));
    }

    @PostMapping
    @Operation(summary = "保存出入库明细", description = "保存出入库明细")
    public ServerResponseEntity<Void> save(@Valid @RequestBody StockBillLogVO stockBillLogVO) {
        //出库操作下判断出库数是否超出库存数？执行出库 ： 返回错误消息
        if (stockBillLogVO.getType() == 1) {
            List<StockBillLogItemVO> stockBillLogItems = stockBillLogVO.getStockBillLogItems();
            for (StockBillLogItemVO stockBillLogItem : stockBillLogItems) {
                if (stockBillLogItem.getStockCount() > stockBillLogItem.getStock()) {
                    throw new LuckException("出库数超出库存数");
                }
            }
        }
        stockBillLogVO.setShopId(AuthUserContext.get().getTenantId());
        stockBillLogVO.setEmployeeId(AuthUserContext.get().getUserId());
        Long userId = AuthUserContext.get().getUserId();
        ServerResponseEntity<ShopUserVO> userResponse = shopUserFeignClient.getByUserId(userId);
        if (!userResponse.isSuccess() || userResponse.getData() == null) {
            throw new LuckException("无法获取制单人手机号");
        }
        stockBillLogVO.setMakerMobile(userResponse.getData().getPhoneNum());
        if (!Objects.equals(stockBillLogVO.getStockBillType(), StockBillType.PURCHASE_STORAGE.value())) {
            stockBillLogVO.setStockBillType(Objects.equals(stockBillLogVO.getType(), StockType.OUT_OF_STOCK.value()) ? StockBillType.OTHER_OUTBOUND.value() : StockBillType.OTHER_STORAGE.value());
        }
        stockBillLogService.saveInfo(stockBillLogVO);
        return ServerResponseEntity.success();
    }


    @PutMapping
    @Operation(summary = "更新出入库明细", description = "更新出入库明细")
    public ServerResponseEntity<Void> update(@Valid @RequestBody StockBillLogDTO stockBillLogDTO) {
        if (Objects.isNull(stockBillLogDTO.getStockBillLogId())) {
            throw new LuckException("id不能为空");
        }
        stockBillLogService.updateInfo(stockBillLogDTO);
        return ServerResponseEntity.success();
    }

    @GetMapping("/export_stock_bill_log")
    @Operation(summary = "导出出入库明细列表", description = "导出出入库明细列表")
    public void exportStockBillLog(StockBillLogDTO stockBillLogDTO, HttpServletResponse response) {
        stockBillLogDTO.setShopId(AuthUserContext.get().getTenantId());
        List<StockBillLogExcelVO> stockBillLogList = stockBillLogService.exportStockBillLogList(stockBillLogDTO);
        // 出/入库分开导出
        if (stockBillLogDTO.getType() == 1) {
            List<StockBillOutLogExcelVO> excelData = JSON.parseObject(
                    JSON.toJSONString(stockBillLogList),
                    new TypeReference<List<StockBillOutLogExcelVO>>() {}
            );
            ExcelUtil.soleExcel(response, excelData,
                    StockBillOutLogExcelVO.EXCEL_NAME,
                    StockBillOutLogExcelVO.MERGE_ROW_INDEX,
                    StockBillOutLogExcelVO.MERGE_COLUMN_INDEX,
                    StockBillOutLogExcelVO.class
            );
        } else {
            List<StockBillInLogExcelVO> excelData = JSON.parseObject(
                    JSON.toJSONString(stockBillLogList),
                    new TypeReference<List<StockBillInLogExcelVO>>() {
                    }
            );
            ExcelUtil.soleExcel(response, excelData,
                    StockBillInLogExcelVO.EXCEL_NAME,
                    StockBillInLogExcelVO.MERGE_ROW_INDEX,
                    StockBillInLogExcelVO.MERGE_COLUMN_INDEX,
                    StockBillInLogExcelVO.class
            );
        }
    }

    @PutMapping("/voided")
    @Operation(summary = "作废出入库明细单", description = "作废出入库明细单")
    public ServerResponseEntity<Void> voided(@RequestParam("stockBillLogId") Long stockBillLogId) {
        Long shopId = AuthUserContext.get().getTenantId();
        stockBillLogService.voided(shopId, stockBillLogId);
        return ServerResponseEntity.success();
    }
}
