<template>
    <PagingTable url="/balance/records" :where="where" ref="table">
        <template #filter>
            <ElButton :icon="Refresh" @click="table.refresh()"></ElButton>
            <ElSelect v-if="isAdmin" v-model="selectUserId" placeholder="请选择用户" clearable
                      @change="updateWhereAndRefresh">
                <ElOption v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
            </ElSelect>
            <ElSelect v-if="isAdmin" v-model="selectType" placeholder="请选择类型" clearable
                      @change="updateWhereAndRefresh">
                <ElOption v-for="item in typeList" :key="item.status" :label="item.label" :value="item.status" />
            </ElSelect>
        </template>
        <ElTableColumn v-if="isAdmin" prop="userId" label="用户id" width="150" align="center" />
        <ElTableColumn v-if="isAdmin" prop="userName" label="用户名" width="150" align="center" />
        <ElTableColumn prop="amount" label="金额" />
        <ElTableColumn prop="type" label="类型" align="center">
            <template #default="{ row }">
                <ElTag v-if="row.type === 'recharge'" type="success">充值</ElTag>
                <ElTag v-else-if="row.type === 'consumption'" type="warning">消费</ElTag>
                <ElTag v-else-if="row.type === 'refund'" type="warning">退款</ElTag>
                <ElTag v-else-if="row.type === 'other'">其他</ElTag>
                <ElTag v-else>未知</ElTag>
            </template>
        </ElTableColumn>
        <ElTableColumn prop="createdAt" label="交易时间" :formatter="timeFormatter" align="center" />
    </PagingTable>
</template>
<script setup>
import { inject, ref } from 'vue'
import PagingTable from '@/components/PagingTable.vue'
import { useTimeFormatter } from '@/utils/formatter'
import { Plus, Refresh } from '@vicons/tabler'
import { http } from '@/plugins/http'

const isAdmin = inject('isAdmin')
const where = ref({})
const timeFormatter = useTimeFormatter()
const table = ref(null)
const userList = ref({})
const typeList = [
    {
        status: 'recharge',
        label: '充值'
    },
    {
        status: 'consumption',
        label: '消费'
    },
    {
        status: 'refund',
        label: '退款'
    },
    {
        id: 'other',
        label: '其他'
    }
]

async function getUserList() {
    userList.value = (
        await http.post('/admin/users', {
            search: { page: { page: 1, limit: 50 }, order: { createdAt: 'DESC' } }
        })
    ).items
}

getUserList()

const selectUserId = ref('')
const selectType = ref('')

function updateWhereAndRefresh() {
    where.value = {}
    if (selectUserId.value) {
        where.value.userId = selectUserId.value
    }
    if (selectType.value) {
        where.value.type = selectType.value
    }
}

</script>
