package com.rj.controller;

import com.rj.dto.LbGoodsRushBuyRequest;
import com.rj.entity.LbGoods;
import com.rj.service.ILbGoodsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/lbGoods")
@Tag(name = "LB 货品", description = "lb_goods 增删改查与分页")
public class LbGoodsController {

    @Autowired
    private ILbGoodsService lbGoodsService;

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体（id 为外部商品 id，需调用方指定）", required = true)
            @RequestBody LbGoods entity) {
        Map<String, Object> result = lbGoodsService.add(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PutMapping("/update")
    @Operation(summary = "编辑")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "实体", required = true) @RequestBody LbGoods entity) {
        Map<String, Object> result = lbGoodsService.update(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键（商品 id）", required = true) @PathVariable Long id) {
        Map<String, Object> result = lbGoodsService.deleteById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "商品 id", required = true) @PathVariable Long id) {
        LbGoods data = lbGoodsService.getById(id);
        if (data == null) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "记录不存在"));
        }
        return ResponseEntity.ok(Map.of("success", true, "message", "查询成功", "data", data));
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String tenantId,
            @RequestParam(required = false) Long oldId,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Long sellerId,
            @Parameter(description = "是否展示：0否 1是") @RequestParam(required = false) Integer isShow,
            @RequestParam(required = false) Integer status,
            @Parameter(description = "同步来源页码") @RequestParam(required = false) Integer currentPage,
            @Parameter(description = "创建开始时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String createdAtStart,
            @Parameter(description = "创建结束时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String createdAtEnd,
            @Parameter(description = "更新开始时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String updatedAtStart,
            @Parameter(description = "更新结束时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String updatedAtEnd) {
        Map<String, Object> result = lbGoodsService.pageQuery(
                current,
                size,
                tenantId,
                oldId,
                userId,
                title,
                sellerId,
                isShow,
                status,
                currentPage,
                createdAtStart,
                createdAtEnd,
                updatedAtStart,
                updatedAtEnd);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        if (result.get("message") != null && result.get("message").toString().contains("格式错误")) {
            return ResponseEntity.badRequest().body(result);
        }
        return ResponseEntity.internalServerError().body(result);
    }

    @PostMapping("/sync-from-hxr")
    @Operation(
            summary = "从 hxrd 第三方同步货品",
            description =
                    "分页调用 GET /api/order/goods（自动计算 S/T/N 签名），"
                            + "解析 data.list 后 upsert 到 lb_goods；"
                            + "token、URL、appStr 等从 lb_third_integration_config 按 tenantId 读取；"
                            + "token 可选，传入时覆盖库中 goodsApiToken")
    public ResponseEntity<Map<String, Object>> syncFromHxr(
            @Parameter(description = "租户 id", required = true) @RequestParam String tenantId,
            @Parameter(description = "hxrd 接口请求头 token；未传时使用 lb_third_integration_config 中的 goodsApiToken")
            @RequestParam(required = false)
            String token) {
        Map<String, Object> result = lbGoodsService.syncFromHxrGoods(tenantId, token);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PostMapping("/rush-buy")
    @Operation(
            summary = "抢购货品",
            description =
                    "从 lb_goods 按 total_money 从大到小选取金额小于39000的货品，调用 hxrd POST /api/order/buy（body: id、seller_id）；"
                            + "成功笔数达到 maxBuyCount 后停止，且循环抢购总次数不超过 maxBuyCount 的5倍；"
                            + "token 可选，未传时使用 hxr.admin.goods-api-token")
    public ResponseEntity<Map<String, Object>> rushBuy(
            @Parameter(description = "maxBuyCount 必填，token 可选", required = true)
            @RequestBody LbGoodsRushBuyRequest request) {
        Map<String, Object> result =
                lbGoodsService.rushBuy(request.getToken(), request.getMaxBuyCount());
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        if (result.get("message") != null
                && result.get("message").toString().contains("必须大于0")) {
            return ResponseEntity.badRequest().body(result);
        }
        return ResponseEntity.ok(result);
    }
}
