<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 />

        <el-card v-if="canSettings" class="period-settings-card" shadow="never">
            <template #header>
                <span>{{ t('game.period.section_auto') }}</span>
            </template>
            <div v-loading="settingsLoading" class="period-settings-body">
                <div class="period-setting-row">
                    <span class="period-setting-label">{{ t('game.period.auto_create_label') }}</span>
                    <el-switch v-model="autoCreate" :disabled="settingsSaving" @change="onSwitchChange" />
                    <span class="period-setting-tip">{{ t('game.period.auto_create_tip') }}</span>
                </div>
                <div class="period-setting-row">
                    <span class="period-setting-label">{{ t('game.period.manual_create_label') }}</span>
                    <el-switch v-model="manualCreate" :disabled="settingsSaving" @change="onSwitchChange" />
                    <span class="period-setting-tip">{{ t('game.period.manual_create_tip') }}</span>
                </div>
                <div v-if="canManual" class="period-setting-actions">
                    <el-button type="primary" :loading="createLoading" @click="onCreateNextManual">
                        {{ t('game.period.btn_create_next') }}
                    </el-button>
                </div>
            </div>
        </el-card>

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

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

        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, provide, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
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 createAxios from '/@/utils/axios'
import baTableClass from '/@/utils/baTable'
import { auth } from '/@/utils/common'

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

const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])

const settingsLoading = ref(false)
const settingsSaving = ref(false)
const createLoading = ref(false)
const autoCreate = ref(false)
const manualCreate = ref(false)
/** 避免初次拉取开关值时触发保存 */
const settingsReady = ref(false)

const canSettings = computed(() => auth('periodSettings'))
const canManual = computed(() => auth('createNextManual'))

const baTable = new baTableClass(
    new baTableApi('/admin/game.Period/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('game.period.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' },
            {
                label: t('game.period.period_no'),
                prop: 'period_no',
                align: 'center',
                minWidth: 180,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
            },
            {
                label: t('game.period.period_start_at'),
                prop: 'period_start_at',
                align: 'center',
                width: 170,
                render: 'datetime',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('game.period.status'),
                prop: 'status',
                align: 'center',
                width: 110,
                operator: 'eq',
                render: 'tag',
                effect: 'dark',
                custom: {
                    '0': 'success',
                    '1': 'warning',
                    '2': 'info',
                    '3': 'primary',
                    '4': 'warning',
                    '5': 'danger',
                },
                replaceValue: {
                    '0': t('game.period.status 0'),
                    '1': t('game.period.status 1'),
                    '2': t('game.period.status 2'),
                    '3': t('game.period.status 3'),
                    '4': t('game.period.status 4'),
                    '5': t('game.period.status 5'),
                },
            },
            {
                label: t('game.period.draw_mode'),
                prop: 'draw_mode',
                align: 'center',
                width: 110,
                operator: 'eq',
                render: 'tag',
                custom: {
                    '0': 'info',
                    '1': 'warning',
                },
                replaceValue: {
                    '0': t('game.period.draw_mode 0'),
                    '1': t('game.period.draw_mode 1'),
                },
            },
            {
                label: t('game.period.preset_number'),
                prop: 'preset_number',
                align: 'center',
                width: 100,
                operator: 'RANGE',
            },
            {
                label: t('game.period.result_number'),
                prop: 'result_number',
                align: 'center',
                width: 100,
                operator: 'RANGE',
            },
            {
                label: t('game.period.void_reason'),
                prop: 'void_reason',
                align: 'center',
                minWidth: 140,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                showOverflowTooltip: true,
            },
            {
                label: t('game.period.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.period.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: 100, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: {
            status: 0,
            draw_mode: 0,
            void_reason: '',
        },
    }
)

provide('baTable', baTable)

async function loadPeriodSettings() {
    if (!canSettings.value) {
        return
    }
    settingsLoading.value = true
    try {
        const res = await createAxios({
            url: '/admin/game.Period/periodSettings',
            method: 'get',
            showCodeMessage: false,
        })
        if (res.code === 1 && res.data) {
            autoCreate.value = res.data.period_auto_create_enabled === 1
            manualCreate.value = res.data.period_manual_create_enabled === 1
            settingsReady.value = true
        }
    } catch {
        // 无权限或接口异常时不打断列表
    } finally {
        settingsLoading.value = false
    }
}

async function onSaveSettings() {
    if (!canSettings.value) {
        return
    }
    settingsSaving.value = true
    try {
        await createAxios({
            url: '/admin/game.Period/periodSettings',
            method: 'post',
            data: {
                period_auto_create_enabled: autoCreate.value ? 1 : 0,
                period_manual_create_enabled: manualCreate.value ? 1 : 0,
            },
            showSuccessMessage: true,
        })
    } finally {
        settingsSaving.value = false
    }
}

function onSwitchChange() {
    if (!settingsReady.value) {
        return
    }
    void onSaveSettings()
}

async function onCreateNextManual() {
    if (!canManual.value) {
        return
    }
    createLoading.value = true
    try {
        await createAxios({
            url: '/admin/game.Period/createNextManual',
            method: 'post',
            showSuccessMessage: true,
        })
        await baTable.getData()
    } finally {
        createLoading.value = false
    }
}

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

<style scoped lang="scss">
.period-settings-card {
    margin-bottom: 12px;
}
.period-settings-body {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.period-setting-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px;
}
.period-setting-label {
    min-width: 160px;
    font-weight: 500;
}
.period-setting-tip {
    color: var(--el-text-color-secondary);
    font-size: 13px;
    flex: 1;
    min-width: 200px;
}
.period-setting-actions {
    margin-top: 4px;
}
</style>
