<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', 'add', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="
                t('Quick search placeholder', { fields: t('user.moneyLog.User name') + '/' + t('user.moneyLog.User nickname') })
            "
        >
            <el-button v-if="!isEmpty(state.userInfo)" v-blur class="table-header-operate">
                <span class="table-header-operate-text">
                    {{ state.userInfo.username + '(ID:' + state.userInfo.id + ') ' + t('user.moneyLog.balance') + ':' + state.userInfo.money }}
                </span>
            </el-button>
        </TableHeader>

        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table />

        <!-- 表单 -->
        <PopupForm />

        <el-dialog v-model="historyDialog.visible" title="Transaction Edit History" width="720px">
            <p class="dialog-note">Transaction edit history is only kept for the most recent 12 months.</p>
            <p class="dialog-note">Transaction 的编辑历史记录仅保存最近 12 个月。</p>
            <el-table v-loading="historyDialog.loading" :data="historyDialog.rows" border size="small" empty-text="No Record">
                <el-table-column prop="id" label="Tx ID" width="100" />
                <el-table-column prop="editedBy" label="Edit By" width="120" />
                <el-table-column prop="editedTime" label="Edit Time" width="170" />
                <el-table-column prop="changes" label="Changes (Old → New)" />
            </el-table>
            <template #footer>
                <el-button @click="historyDialog.visible = false">CANCEL</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { debounce, isEmpty, parseInt } from 'lodash-es'
import { provide, reactive, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import PopupForm from './popupForm.vue'
import { add, logHistory, url } from '/@/api/backend/user/moneyLog'
import { baTableApi } from '/@/api/common'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import scoreLog from '/@/lang/backend/zh-cn/user/scoreLog'
import { defaultOptButtons } from '/@/components/table'
defineOptions({
    name: 'user/moneyLog',
})

const { t, tm } = useI18n()
const route = useRoute()
const defalutUser = (route.query.user_id ?? '') as string
const state = reactive({
    userInfo: {} as anyObj,
})
interface HistoryRow {
    id: number | string
    editedBy: string
    editedTime: string
    changes: string
}

const historyDialog = reactive({
    visible: false,
    loading: false,
    rows: [] as HistoryRow[],
})
const gameTypeMap = scoreLog.game_type as Record<string, string>
const optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: 'history',
        title: 'History',
        text: '',
        type: 'primary',
        icon: 'fa fa-history',
        class: 'table-row-history',
        disabledTip: false,
        click: (row: TableRow) => {
            openHistory(row)
        },
    },
    ...defaultOptButtons(['edit']),
    ...defaultOptButtons(['delete']),
]

const toNumber = (value: unknown) => {
    const number = Number(value)
    return Number.isFinite(number) ? number : 0
}

