<template>
    <!-- 对话框表单 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        :destroy-on-close="true"
    >
        <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
                    ref="formRef"
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                    v-if="!baTable.form.loading"
                >
                    <FormItem
                        :label="t('auth.group.Parent group')"
                        v-model="baTable.form.items!.pid"
                        type="remoteSelect"
                        prop="pid"
                        :input-attr="{
                            params: { isTree: true },
                            field: 'name',
                            remoteUrl: baTable.api.actionUrl.get('index'),
                            placeholder: t('Click select'),
                            emptyValues: ['', null, undefined, 0],
                            valueOnClear: 0,
                        }"
                    />
                    <p
                        v-if="!isRootGroup"
                        class="group-channel-inherit-hint"
                        :style="{ paddingLeft: (baTable.form.labelWidth ?? 120) + 'px' }"
                    >
                        {{ t('auth.group.channel_inherit_hint') }}
                    </p>

                    <!-- 顶级+超管：可选渠道；展示只读渠道名称（channel_id 仅由表单传给后端） -->
                    <FormItem
                        v-if="isRootGroup && adminInfo.super"
                        :label="t('auth.group.channel_id')"
                        v-model="baTable.form.items!.channel_id"
                        type="remoteSelect"
                        prop="channel_id"
                        :input-attr="{
                            pk: 'id',
                            field: 'name',
                            remoteUrl: '/admin/channel/index',
                            placeholder: t('Click select'),
                            emptyValues: ['', null, undefined, 0],
                            valueOnClear: null,
                        }"
                    />
                    <template v-if="isRootGroup && adminInfo.super && channelPreviewName">
                        <el-form-item :label="t('auth.group.channel_name')">
                            <el-input :model-value="channelPreviewName" readonly />
                        </el-form-item>
                    </template>

                    <!-- 子级：只读展示上级对应渠道名称，不提交 channel_id（由后端按父级写入） -->
                    <template v-if="!isRootGroup && channelPreviewName">
                        <el-form-item :label="t('auth.group.channel_name')">
                            <el-input :model-value="channelPreviewName" readonly />
                        </el-form-item>
                    </template>

                    <el-form-item prop="name" :label="t('auth.group.Group name')">
                        <el-input
                            v-model="baTable.form.items!.name"
                            type="string"
                            :placeholder="t('Please input field', { field: t('auth.group.Group name') })"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="auth" :label="t('auth.group.jurisdiction')">
                        <el-tree
                            ref="treeRef"
                            :key="baTable.form.extend!.treeKey"
                            :default-checked-keys="baTable.form.extend!.defaultCheckedKeys"
                            :default-expand-all="true"
                            show-checkbox
                            node-key="id"
                            :props="{ children: 'children', label: 'title', class: treeNodeClass }"
                            :data="baTable.form.extend!.menuRules"
                            class="w100"
                        />
                    </el-form-item>
                    <FormItem
                        :label="t('State')"
                        v-model="baTable.form.items!.status"
                        type="radio"
                        :input-attr="{
                            border: true,
                            content: { 0: t('Disable'), 1: t('Enable') },
                        }"
                    />
                </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 { reactive, inject, useTemplateRef, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import FormItem from '/@/components/formItem/index.vue'
import type { ElTree, FormItemRule } from 'element-plus'
import { buildValidatorData } from '/@/utils/validate'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useConfig } from '/@/stores/config'
import { useAdminInfo } from '/@/stores/adminInfo'
import createAxios from '/@/utils/axios'

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

const { t } = useI18n()
const isRootGroup = computed(() => {
    const p = baTable.form.items?.pid
    if (p === undefined || p === null || p === '') {
        return true
    }
    return Number(p) === 0
})

const strFromRow = (key: string): string => {
    const row = baTable.form.items
    if (!row) return ''
    const v = row[key]
    return typeof v === 'string' ? v : ''
}

