<template>
    <el-dialog class="cn-operate-dialog" width="500px" v-model.trim="dialogVisible" :title="title">
        <el-form :inline="false" ref="formRef" :model="form" label-width="auto" class="form-one" :rules="rules">
            <el-form-item label="角色名称" prop="name">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.name" placeholder="请输入菜单名称" />
            </el-form-item>
            <el-form-item label="角色编码" prop="code">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.code" placeholder="请输入菜单名称" />
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input  show-word-limit 
                    maxlength="300"
                    
                    v-model.trim="form.remark"
                    :rows="2"
                    type="textarea"
                    placeholder="请输入描述"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { reactive } from 'vue'
import TableStore from '@/utils/tableStore'
import { ElMessage } from 'element-plus'
import { add, update } from '@/api/user-boot/role'
import { useAdminInfo } from '@/stores/adminInfo'

const adminInfo = useAdminInfo()
const tableStore = inject('tableStore') as TableStore
// do not use same name with ref
const form = reactive({
    code: '',
    name: '',
    remark: '',
    id: '',
    type: 0
})
const loading = ref(false)
const rules = {
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
}
const dialogVisible = ref(false)
const title = ref('新增菜单')
const formRef = ref()
const open = (text: string, data?: anyObj) => {
    formRef.value?.resetFields()
    title.value = text
    dialogVisible.value = true
    if (data) {
        for (let key in form) {
            form[key] = data[key]
        }
    } else {
        for (let key in form) {
            form[key] = ''
        }
    }
}
const submit = async () => {
    formRef.value.validate(async valid => {
        if (valid) {
            loading.value = true
            if (form.id) {
                await update(form)
            } else {
                form.type = adminInfo.$state.userType + 1
                await add(form)
            }
            ElMessage.success('保存成功')
            tableStore.index()
            dialogVisible.value = false
            loading.value = false
        }
    })
}

defineExpose({ open })
</script>
