<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.config.channel_id')"
                        type="remoteSelect"
                        v-model="baTable.form.items!.channel_id"
                        prop="channel_id"
                        :input-attr="{ ...channelRemoteAttr, disabled: metaFieldsDisabled }"
                        :placeholder="t('Please select field', { field: t('game.config.channel_id') })"
                    />
                    <FormItem
                        :label="t('game.config.group')"
                        type="select"
                        v-model="baTable.form.items!.group"
                        prop="group"
                        :input-attr="{ content: groupSelectContentFiltered, disabled: metaFieldsDisabled }"
                        :placeholder="t('Please select field', { field: t('game.config.group') })"
                    />
                    <FormItem
                        :label="t('game.config.name')"
                        type="string"
                        v-model="baTable.form.items!.name"
                        prop="name"
                        :input-attr="{ disabled: metaFieldsDisabled }"
                        :placeholder="t('Please input field', { field: t('game.config.name') })"
                    />
                    <FormItem
                        :label="t('game.config.title')"
                        type="string"
                        v-model="baTable.form.items!.title"
                        prop="title"
                        :input-attr="{ disabled: metaFieldsDisabled }"
                        :placeholder="t('Please input field', { field: t('game.config.title') })"
                    />
                    <!-- game_weight：数组形式编辑，存库仍为 JSON 字符串 -->
                    <el-form-item v-if="isGameWeight" :label="t('game.config.value')" prop="value">
                        <div class="weight-value-editor">
                            <div v-for="(row, idx) in weightRows" :key="idx" class="weight-value-row">
                                <el-input
                                    v-model="row.key"
                                    class="weight-key"
                                    :readonly="weightKeyReadonly"
                                    :clearable="!weightKeyReadonly"
                                    :placeholder="t('Please input field', { field: t('game.config.weight key') })"
                                    @input="onWeightRowChange"
                                />
                                <span class="weight-sep">:</span>
                                <el-input
                                    v-model="row.val"
                                    class="weight-val"
                                    :placeholder="t('Please input field', { field: t('game.config.weight value') })"
                                    clearable
                                    @input="onWeightRowChange"
                                />
                                <el-button v-if="canEditWeightStructure" type="danger" link @click="removeWeightRow(idx)">
                                    {{ t('Delete') }}
                                </el-button>
                            </div>
                            <el-button v-if="canEditWeightStructure" type="primary" link @click="addWeightRow">{{ t('Add') }}</el-button>
                        </div>
                    </el-form-item>
                    <FormItem
                        v-else
                        :label="t('game.config.value')"
                        type="textarea"
                        v-model="baTable.form.items!.value"
                        prop="value"
                        :input-attr="{ rows: 3 }"
                        @keyup.enter.stop=""
                        @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                        :placeholder="t('Please input field', { field: t('game.config.value') })"
                    />
                    <FormItem
                        :label="t('game.config.sort')"
                        type="number"
                        v-model="baTable.form.items!.sort"
                        prop="sort"
                        :input-attr="{ step: 1 }"
                        :placeholder="t('Please input field', { field: t('game.config.sort') })"
                    />
                    <FormItem
                        :label="t('game.config.instantiation')"
                        type="switch"
                        v-model="baTable.form.items!.instantiation"
                        prop="instantiation"
                        :input-attr="{ content: { '0': t('game.config.instantiation 0'), '1': t('game.config.instantiation 1') } }"
                    />
                </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 { computed, inject, reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import { useAdminInfo } from '/@/stores/adminInfo'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'

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

const { t } = useI18n()

const isSuperAdmin = computed(() => adminInfo.super === true)

/** 编辑且非超级管理员：渠道、分组、配置标识、配置名称不可改 */
const metaFieldsDisabled = computed(() => !isSuperAdmin.value && baTable.form.operate === 'Edit')

const channelRemoteAttr = {
    pk: 'game_channel.id',
    field: 'name',
    remoteUrl: '/admin/game.Channel/index',
}

const groupSelectBase = {
    game_config: 'game_config',
    game_weight: 'game_weight',
}

/** 非超级管理员新增时不可选 game_weight（需先由超级管理员建好键结构） */
const groupSelectContentFiltered = computed(() => {
    if (!isSuperAdmin.value && baTable.form.operate === 'Add') {
        return { game_config: groupSelectBase.game_config }
    }
    return groupSelectBase
})

/** game_weight：编辑或非超管时键只读；仅超管新增时可增删行、改键 */
const weightKeyReadonly = computed(() => {
    if (!isGameWeight.value) return false
    if (baTable.form.operate === 'Edit') return true
    return !isSuperAdmin.value
})

const canEditWeightStructure = computed(() => isGameWeight.value && baTable.form.operate === 'Add' && isSuperAdmin.value)

type WeightRow = { key: string; val: string }

const weightRows = ref<WeightRow[]>([{ key: '', val: '' }])

const WEIGHT_SUM100_NAMES = ['default_tier_weight', 'default_kill_score_weight']

const isGameWeight = computed(() => baTable.form.items?.group === 'game_weight')

function parseValueToWeightRows(raw: unknown): WeightRow[] {
    if (raw === null || raw === undefined || raw === '') {
        return [{ key: '', val: '' }]
    }
    if (typeof raw === 'string') {
        const s = raw.trim()
        if (!s) return [{ key: '', val: '' }]
        try {
            const parsed = JSON.parse(s)
            return arrayToWeightRows(parsed)
        } catch {
            return [{ key: '', val: '' }]
        }
    }
    if (Array.isArray(raw)) {
        return arrayToWeightRows(raw)
    }
    return [{ key: '', val: '' }]
}

function arrayToWeightRows(arr: unknown): WeightRow[] {
    if (!Array.isArray(arr)) {
        return [{ key: '', val: '' }]
    }
    const out: WeightRow[] = []
    for (const item of arr) {
        if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
            for (const [k, v] of Object.entries(item)) {
                out.push({ key: k, val: v === null || v === undefined ? '' : String(v) })
            }
        }
    }
    return out.length ? out : [{ key: '', val: '' }]
}

