<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="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="type">
                <el-select
                    v-model="queryParams.type"
                    placeholder="类型"
                    style="width: 140px"
                    clearable
                >
                    <el-option label="限价单" value="1" />
                    <el-option label="市价单" value="2" />
                </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="status">
                <el-select
                    v-model="queryParams.status"
                    placeholder="状态"
                    style="width: 140px"
                    clearable
                >
                    <el-option label="新建" value="1" />
                    <el-option label="已成交" value="2" />
                    <el-option label="部分成交" value="3" />
                    <el-option label="已撤单" value="4" />
                    <el-option label="撤单中" value="5" />
                    <el-option label="已过期" value="6" />
                </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" prop="ctime" label="委托时间" min-width="160">
                <template #default="scope">
                    {{ formatTime(scope.row.ctime) }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="userId" label="用户UID" min-width="100" />
            <el-table-column align="center" prop="symbol" label="交易对" min-width="120" />
            <el-table-column align="center" prop="type" label="类型" min-width="80">
                <template #default="scope">
                    {{ scope.row.type == 1 ? '限价单' : scope.row.type == 2 ? '市价单' : scope.row.type }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="side" label="方向" min-width="80">
                <template #default="scope">
                    <span :style="{ color: scope.row.side == 'BUY' ? '#00b96b' : '#ff4d4f' }">
                        {{ scope.row.side == 'BUY' ? '买入' : '卖出' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="价格" min-width="120">
                <template #default="scope">
                    {{ scope.row.type == 2 && scope.row.price == 0 ? '--' : scope.row.price }}
                </template>
            </el-table-column>
            <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) }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="dealVolume" label="已成交数量" min-width="120" />
            <el-table-column align="center" prop="status" label="状态" min-width="100">
                <template #default="scope">
                    {{ statusLabel(scope.row.status) }}
                </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: "orderManage";
</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 { adminOrderPage, 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: "",
    userId: "",
    symbol: "",
    type: "",
    side: "",
    status: "",
});

function statusLabel(status: number) {
    const map: Record<number, string> = { 1: "新建", 2: "已成交", 3: "部分成交", 4: "已撤单", 5: "撤单中", 6: "已过期" };
    return map[status] || status;
}

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(row: any) {
    // 优先使用 dealMoney（市价单 price 为 0，必须用 dealMoney）
    if (row.dealMoney != null) {
        const dm = parseFloat(row.dealMoney);
        if (!isNaN(dm) && dm > 0) return dm.toFixed(8);
    }
    const p = parseFloat(row.price);
    const v = parseFloat(row.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;
    adminOrderPage({
        page: queryParams.page,
        size: queryParams.size,
        id: queryParams.id ? Number(queryParams.id) : undefined,
        userId: queryParams.userId ? Number(queryParams.userId) : undefined,
        symbol: queryParams.symbol || undefined,
        type: queryParams.type ? Number(queryParams.type) : undefined,
        side: queryParams.side || undefined,
        status: queryParams.status ? Number(queryParams.status) : 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>