const channelPreviewName = computed(() => strFromRow('channel_name'))

/**
 * 子角色组：选择上级分组后，只拉取展示用渠道名；channel_id 由后端按父级保存，不在此写入提交字段。
 */
watch(
    () => baTable.form.items?.pid,
    async (pid, oldPid) => {
        const items = baTable.form.items
        if (!items || !baTable.form.operate || !['Add', 'Edit'].includes(baTable.form.operate)) {
            return
        }
        const pidNum = Number(pid ?? 0)
        const oldNum = oldPid === undefined || oldPid === null || oldPid === '' ? null : Number(oldPid)

        if (pidNum === 0) {
            if (adminInfo.super && oldNum !== null && oldNum !== 0) {
                items.channel_id = null
                items['channel_name'] = ''
            }
            return
        }

        delete items.channel_id

        try {
            const res = await createAxios(
                {
                    url: '/admin/auth.Group/edit',
                    method: 'get',
                    params: { id: pidNum },
                },
                { showErrorMessage: false, showCodeMessage: false }
            )
            const row = res.data.row
            if (row) {
                items['channel_name'] = typeof row.channel_name === 'string' ? row.channel_name : ''
            }
        } catch {
            items['channel_name'] = ''
        }
    }
)

/** 顶级+超管：所选渠道变更时刷新只读渠道名 */
watch(
    () => baTable.form.items?.channel_id,
    async (cid) => {
        const items = baTable.form.items
        if (!items || !baTable.form.operate || !['Add', 'Edit'].includes(baTable.form.operate)) {
            return
        }
        if (!isRootGroup.value || !adminInfo.super) {
            return
        }
        if (cid === null || cid === undefined || cid === '') {
            items['channel_name'] = ''
            return
        }
        try {
            const res = await createAxios(
                {
                    url: '/admin/auth.Group/channelBindPreview',
                    method: 'get',
                    params: { channel_id: cid },
                },
                { showErrorMessage: false, showCodeMessage: false }
            )
            items['channel_name'] = typeof res.data.channel_name === 'string' ? res.data.channel_name : ''
        } catch {
            items['channel_name'] = ''
        }
    }
)

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    name: [buildValidatorData({ name: 'required', title: t('auth.group.Group name') })],
    auth: [
        {
            required: true,
            validator: (rule: any, val: string, callback: Function) => {
                let ids = getCheckeds()
                if (ids.length <= 0) {
                    return callback(new Error(t('Please select field', { field: t('auth.group.jurisdiction') })))
                }
                return callback()
            },
        },
    ],
    pid: [
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (!val) {
                    return callback()
                }
                if (parseInt(val) == parseInt(baTable.form.items!.id)) {
                    return callback(new Error(t('auth.group.The parent group cannot be the group itself')))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
})

const getCheckeds = () => {
    return treeRef.value!.getCheckedKeys().concat(treeRef.value!.getHalfCheckedKeys())
}

const treeNodeClass = (data: anyObj, node: Node) => {
    if (node.isLeaf) return ''
    let addClass = true
    for (const key in node.childNodes) {
        if (!node.childNodes[key].isLeaf) {
            addClass = false
        }
    }
    return addClass ? 'penultimate-node' : ''
}

defineExpose({
    getCheckeds,
})
</script>

<style scoped lang="scss">
.group-channel-inherit-hint {
    margin: -6px 0 14px;
    font-size: 12px;
    line-height: 1.5;
    color: var(--el-text-color-secondary);
    box-sizing: border-box;
}

:deep(.penultimate-node) {
    .el-tree-node__children {
        padding-left: 60px;
        white-space: pre-wrap;
        line-height: 12px;
        .el-tree-node {
            display: inline-block;
        }
        .el-tree-node__content {
            padding-left: 5px !important;
            padding-right: 5px;
            .el-tree-node__expand-icon {
                display: none;
            }
        }
    }
}
</style>
