<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <TableHeader
            :buttons="['refresh', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('game.playRecord.quick Search Fields') })"
        ></TableHeader>

        <Table ref="tableRef"></Table>

        <el-dialog class="ba-operate-dialog" :title="t('game.playRecord.review_title')" :model-value="reviewDialog.visible" width="620px" :close-on-click-modal="false" @close="closeReviewDialog">
            <div v-loading="reviewDialog.loading">
                <el-descriptions :column="2" border class="mb-12">
                    <el-descriptions-item :label="t('game.playRecord.id')">{{ reviewDialog.row?.id ?? '-' }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.gameRecord_period_no')">{{ reviewDialog.row?.gameRecord?.period_no ?? '-' }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.user_username')">{{ reviewDialog.row?.user?.username ?? '-' }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.channel_name')">{{ reviewDialog.row?.channel?.name ?? '-' }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.pick_numbers')">{{ formatPickNumbers({}, {}, reviewDialog.row?.pick_numbers) }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.total_amount')">{{ formatAmount({}, {}, reviewDialog.row?.total_amount) }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.win_amount')">{{ formatAmount({}, {}, reviewDialog.row?.win_amount) }}</el-descriptions-item>
                    <el-descriptions-item :label="t('game.playRecord.status')">
                        <el-tag v-if="reviewDialog.row?.status !== null && reviewDialog.row?.status !== undefined && reviewDialog.row?.status !== ''" :type="playRecordStatusTagType(reviewDialog.row.status)" effect="dark" size="small">
                            {{ t(`game.playRecord.status ${reviewDialog.row.status}`) }}
                        </el-tag>
                        <span v-else>-</span>
                    </el-descriptions-item>
                </el-descriptions>
                <el-form label-width="90px">
                    <el-form-item :label="t('game.playRecord.review_remark')">
                        <el-input
                            v-model="reviewDialog.remark"
                            type="textarea"
                            :rows="3"
                            :placeholder="t('game.playRecord.review_remark_placeholder')"
                        />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <el-button @click="closeReviewDialog">{{ t('Cancel') }}</el-button>
                <el-button v-if="canRejectJackpot" type="danger" :loading="reviewDialog.loading" @click="submitReject">{{ t('game.playRecord.review_reject') }}</el-button>
                <el-button v-if="canApproveJackpot" type="primary" :loading="reviewDialog.loading" @click="submitApprove">{{ t('game.playRecord.review_approve') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, reactive, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import createAxios from '/@/utils/axios'
import { auth } from '/@/utils/common'

defineOptions({
    name: 'game/playRecord',
})

const { t } = useI18n()
const canApproveJackpot = auth('approveJackpot')
const canRejectJackpot = auth('rejectJackpot')
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons([])
const reviewDialog = reactive({
    visible: false,
    loading: false,
    id: 0,
    remark: '',
    row: null as any,
})

function formatPickNumbers(_row: anyObj, _column: any, cellValue: unknown) {
    if (cellValue === null || cellValue === undefined) {
        return '-'
    }
    if (typeof cellValue === 'string') {
        return cellValue
    }
    try {
        return JSON.stringify(cellValue)
    } catch {
        return String(cellValue)
    }
}

function playRecordStatusTagType(status: unknown): 'primary' | 'success' | 'info' | 'warning' | 'danger' {
    const key = status === null || status === undefined ? '' : String(status)
    const map: Record<string, 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
        '1': 'info',
        '2': 'success',
        '3': 'danger',
        '4': 'warning',
        '5': 'primary',
    }
    return map[key] ?? 'info'
}

function formatAmount(_row: anyObj, _column: any, cellValue: unknown) {
    if (cellValue === null || cellValue === undefined || cellValue === '') {
        return '-'
    }
    const s = String(cellValue).trim().replace(',', '.')
    const n = parseFloat(s)
    if (!Number.isFinite(n)) {
        return String(cellValue)
    }
    return n.toFixed(2)
}

const baTable = new baTableClass(
    new baTableApi('/admin/game.PlayRecord/'),
    {
        pk: 'id',
        column: [
            { label: t('game.playRecord.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' },
            { label: t('game.playRecord.period_id'), prop: 'period_id', align: 'center', show: false, width: 100, operator: 'RANGE' },
            {
                label: t('game.playRecord.gameRecord_period_no'),
                prop: 'gameRecord.period_no',
                align: 'center',
                minWidth: 200,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                render: 'tag',
            },
            {
                label: t('game.playRecord.gameRecord_status'),
                prop: 'gameRecord.status',
                align: 'center',
                width: 100,
                operator: 'eq',
                render: 'tag',
                effect: 'dark',
                custom: { '0': 'success', '1': 'warning', '2': 'info', '3': 'primary', '4': 'warning', '5': 'danger' },
                replaceValue: {
                    '0': t('game.playRecord.gameRecord_status 0'),
                    '1': t('game.playRecord.gameRecord_status 1'),
                    '2': t('game.playRecord.gameRecord_status 2'),
                    '3': t('game.playRecord.gameRecord_status 3'),
                    '4': t('game.playRecord.gameRecord_status 4'),
                    '5': t('game.playRecord.gameRecord_status 5'),
                },
            },
            { label: t('game.playRecord.user_id'), prop: 'user_id', align: 'center', show: false, width: 90, operator: 'RANGE' },
            {
                label: t('game.playRecord.user_username'),
                prop: 'user.username',
                align: 'center',
                minWidth: 120,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                render: 'tags',
            },
            {
                label: t('game.playRecord.channel_name'),
                prop: 'channel.name',
                align: 'center',
                minWidth: 100,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                render: 'tags',
            },
            { label: t('game.playRecord.pick_numbers'), prop: 'pick_numbers', align: 'center', minWidth: 120, operator: false, formatter: formatPickNumbers },
            { label: t('game.playRecord.total_amount'), prop: 'total_amount', align: 'center', minWidth: 110, operator: 'RANGE', formatter: formatAmount },
            { label: t('game.playRecord.streak_at_bet'), prop: 'streak_at_bet', align: 'center', width: 110, operator: 'RANGE' },
            {
                label: t('game.playRecord.is_auto'),
                prop: 'is_auto',
                align: 'center',
                width: 90,
                operator: 'eq',
                render: 'tag',
                custom: { '0': 'info', '1': 'primary' },
                replaceValue: { '0': t('game.playRecord.is_auto 0'), '1': t('game.playRecord.is_auto 1') },
            },
            { label: t('game.playRecord.win_amount'), prop: 'win_amount', align: 'center', minWidth: 110, operator: 'RANGE', formatter: formatAmount },
            {
                label: t('game.playRecord.status'),
                prop: 'status',
                align: 'center',
                minWidth: 118,
                operator: 'eq',
                render: 'tag',
                effect: 'dark',
                custom: { '1': 'info', '2': 'success', '3': 'danger', '4': 'warning', '5': 'primary' },
                replaceValue: {
                    '1': t('game.playRecord.status 1'),
                    '2': t('game.playRecord.status 2'),
                    '3': t('game.playRecord.status 3'),
                    '4': t('game.playRecord.status 4'),
                    '5': t('game.playRecord.status 5'),
                },
            },
            {
                label: t('game.playRecord.idempotency_key'),
                prop: 'idempotency_key',
                align: 'center',
                minWidth: 140,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                showOverflowTooltip: true,
            },
            {
                label: t('game.playRecord.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                width: 170,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('game.playRecord.update_time'),
                prop: 'update_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                width: 170,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            { label: t('Operate'), align: 'center', width: 90, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {}
)

const openReviewDialog = (row: any) => {
    const idRaw = row?.id
    const id = typeof idRaw === 'number' ? idRaw : Number(idRaw)
    if (!Number.isFinite(id) || id <= 0) {
        ElMessage.error(t('Parameter error'))
        return
    }
    reviewDialog.visible = true
    reviewDialog.id = id
    reviewDialog.remark = ''
    reviewDialog.row = row ?? null
}

const closeReviewDialog = (force = false) => {
    if (reviewDialog.loading && !force) return
    reviewDialog.visible = false
    reviewDialog.id = 0
    reviewDialog.remark = ''
    reviewDialog.row = null
}

const submitApprove = async () => {
    if (!reviewDialog.id) return
    reviewDialog.loading = true
    try {
        await createAxios(
            {
                url: '/admin/game.PlayRecord/approveJackpot',
                method: 'post',
                data: { id: reviewDialog.id, remark: reviewDialog.remark },
            },
            { showSuccessMessage: false }
        )
        ElMessage.success(t('game.playRecord.review_approve_success'))
        if (reviewDialog.row) {
            reviewDialog.row.status = 2
            reviewDialog.row.can_jackpot_approve = 0
        }
        closeReviewDialog(true)
        baTable.onTableHeaderAction('refresh', { event: 'review-approve' })
    } catch (error: any) {
        const message = typeof error?.message === 'string' && error.message !== '' ? error.message : t('Operation failed')
        ElMessage.error(message)
    } finally {
        reviewDialog.loading = false
    }
}

const submitReject = async () => {
    if (!reviewDialog.id) return
    const remark = String(reviewDialog.remark ?? '').trim()
    if (!remark) {
        ElMessage.error(t('game.playRecord.review_remark_required'))
        return
    }
    reviewDialog.loading = true
    try {
        await createAxios(
            {
                url: '/admin/game.PlayRecord/rejectJackpot',
                method: 'post',
                data: { id: reviewDialog.id, remark },
            },
            { showSuccessMessage: false }
        )
        ElMessage.success(t('game.playRecord.review_reject_success'))
        if (reviewDialog.row) {
            reviewDialog.row.status = 4
            reviewDialog.row.can_jackpot_approve = 0
        }
        closeReviewDialog(true)
        baTable.onTableHeaderAction('refresh', { event: 'review-reject' })
    } catch (error: any) {
        const message = typeof error?.message === 'string' && error.message !== '' ? error.message : t('Operation failed')
        ElMessage.error(message)
    } finally {
        reviewDialog.loading = false
    }
}

optButtons.unshift({
    render: 'tipButton',
    name: 'approve-jackpot',
    title: 'game.playRecord.review_open',
    text: '',
    type: 'warning',
    icon: 'fa fa-check',
    disabledTip: true,
    display: (row: any) => {
        if (!canApproveJackpot && !canRejectJackpot) {
            return false
        }
        const v = row?.can_jackpot_approve
        return String(v ?? '') === '1'
    },
    click: (row: any) => {
        openReviewDialog(row)
    },
})

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getData()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

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

