<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('mall.item.title')"
                        type="string"
                        v-model="baTable.form.items!.title"
                        prop="title"
                        :placeholder="t('Please input field', { field: t('mall.item.title') })"
                    />
                    <FormItem
                        :label="t('mall.item.type')"
                        type="select"
                        v-model="baTable.form.items!.type"
                        prop="type"
                        :input-attr="{ content: { '1': t('mall.item.type 1'), '2': t('mall.item.type 2'), '3': t('mall.item.type 3') } }"
                        :placeholder="t('Please select field', { field: t('mall.item.type') })"
                    />

                    <template v-if="hasItemType">
                        <FormItem
                            :label="t('mall.item.description')"
                            type="textarea"
                            v-model="baTable.form.items!.description"
                            prop="description"
                            :input-attr="{ rows: 3 }"
                            @keyup.enter.stop=""
                            @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                            :placeholder="t('Please input field', { field: t('mall.item.description') })"
                        />
                        <FormItem
                            :label="t('mall.item.title_en')"
                            type="string"
                            v-model="baTable.form.items!.title_en"
                            prop="title_en"
                            :placeholder="t('Please input field', { field: t('mall.item.title_en') })"
                        />
                        <FormItem
                            :label="t('mall.item.description_en')"
                            type="textarea"
                            v-model="baTable.form.items!.description_en"
                            prop="description_en"
                            :input-attr="{ rows: 3 }"
                            @keyup.enter.stop=""
                            @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                            :placeholder="t('Please input field', { field: t('mall.item.description_en') })"
                        />
                        <FormItem
                            :label="t('mall.item.title_ms')"
                            type="string"
                            v-model="baTable.form.items!.title_ms"
                            prop="title_ms"
                            :placeholder="t('Please input field', { field: t('mall.item.title_ms') })"
                        />
                        <FormItem
                            :label="t('mall.item.description_ms')"
                            type="textarea"
                            v-model="baTable.form.items!.description_ms"
                            prop="description_ms"
                            :input-attr="{ rows: 3 }"
                            @keyup.enter.stop=""
                            @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                            :placeholder="t('Please input field', { field: t('mall.item.description_ms') })"
                        />
                        <FormItem
                            :label="t('mall.item.score')"
                            type="number"
                            v-model="baTable.form.items!.score"
                            prop="score"
                            :input-attr="{ step: 1 }"
                            :placeholder="t('Please input field', { field: t('mall.item.score') })"
                        />

                        <!-- BONUS / WITHDRAW：现金面值、流水倍数 -->
                        <FormItem
                            v-if="isBonusOrWithdraw"
                            :label="t('mall.item.amount')"
                            type="number"
                            v-model="baTable.form.items!.amount"
                            prop="amount"
                            :input-attr="{ step: 0.01 }"
                            :placeholder="t('Please input field', { field: t('mall.item.amount') })"
                        />
                        <FormItem
                            v-if="isBonusOrWithdraw"
                            :label="t('mall.item.multiplier')"
                            type="number"
                            v-model="baTable.form.items!.multiplier"
                            prop="multiplier"
                            :input-attr="{ step: 1 }"
                            :placeholder="t('Please input field', { field: t('mall.item.multiplier') })"
                        />
                        <!-- 仅 BONUS：Bonus Grant 需要 -->
                        <FormItem
                            v-if="isBonus"
                            :label="t('mall.item.category')"
                            type="string"
                            v-model="baTable.form.items!.category"
                            prop="category"
                            :placeholder="t('Please input field', { field: t('mall.item.category') })"
                        />
                        <FormItem
                            v-if="isBonus"
                            :label="t('mall.item.category_title')"
                            type="string"
                            v-model="baTable.form.items!.category_title"
                            prop="category_title"
                            :placeholder="t('Please input field', { field: t('mall.item.category_title') })"
                        />
                        <!-- 仅 PHYSICAL：库存 -->
                        <FormItem
                            v-if="isPhysical"
                            :label="t('mall.item.stock')"
                            type="number"
                            v-model="baTable.form.items!.stock"
                            prop="stock"
                            :input-attr="{ step: 1 }"
                            :placeholder="t('Please input field', { field: t('mall.item.stock') })"
                        />

                        <FormItem
                            :label="t('mall.item.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('mall.item.remark') })"
                        />
                        <FormItem :label="t('mall.item.image')" type="image" v-model="baTable.form.items!.image" />
                        <FormItem
                            :label="t('mall.item.sort')"
                            type="number"
                            v-model="baTable.form.items!.sort"
                            prop="sort"
                            :input-attr="{ step: 1 }"
                            :placeholder="t('Please input field', { field: t('mall.item.sort') })"
                        />
                        <FormItem
                            :label="t('mall.item.status')"
                            type="switch"
                            v-model="baTable.form.items!.status"
                            prop="status"
                            :input-attr="{ content: { '0': t('mall.item.status 0'), '1': t('mall.item.status 1') } }"
                        />
                    </template>
                </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, 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 } from '/@/utils/validate'

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

