<template>
    <div class="market-page">
        <h1>🛒 京海鱼市交易中心</h1>

        <el-tabs v-model="activeTab" @tab-click="handleTabChange" type="border-card">
            <el-tab-pane label="鱼市" name="all" />
            <el-tab-pane label="我的市场" name="mine" />
            <el-tab-pane label="交易记录" name="history" />
        </el-tabs>

        <!-- 鱼市表格 -->
        <el-table v-if="activeTab === 'all'" :data="marketList" style="width: 100%" height="calc(100vh - 110px)" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="fishName" label="鱼名" />
            <el-table-column prop="sellerName" label="卖家" />
            <el-table-column prop="points" label="价格（点数）" width="150" />
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button type="success" @click="buyFish(row)">购买</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 我的市场表格 -->
        <el-table v-if="activeTab === 'mine'" :data="myMarketList" style="width: 100%" height="calc(100vh - 110px)" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="fishName" label="鱼名" />
            <el-table-column prop="points" label="挂售价格" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="danger" @click="removeMyListing(row)">下架</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 历史记录 -->
        <el-card v-if="activeTab === 'history'" class="history-box">
            <div v-if="historyList.length">
                <p v-for="(item, index) in historyList" :key="index">{{ item }}</p>
            </div>
            <div v-else>
                <el-empty description="暂无交易记录" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllMarketplace, getMyMarketplace, getMarketplaceHistory, buyFromMarketplace, downMyFish } from '@/api/market/market'

const activeTab = ref('all')

const marketList = ref([])
const myMarketList = ref([])
const historyList = ref([])

// 切换标签
const handleTabChange = () => {
    if (activeTab.value === 'all') {
        fetchAllMarketplace()
    } else if (activeTab.value === 'mine') {
        fetchMyMarketplace()
    } else if (activeTab.value === 'history') {
        fetchHistory()
    }
}

// 获取鱼市数据
const fetchAllMarketplace = async () => {
    try {
        const res = await getAllMarketplace()
        marketList.value = res
    } catch {
        ElMessage.error('获取鱼市数据失败')
    }
}

// 获取我的市场数据
const fetchMyMarketplace = async () => {
    try {
        const res = await getMyMarketplace()
        myMarketList.value = res
    } catch {
        ElMessage.error('获取我的市场数据失败')
    }
}

// 获取交易记录
const fetchHistory = async () => {
    try {
        const res = await getMarketplaceHistory()
        historyList.value = res
    } catch {
        ElMessage.error('获取历史记录失败')
    }
}

// 购买鱼
const buyFish = async (item) => {
    try {
        await ElMessageBox.confirm(
            `是否确认花费 ${item.points} 点数购买 ${item.fishName}？`,
            '确认购买',
            {
                confirmButtonText: '购买',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        const res = await buyFromMarketplace(item.id)
        if (res.success) {
            ElMessage.success('购买成功')
            fetchAllMarketplace()
        } else {
            ElMessage.error(res.message || '购买失败')
        }
    } catch (err) {
        if (err !== 'cancel') {
            ElMessage.error('购买过程中出错')
        }
    }
}

// 下架自己挂售的鱼
const removeMyListing = async (item) => {
    try {
        await ElMessageBox.confirm(`确定下架 ${item.fishName} 吗？`, '确认操作', {
            confirmButtonText: '下架',
            cancelButtonText: '取消',
            type: 'warning',
        })
        const res = await downMyFish(item.id)
        if (res.success) {
            ElMessage.success('下架成功')
            fetchMyMarketplace()
        } else {
            ElMessage.error(res.message || '操作失败')
        }
    } catch (err) {
        if (err !== 'cancel') {
            ElMessage.error('操作失败')
        }
    }
}

onMounted(() => {
    fetchAllMarketplace()
})
</script>

<style scoped>
.market-page {
    padding: 20px;
}

.history-box {
    margin-top: 20px;
    line-height: 1.8;
}
</style>