const formatDateTime = (value: unknown) => {
    if (typeof value === 'string' && value.trim() && !Number.isFinite(Number(value))) {
        return value
    }

    const timestamp = toNumber(value)
    if (!timestamp) return ''

    const date = new Date(timestamp * 1000)
    const pad = (number: number) => number.toString().padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

const stringifyChange = (history: Record<string, unknown>) => {
    if (history.bank_befter !== undefined || history.bank_after !== undefined) {
        return `Bank:${history.bank_befter ?? ''}→${history.bank_after ?? ''}`
    }

    return JSON.stringify(history)
}

const mapHistory = (history: Record<string, unknown>): HistoryRow => ({
    id: (history.id || history.money_log_id || '') as number | string,
    editedBy: String(history.admin_name || ''),
    editedTime: formatDateTime(history.create_time),
    changes: stringifyChange(history),
})

const openHistory = (row: TableRow) => {
    historyDialog.visible = true
    historyDialog.loading = true
    historyDialog.rows = []

    logHistory({ id: row.id })
        .then((res) => {
            const data = Array.isArray(res.data) ? res.data : res.data?.list
            historyDialog.rows = Array.isArray(data) ? data.map((item) => mapHistory(item as Record<string, unknown>)) : []
        })
        .finally(() => {
            historyDialog.loading = false
        })
}

const baTable = new baTableClass(
    new baTableApi(url),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            {
                label: t('user.moneyLog.Created by'),
                prop: 'admin.username',
                align: 'center',
                width: 70,
                formatter: (row: TableRow) => {
                    return row.admin?.username || 'web'
                },
            },
            { label: t('user.moneyLog.User name'), prop: 'user.jk_username', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: t('user.moneyLog.Change balance'), prop: 'money', align: 'center', operator: 'RANGE', sortable: 'custom' },
            { label: t('user.moneyLog.bank_id'), prop: 'bank.bank_name', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { label: t('user.moneyLog.Transaction id'), prop: 'transaction_id', align: 'center', operator: 'RANGE' },
            {
                label: t('user.moneyLog.Game Ticket'),
                prop: 'scoreLog',
                align: 'center',
                // 使用渲染函数手动构建显示内容
                formatter: (row: TableRow) => {
                    if (!row.scoreLog || row.scoreLog.length === 0) return '-'
                    return row.scoreLog
                        .map((item: any) => {
                            const gameName = gameTypeMap[String(item.game_type)] || item.game_type
                            return `${gameName}: ${item.score}`
                        })
                        .join(' | ')
                },
            },
            {
                label: t('user.moneyLog.type'),
                prop: 'type',
                align: 'center',
                operator: 'eq',
                sortable: false,
                render: 'tag',
                custom: {
                    '1': 'success',
                    '2': 'danger',
                    '3': 'success',
                    '4': 'danger',
                },
                replaceValue: { ...tm('user.moneyLog.type_list') },
            },
            {
                label: t('user.moneyLog.remarks'),
                prop: 'memo',
                align: 'center',
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
                showOverflowTooltip: true,
            },
            { label: t('Create time'), prop: 'create_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: t('Operate'), align: 'center', width: '130', render: 'buttons', buttons: optButtons },
        ],
        dblClickNotEditColumn: ['all'],
    },
    {
        defaultItems: {
            user_id: defalutUser,
            memo: '',
        },
    }
)

// 表单提交后
baTable.after.onSubmit = () => {
    getUserInfo(baTable.comSearch.form.user_id)
}
baTable.after.onTableHeaderAction = ({ event }) => {
    // 刷新后
    if (event == 'refresh') {
        getUserInfo(baTable.comSearch.form.user_id)
    }
}

baTable.before.onTableAction = ({ event }) => {
    // 公共搜索
    if (event === 'com-search') {
        baTable.table.filter!.search = baTable.getComSearchData()

        for (const key in baTable.table.filter!.search) {
            if (['money', 'before', 'after'].includes(baTable.table.filter!.search[key].field)) {
                const val = (baTable.table.filter!.search[key].val as string).split(',')
                const newVal: (string | number)[] = []
                for (const k in val) {
                    newVal.push(isNaN(parseFloat(val[k])) ? '' : parseFloat(val[k]) * 100)
                }
                baTable.table.filter!.search[key].val = newVal.join(',')
            }
        }

        baTable.onTableHeaderAction('refresh', { event: 'com-search', data: baTable.table.filter!.search })
        return false
    }
}

baTable.mount()
baTable.getData()

provide('baTable', baTable)

const getUserInfo = debounce((userId: string) => {
    if (userId && parseInt(userId) > 0) {
        add(userId).then((res) => {
            state.userInfo = res.data.user
        })
    } else {
        state.userInfo = {}
    }
}, 300)

getUserInfo(baTable.comSearch.form.user_id)

watch(
    () => baTable.comSearch.form.user_id,
    (newVal) => {
        baTable.form.defaultItems!.user_id = newVal
        getUserInfo(newVal)
    }
)
</script>

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