package com.it.rattan.monisuo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.it.rattan.monisuo.common.Result;
import com.it.rattan.monisuo.context.UserContext;
import com.it.rattan.monisuo.entity.OrderTrade;
import com.it.rattan.monisuo.service.TradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 交易接口
 */
@RestController
@RequestMapping("/api/trade")
public class TradeController {

    @Autowired
    private TradeService tradeService;

    /**
     * 买入
     */
    @PostMapping("/buy")
    public Result<Map<String, Object>> buy(@RequestBody Map<String, Object> params) {
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized("请先登录");
        }

        String coinCode = (String) params.get("coinCode");
        BigDecimal price = new BigDecimal(params.get("price").toString());
        BigDecimal quantity = new BigDecimal(params.get("quantity").toString());

        if (coinCode == null || coinCode.isEmpty()) {
            return Result.fail("请选择币种");
        }
        if (price.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.fail("价格必须大于0");
        }
        if (quantity.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.fail("数量必须大于0");
        }

        try {
            Map<String, Object> result = tradeService.buy(userId, coinCode.toUpperCase(), price, quantity);
            return Result.success("买入成功", result);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 卖出
     */
    @PostMapping("/sell")
    public Result<Map<String, Object>> sell(@RequestBody Map<String, Object> params) {
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized("请先登录");
        }

        String coinCode = (String) params.get("coinCode");
        BigDecimal price = new BigDecimal(params.get("price").toString());
        BigDecimal quantity = new BigDecimal(params.get("quantity").toString());

        if (coinCode == null || coinCode.isEmpty()) {
            return Result.fail("请选择币种");
        }
        if (price.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.fail("价格必须大于0");
        }
        if (quantity.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.fail("数量必须大于0");
        }

        try {
            Map<String, Object> result = tradeService.sell(userId, coinCode.toUpperCase(), price, quantity);
            return Result.success("卖出成功", result);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 交易记录
     */
    @GetMapping("/orders")
    public Result<Map<String, Object>> getOrders(
            @RequestParam(required = false) String coinCode,
            @RequestParam(required = false) Integer direction,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized("请先登录");
        }

        try {
            IPage<OrderTrade> page = tradeService.getOrders(userId, coinCode, direction, pageNum, pageSize);
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("list", page.getRecords());
            result.put("total", page.getTotal());
            result.put("pageNum", page.getCurrent());
            result.put("pageSize", page.getSize());
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 订单详情
     */
    @GetMapping("/order/detail")
    public Result<OrderTrade> getOrderDetail(@RequestParam String orderNo) {
        Long userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized("请先登录");
        }

        try {
            OrderTrade order = tradeService.getOrderDetail(userId, orderNo);
            if (order == null) {
                return Result.fail("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}
