<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem
                        :label="t('game.user.username')"
                        type="string"
                        v-model="baTable.form.items!.username"
                        prop="username"
                        :placeholder="t('Please input field', { field: t('game.user.username') })"
                    />
                    <FormItem
                        :label="t('game.user.password')"
                        type="password"
                        v-model="baTable.form.items!.password"
                        prop="password"
                        :placeholder="t('Please input field', { field: t('game.user.password') })"
                    />
                    <FormItem
                        :label="t('game.user.phone')"
                        type="string"
                        v-model="baTable.form.items!.phone"
                        prop="phone"
                        :placeholder="t('Please input field', { field: t('game.user.phone') })"
                    />
                    <FormItem
                        :label="t('game.user.remark')"
                        type="textarea"
                        v-model="baTable.form.items!.remark"
                        prop="remark"
                        :input-attr="{ rows: 3 }"
                        @keyup.enter.stop=""
                        @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                        :placeholder="t('Please input field', { field: t('game.user.remark') })"
                    />
                    <FormItem
                        :label="t('game.user.coin')"
                        type="number"
                        v-model="baTable.form.items!.coin"
                        prop="coin"
                        :input-attr="{ step: 1 }"
                        :placeholder="t('Please input field', { field: t('game.user.coin') })"
                    />
                    <FormItem
                        :label="t('game.user.status')"
                        type="switch"
                        v-model="baTable.form.items!.status"
                        prop="status"
                        :input-attr="{ content: { '0': t('game.user.status 0'), '1': t('game.user.status 1') } }"
                    />
                    <el-form-item :label="t('game.user.channel_id')" prop="admin_id">
                        <el-tree-select
                            v-model="baTable.form.items!.admin_id"
                            class="w100"
                            clearable
                            filterable
                            :data="channelAdminTree"
                            :props="treeProps"
                            :render-after-expand="false"
                            :placeholder="t('Please select field', { field: t('game.user.admin_id') })"
                            @change="onAdminTreeChange"
                        />
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormItemRule } from 'element-plus'
import { inject, onMounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData, regularPassword } from '/@/utils/validate'
import createAxios from '/@/utils/axios'

const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

type TreeNode = {
    value: string
    label: string
    disabled?: boolean
    children?: TreeNode[]
    channel_id?: number
    is_leaf?: boolean
}

const channelAdminTree = ref<TreeNode[]>([])
const adminIdToChannelId = ref<Record<string, number>>({})

const treeProps = {
    value: 'value',
    label: 'label',
    children: 'children',
    disabled: 'disabled',
}

const loadChannelAdminTree = async () => {
    const res = await createAxios({
        url: '/admin/channel/adminTree',
        method: 'get',
    })
    const list = (res.data?.list ?? []) as TreeNode[]
    channelAdminTree.value = list

    const map: Record<string, number> = {}
    const walk = (nodes: TreeNode[]) => {
        for (const n of nodes) {
            if (n.children && n.children.length) {
                walk(n.children)
            } else if (n.is_leaf && n.channel_id !== undefined) {
                map[n.value] = n.channel_id
            }
        }
    }
    walk(list)
    adminIdToChannelId.value = map
}

const onAdminTreeChange = (val: string | number | null) => {
    if (val === null || val === undefined || val === '') {
        return
    }
    const key = typeof val === 'number' ? String(val) : val
    const channelId = adminIdToChannelId.value[key]
    if (channelId !== undefined) {
        baTable.form.items!.channel_id = channelId
    }
}

onMounted(() => {
    loadChannelAdminTree()
})

watch(
    () => baTable.form.items?.admin_id,
    (val) => {
        if (val === undefined || val === null || val === '') return
        onAdminTreeChange(val as any)
    }
)

const validatorGameUserPassword = (rule: any, val: string, callback: (error?: Error) => void) => {
    const operate = baTable.form.operate
    const v = typeof val === 'string' ? val.trim() : ''

    // 新增：必填
    if (operate === 'Add') {
        if (!v) return callback(new Error(t('Please input field', { field: t('game.user.password') })))
        if (!regularPassword(v)) return callback(new Error(t('validate.Please enter the correct password')))
        return callback()
    }

    // 编辑：可空；非空则校验格式
    if (!v) return callback()
    if (!regularPassword(v)) return callback(new Error(t('validate.Please enter the correct password')))
    return callback()
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    username: [buildValidatorData({ name: 'required', title: t('game.user.username') })],
    password: [{ validator: validatorGameUserPassword, trigger: 'blur' }],
    phone: [buildValidatorData({ name: 'required', title: t('game.user.phone') })],
    coin: [buildValidatorData({ name: 'number', title: t('game.user.coin') })],
    admin_id: [buildValidatorData({ name: 'required', title: t('game.user.admin_id') })],
    create_time: [buildValidatorData({ name: 'date', title: t('game.user.create_time') })],
    update_time: [buildValidatorData({ name: 'date', title: t('game.user.update_time') })],
})
</script>

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