const { t } = useI18n()

const itemType = computed(() => baTable.form.items!.type)
const isBonus = computed(() => itemType.value === 1 || itemType.value === '1')
const isPhysical = computed(() => itemType.value === 2 || itemType.value === '2')
const isWithdraw = computed(() => itemType.value === 3 || itemType.value === '3')
const isBonusOrWithdraw = computed(() => isBonus.value || isWithdraw.value)

/** 已选择商品类型（1/2/3）后，才展示其余表单项 */
const hasItemType = computed(() => isBonus.value || isPhysical.value || isWithdraw.value)

// 切换类型后，清理不适用的字段（严格：WITHDRAW 不保留红利类别字段）
watch(
    itemType,
    (n, o) => {
        if (o === undefined) return
        if (!baTable.form.items) return

        const typeNum = Number(n)
        if (!Number.isFinite(typeNum)) return

        if (typeNum === 1) {
            // BONUS：实物库存不适用
            baTable.form.items.stock = 0
        } else if (typeNum === 2) {
            // PHYSICAL：现金/倍数/类别不适用
            baTable.form.items.amount = 0
            baTable.form.items.multiplier = 0
            baTable.form.items.category = ''
            baTable.form.items.category_title = ''
        } else if (typeNum === 3) {
            // WITHDRAW：提现接口不使用 category，清空避免误存
            baTable.form.items.stock = 0
            baTable.form.items.category = ''
            baTable.form.items.category_title = ''
        }
    },
    { flush: 'post' },
)

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    title: [buildValidatorData({ name: 'required', title: t('mall.item.title') })],
    description: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!hasItemType.value) return callback()
                if (val === '' || val === null || val === undefined) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.description') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    score: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!hasItemType.value) return callback()
                if (val === '' || val === null || val === undefined) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.score') })))
                }
                const num = Number(val)
                if (!Number.isFinite(num)) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.score') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    type: [buildValidatorData({ name: 'required', title: t('mall.item.type') })],
    amount: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!isBonusOrWithdraw.value) return callback()
                if (val === '' || val === null || val === undefined) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.amount') })))
                }
                const num = Number(val)
                if (!Number.isFinite(num)) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.amount') })))
                }
                if (num < 0) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.amount') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    multiplier: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!isBonusOrWithdraw.value) return callback()
                if (val === '' || val === null || val === undefined) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.multiplier') })))
                }
                const num = Number(val)
                if (!Number.isFinite(num) || !Number.isInteger(num)) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.multiplier') })))
                }
                if (num < 0) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.multiplier') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    category: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!isBonus.value) return callback()
                if (!val) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.category') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    category_title: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!isBonus.value) return callback()
                if (!val) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.category_title') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    stock: [
        {
            validator: (rule: any, val: any, callback: Function) => {
                if (!isPhysical.value) return callback()
                if (val === '' || val === null || val === undefined) {
                    return callback(new Error(t('Please input field', { field: t('mall.item.stock') })))
                }
                const num = Number(val)
                if (!Number.isFinite(num) || !Number.isInteger(num)) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.stock') })))
                }
                if (num < 0) {
                    return callback(new Error(t('Please enter the correct field', { field: t('mall.item.stock') })))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
    sort: [buildValidatorData({ name: 'number', title: t('mall.item.sort') })],
    create_time: [buildValidatorData({ name: 'date', title: t('mall.item.create_time') })],
    update_time: [buildValidatorData({ name: 'date', title: t('mall.item.update_time') })],
})
</script>

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