<template>
    <div class="app-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="id">
                <el-input
                    v-model="queryParams.id"
                    placeholder="成交订单ID"
                    style="width: 160px"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="orderId">
                <el-input
                    v-model="queryParams.orderId"
                    placeholder="委托订单ID"
                    style="width: 160px"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="userId">
                <el-input
                    v-model="queryParams.userId"
                    placeholder="用户UID"
                    style="width: 160px"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="symbol">
                <el-select
                    v-model="queryParams.symbol"
                    placeholder="交易对"
                    style="width: 160px"
                    clearable
                    filterable
                >
                    <el-option
                        v-for="s in symbolOptions"
                        :key="s.symbol"
                        :label="s.symbol"
                        :value="s.symbol"
                    />
                </el-select>
            </el-form-item>
            <el-form-item prop="side">
                <el-select
                    v-model="queryParams.side"
                    placeholder="方向"
                    style="width: 140px"
                    clearable
                >
                    <el-option label="买入" value="BUY" />
                    <el-option label="卖出" value="SELL" />
                </el-select>
            </el-form-item>
            <el-form-item prop="role">
                <el-select
                    v-model="queryParams.role"
                    placeholder="角色"
                    style="width: 140px"
                    clearable
                >
                    <el-option label="Taker" value="TAKER" />
                    <el-option label="Maker" value="MAKER" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="timeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="成交开始时间"
                    end-placeholder="成交结束时间"
                    value-format="x"
                    style="width: 360px"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="listdata" v-loading="loading" highlight-current-row border>
            <el-table-column align="center" prop="id" label="成交订单ID" min-width="140" />
            <el-table-column align="center" label="委托订单ID" min-width="140">
                <template #default="scope">
                    {{ getOrderId(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="成交时间" min-width="160">
                <template #default="scope">
                    {{ formatTime(scope.row.ctime) }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="用户UID" min-width="100">
                <template #default="scope">
                    {{ getUserId(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="symbol" label="交易对" min-width="120" />
            <el-table-column align="center" label="方向" min-width="80">
                <template #default="scope">
                    <span :style="{ color: scope.row.trendSide == 'BUY' ? '#00b96b' : '#ff4d4f' }">
                        {{ scope.row.trendSide == 'BUY' ? '买入' : '卖出' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="price" label="成交价格" min-width="120" />
            <el-table-column align="center" prop="volume" label="成交数量" min-width="120" />
            <el-table-column align="center" label="成交金额" min-width="120">
                <template #default="scope">
                    {{ formatAmount(scope.row.price, scope.row.volume) }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="手续费" min-width="120">
                <template #default="scope">
                    {{ getFee(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="角色" min-width="80">
                <template #default="scope">
                    {{ getRoleLabel(scope.row) }}
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.size"
            @pagination="handleQuery"
        />
    </div>
</template>

<script lang="ts">
name: "tradeHistory";
</script>

<script lang="ts" setup>
import { reactive, onMounted, ref } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
import { ElForm } from "element-plus";
import { adminTradePage, adminSymbolAll } from "@/api/coinSpot";

const queryFormRef = ref(ElForm);

const loading = ref(true);
const total = ref(0);
const listdata = ref<any[]>([]);
const timeRange = ref<string[]>([]);
const symbolOptions = ref<{ symbol: string }[]>([]);

const queryParams = reactive({
    page: 1,
    size: 15,
    id: "",
    orderId: "",
    userId: "",
    symbol: "",
    side: "",
    role: "",
});

// Taker = the side that initiated the trade (trendSide)
// If trendSide == BUY, taker is buyer (bidUserId), maker is seller (askUserId)
// If trendSide == SELL, taker is seller (askUserId), maker is buyer (bidUserId)
function getRoleLabel(row: any) {
    if (queryParams.role) return queryParams.role == "TAKER" ? "Taker" : "Maker";
    return row.trendSide == "BUY" ? "Taker" : "Taker";
}

function getOrderId(row: any) {
    if (queryParams.role == "TAKER") {
        return row.trendSide == "BUY" ? row.bidId : row.askId;
    }
    if (queryParams.role == "MAKER") {
        return row.trendSide == "BUY" ? row.askId : row.bidId;
    }
    return row.trendSide == "BUY" ? row.bidId : row.askId;
}

function getUserId(row: any) {
    if (queryParams.role == "TAKER") {
        return row.trendSide == "BUY" ? row.bidUserId : row.askUserId;
    }
    if (queryParams.role == "MAKER") {
        return row.trendSide == "BUY" ? row.askUserId : row.bidUserId;
    }
    return row.trendSide == "BUY" ? row.bidUserId : row.askUserId;
}

function getFee(row: any) {
    let fee;
    if (queryParams.role == "TAKER") {
        fee = row.trendSide == "BUY" ? row.buyFee : row.sellFee;
    }
    else if (queryParams.role == "MAKER") {
        fee = row.trendSide == "BUY" ? row.sellFee : row.buyFee;
    }
    else {
        fee = row.trendSide == "BUY" ? row.buyFee : row.sellFee;
    }
    if (fee == null) return "";
    const num = Number(fee);
    if (isNaN(num)) return String(fee);
    return num.toFixed(8).replace(/\.?0+$/, "");
}

function formatTime(val: any) {
    if (!val) return "";
    if (typeof val === "number") {
        const d = new Date(val);
        if (!isNaN(d.getTime())) return d.toLocaleString("zh-CN", { hour12: false });
    }
    const d = new Date(val);
    if (!isNaN(d.getTime())) return d.toLocaleString("zh-CN", { hour12: false });
    return val;
}

function formatAmount(price: any, volume: any) {
    const p = parseFloat(price);
    const v = parseFloat(volume);
    if (isNaN(p) || isNaN(v)) return "";
    return (p * v).toFixed(8);
}

function extractSymbol(item: any) {
    if (typeof item === "string") return item.trim();
    if (!item || typeof item !== "object") return "";
    if (typeof item.symbol === "string") return item.symbol.trim();
    if (item.symbol && typeof item.symbol === "object" && typeof item.symbol.symbol === "string") {
        return item.symbol.symbol.trim();
    }
    return "";
}

function normalizeSymbolOptions(data: any) {
    const list = Array.isArray(data) ? data : [];
    const seen = new Set<string>();
    const options: { symbol: string }[] = [];
    list.forEach((item) => {
        const symbol = extractSymbol(item);
        if (!symbol || seen.has(symbol)) return;
        seen.add(symbol);
        options.push({ symbol });
    });
    return options;
}

function loadSymbols() {
    adminSymbolAll()
        .then((res: any) => {
            symbolOptions.value = normalizeSymbolOptions(res.data);
        })
        .catch(() => {
            symbolOptions.value = [];
        });
}

function handleQuery() {
    loading.value = true;
    adminTradePage({
        page: queryParams.page,
        size: queryParams.size,
        id: queryParams.id ? Number(queryParams.id) : undefined,
        orderId: queryParams.orderId ? Number(queryParams.orderId) : undefined,
        userId: queryParams.userId ? Number(queryParams.userId) : undefined,
        symbol: queryParams.symbol || undefined,
        side: queryParams.side || undefined,
        role: queryParams.role || undefined,
        ctimeBegin: timeRange.value?.[0] || undefined,
        ctimeEnd: timeRange.value?.[1] || undefined,
    }).then((res: any) => {
        listdata.value = res.data.records;
        total.value = res.data.total;
        loading.value = false;
    });
}

function resetQuery() {
    queryFormRef.value.resetFields();
    timeRange.value = [];
    handleQuery();
}

onMounted(() => {
    loadSymbols();
    handleQuery();
});
</script>

<style lang="less" scoped></style>