function weightRowsToJsonString(rows: WeightRow[]): string {
    const pairs: Record<string, string>[] = []
    for (const r of rows) {
        const k = r.key.trim()
        if (k === '') continue
        const one: Record<string, string> = {}
        one[k] = r.val
        pairs.push(one)
    }
    return JSON.stringify(pairs)
}

function syncWeightRowsToFormValue() {
    const items = baTable.form.items
    if (!items) return
    items.value = weightRowsToJsonString(weightRows.value)
}

function onWeightRowChange() {
    if (isGameWeight.value) {
        syncWeightRowsToFormValue()
    }
}

function addWeightRow() {
    if (!canEditWeightStructure.value) return
    weightRows.value.push({ key: '', val: '' })
    syncWeightRowsToFormValue()
}

function removeWeightRow(idx: number) {
    if (!canEditWeightStructure.value) return
    if (weightRows.value.length <= 1) {
        weightRows.value = [{ key: '', val: '' }]
    } else {
        weightRows.value.splice(idx, 1)
    }
    syncWeightRowsToFormValue()
}

function hydrateWeightRowsFromForm() {
    if (!isGameWeight.value) return
    weightRows.value = parseValueToWeightRows(baTable.form.items?.value)
}

watch(isGameWeight, (gw) => {
    if (gw) {
        hydrateWeightRowsFromForm()
    }
})

watch(
    () => baTable.form.loading,
    (loading) => {
        if (loading === false && baTable.form.items?.group === 'game_weight') {
            hydrateWeightRowsFromForm()
        }
    }
)

watch(
    () => baTable.form.items?.group,
    () => {
        if (baTable.form.items?.group === 'game_weight') {
            hydrateWeightRowsFromForm()
        }
    }
)

function validateGameWeightRules(): string | undefined {
    if (baTable.form.items?.group !== 'game_weight') {
        return undefined
    }
    const name = baTable.form.items?.name ?? ''
    const nums: number[] = []
    for (const r of weightRows.value) {
        const k = r.key.trim()
        if (k === '') continue
        const vs = r.val.trim()
        if (vs === '') {
            return t('Please input field', { field: t('game.config.weight value') })
        }
        const n = Number(vs)
        if (!Number.isFinite(n)) {
            return t('game.config.weight value numeric')
        }
        if (n > 100) {
            return t('game.config.weight each max 100')
        }
        nums.push(n)
    }
    if (nums.length === 0) {
        return t('Please input field', { field: t('game.config.value') })
    }
    if (WEIGHT_SUM100_NAMES.includes(name)) {
        let sum = 0
        for (const x of nums) {
            sum += x
        }
        if (Math.abs(sum - 100) > 0.000001) {
            return t('game.config.weight sum must 100')
        }
    }
    return undefined
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    group: [buildValidatorData({ name: 'required', title: t('game.config.group') })],
    name: [buildValidatorData({ name: 'required', title: t('game.config.name') })],
    title: [buildValidatorData({ name: 'required', title: t('game.config.title') })],
    sort: [buildValidatorData({ name: 'number', title: t('game.config.sort') })],
    instantiation: [buildValidatorData({ name: 'number', title: t('game.config.instantiation') })],
    value: [
        {
            validator: (_rule, _val, callback) => {
                const err = validateGameWeightRules()
                if (err) {
                    callback(new Error(err))
                    return
                }
                callback()
            },
            trigger: ['blur', 'change'],
        },
    ],
    create_time: [buildValidatorData({ name: 'date', title: t('game.config.create_time') })],
    update_time: [buildValidatorData({ name: 'date', title: t('game.config.update_time') })],
})
</script>

<style scoped lang="scss">
.weight-value-editor {
    width: 100%;
}
.weight-value-row {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
}
.weight-key {
    max-width: 140px;
}
.weight-val {
    flex: 1;
    min-width: 80px;
}
.weight-sep {
    flex-shrink: 0;
    color: var(--el-text-color-secondary);
}
</style>
