<template>
    <app-drawer title="编辑" width="600" v-model:show="show" :refresh="refresh">
        <el-form ref="formRef" class="el-form--vertical" label-width="90px" :model="formData" :rules="formRules"
            :show-message="false">
            <el-form-item label="权限类型" prop="authType">
                <el-radio-group v-model="formData.authType">
                    <template v-for="(item, index) in getAuthTypeList()" :key="index">
                        <el-radio :label="item.label" :value="item.value" />
                    </template>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="所属层级">
                <el-tree-select v-model="formData.parentCode" :data="menus" :empty-values="[null, undefined]"
                    value-key="resourceCode" default-expand-all>
                    <template #default="{ data }">
                        <el-option :label="data.title || '[无效的标题]'" :value="data.resourceCode" />
                    </template>
                </el-tree-select>
            </el-form-item>
            <el-form-item label="权限标题" prop="title">
                <el-input v-model="formData.title" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="权限代码" prop="resourceCode">
                <el-input v-model="formData.resourceCode" placeholder="请输入" :disabled="!!record?.resourceCode" />
            </el-form-item>
            <el-form-item label="按钮样式" v-if="formData.authType === AuthType.Operate">
                <div class="el-form-item--col">
                    <el-select v-model="formData.className" clearable>
                        <el-option label="默认" value="default" />
                        <el-option label="主要" value="primary" />
                        <el-option label="成功" value="success" />
                        <el-option label="信息" value="info" />
                        <el-option label="警告" value="warning" />
                        <el-option label="危险" value="danger" />
                    </el-select>
                    <el-button :type="formData.className">
                        <component :is="components.appIcon" :icon="formData.icon" />
                        <span v-if="formData.title">{{ formData.title }}</span>
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="图标">
                <component :is="components.appIconSelect" v-model="formData.icon" />
            </el-form-item>
            <el-form-item label="链接地址" prop="url" v-if="formData.authType === AuthType.Menu">
                <el-input v-model="formData.url" placeholder="请输入">
                    <template #prepend>
                        <el-select v-model="formData.urlType" style="width: 120px">
                            <el-option :label="item.label" :value="item.value" v-for="(item, index) in getUrlTypeList()"
                                :key="index" />
                        </el-select>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="组件地址" prop="component"
                v-if="formData.authType !== AuthType.Menu || formData.urlType === UrlType.Path">
                <el-input v-model="formData.component" placeholder="请输入" />
            </el-form-item>
            <!-- <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" :rows="3" v-model="formData.remark" placeholder="请输入" />
                </el-form-item> -->
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="formData.sort" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="是否显示">
                <el-switch v-model="formData.show" :active-value="1" :inactive-value="0" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">取消</el-button>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { shallowRef, reactive, PropType, defineAsyncComponent, onMounted, toRaw, computed } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { hasValueInTree } from '@/filters'
import { AuthType, UrlType, getAuthTypeList, getUrlTypeList } from '@/constants/menu'
import { dealMenus } from '@/services/api/user'
import { useRouterStore } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'

const components = {
    appIcon: defineAsyncComponent(() => import('@pc/components/base/icon/index.vue')),
    appIconSelect: defineAsyncComponent(() => import('@pc/components/base/icon-select/index.vue')),
}

const props = defineProps({
    record: {
        type: Object as PropType<Model.MenusRsp>
    }
})

const routerStore = useRouterStore()
const formRef = shallowRef<FormInstance>()
const show = shallowRef(true)
const refresh = shallowRef(false)

const menus = computed(() => {
    const data: Model.MenusRsp[] = [{
        resourceCode: '',
        parentCode: '',
        authType: AuthType.Menu,
        title: '一级菜单',
        urlType: UrlType.Path,
        url: '',
        component: '',
        icon: '',
        className: 'default',
        sort: 0,
        show: 1,
        remark: ''
    }, ...toRaw(routerStore.userRoutes)]

    // 移除指定的节点
    const removeNodesByCode = (arr: Model.MenusRsp[], code?: string) => {
        return arr.map(item => {
            // 创建新对象，避免直接修改原始对象
            const newItem = { ...item }
            // 递归处理 children
            if (newItem.children) {
                newItem.children = removeNodesByCode(newItem.children, code)
                // 删除为空的 children
                if (newItem.children.length === 0) {
                    delete newItem.children
                }
            }
            return newItem // 返回新的对象
        }).filter(item => item.resourceCode !== code && item.authType !== AuthType.Operate)
    }

    return removeNodesByCode(data, props.record?.resourceCode)
})

const formData = reactive<Model.DealMenusReq>({
    resourceCode: '',
    parentCode: '',
    authType: AuthType.Menu,
    title: '',
    urlType: UrlType.Path,
    url: '',
    component: '',
    icon: '',
    className: 'default',
    sort: 0,
    show: 1,
    remark: ''
})

// 表单验证规则
const formRules: FormRules = {
    title: [{ required: true }],
    resourceCode: [{ required: true }],
    url: [{ required: true }],
    component: [{ required: true }]
}

const onCancel = (isRefresh = false) => {
    show.value = false
    refresh.value = isRefresh
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            const rawData = toRaw(formData)
            const hasNode = hasValueInTree(routerStore.userRoutes, rawData.resourceCode, { id: 'resourceCode' })

            if (props.record?.resourceCode === rawData.resourceCode || !hasNode) {
                if (rawData.authType === AuthType.Menu) {
                    if (rawData.urlType !== UrlType.Path) {
                        rawData.component = ''
                    }
                } else {
                    rawData.urlType = UrlType.None
                    rawData.url = ''
                }
                dealMenus({
                    data: rawData
                }).then(() => {
                    ElMessage.success('保存成功')
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error('保存失败：' + err)
                })
            } else {
                ElMessage.warning('代码 ' + rawData.resourceCode + ' 已存在')
            }
        }
    })
}

onMounted(() => {
    if (props.record) {
        ({
            resourceCode: formData.resourceCode,
            parentCode: formData.parentCode,
            authType: formData.authType,
            title: formData.title,
            urlType: formData.urlType,
            url: formData.url,
            component: formData.component,
            icon: formData.icon,
            className: formData.className,
            sort: formData.sort,
            show: formData.show,
            remark: formData.remark,
        } = props.record)
    }
})
</script>