<template>
    <div class="p-2">
      <transition>
        <div class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
              <!-- <el-form-item label="菜单名称" prop="permission_name">
                <el-input v-model="queryParams.permission_name" placeholder="请输入菜单名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item> -->
              <!-- <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
                  <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item> -->
              <el-form-item>
                <!-- <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>
  
      <el-card shadow="hover">
        <template #header>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增 </el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
            </el-col> --> 
          </el-row>
        </template> 
        <el-table
          v-loading="loading"
          :data="menuList"
          row-key="uid"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          ref="menuTableRef"
          :default-expand-all="isExpandAll" 
        >
          <el-table-column prop="permission_name" label="菜单名称" :show-overflow-tooltip="true" width="160"></el-table-column>
          <el-table-column prop="permission_code" label="权限标识" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="resource_path" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="类型" align="center" prop="permission_type">
            <template #default="scope">
              <el-tag v-if="scope.row.permission_type === 1" type="primary">菜单</el-tag>
              <el-tag v-if="scope.row.permission_type === 3" type="info">按钮</el-tag>  
            </template>
          </el-table-column>
          <el-table-column prop="description" label="权限描述" :show-overflow-tooltip="true" />
          <el-table-column prop="http_method" label="请求方式" :show-overflow-tooltip="true" width="80" />
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"/>
              </el-tooltip>
              <el-tooltip content="新增" placement="top">
                <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"/>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"/>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <el-dialog :title="dialog.title" v-model="dialog.visible" destroy-on-close append-to-body width="750px">
        <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="100px">
          <el-row> 
            <el-col :span="24">
              <el-form-item label="上级菜单">
                <el-tree-select
                  v-model="form.parent_uid"
                  :data="menuOptions"
                  :props="{ value: 'uid', label: 'permission_name', children: 'children' }"
                  value-key="uid"
                  placeholder="选择上级菜单"
                  check-strictly
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="菜单名称" prop="permission_name"> 
                    <el-input v-model="form.permission_name" placeholder="请输入菜单名称"/>
                </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="菜单类型" prop="permission_type">
                <el-radio-group v-model="form.permission_type"> 
                  <el-radio :label="1">菜单</el-radio>
                  <el-radio :label="3">按钮</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>   
            <el-col :span="24">
              <el-form-item prop="permission_code">
                <el-input v-model="form.permission_code" placeholder="请输入权限标识" maxlength="100" />
                <template #label>
                  <span>
                    <el-tooltip content="控制器中定义的权限字符，如：user:list')" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    权限字符
                  </span>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.permission_type === 1">
              <el-form-item prop="resource_path">
                <template #label>
                  <span>
                    <el-tooltip content="访问的路径，如：`/user/index`" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    路径
                  </span>
                </template>
                <el-input v-model="form.resource_path" placeholder="请输入组件路径" />
              </el-form-item>
            </el-col> 
            <!-- <el-col :span="24" v-if="form.permission_type === 3">
              <el-form-item prop="http_method">
                <template #label>
                  <span>
                    <el-tooltip content="请求方法，如：`GET`、`POST`、`PUT`、`DELETE`等" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    请求方法
                  </span>
                </template>
                <el-input v-model="form.http_method" placeholder="请输入请求方法" />
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
                <el-form-item label="权限描述" prop="description">
                    <el-input v-model="form.description" type="textarea" placeholder="请输入权限描述"></el-input>
                </el-form-item> 
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
</template>
  
  <script setup name="menuManagement">
  import { addMenu, delMenu, listMenu, updateMenu } from '@/api/menu.js';   
  
  const { proxy } = getCurrentInstance() 

  const menuList = ref([])
  const loading = ref(true) 
  const menuOptions = ref([])
  const isExpandAll = ref(false)
  
  const dialog = reactive({
    visible: false,
    title: ''
  });
  
  const queryFormRef = ref();
  const menuFormRef = ref();
  const menuTableRef = ref();
  const initFormData = {
    permission_name: '', 
    permission_type: 1,// 1：菜单 3：按钮  2:接口
    permission_code: '',
    resource_path: '',
    http_method: '',
    description: '',
    parent_uid: '',
  }
  const data = reactive({
    form: { ...initFormData },
    queryParams: {
        permission_types:'1,3'
    },
    rules: {
      permission_name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
      permission_code: [{ required: true, message: "权限标识不能为空", trigger: "blur" }],
      permission_type: [{ required: true, message: "菜单类型不能为空", trigger: "change" }],
    },
  })
  

  
  const { queryParams, form, rules } = toRefs(data)
  /** 查询菜单列表 */
  const getList = async () => {
    loading.value = true
    const res = await listMenu(queryParams.value); 
    menuList.value = res.data 
    loading.value = false
  }
  /** 查询菜单下拉树结构 */
  const getTreeselect = async () => {
    menuOptions.value = []
    const response = await listMenu(queryParams.value);
    const menu = { uid: '0', permission_name: "主类目", children: [] }
    menu.children = response.data
    menuOptions.value.push(menu)
  }
  /** 取消按钮 */
  const cancel = () => {
    // reset()
    dialog.visible = false
  }
  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    menuFormRef.value?.resetFields();
  }
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    getList();
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  /** 新增按钮操作 */
  const handleAdd = (row) => {
    reset();
    getTreeselect();
    row && row.uid ? form.value.parent_uid = row.uid : form.value.parent_uid = '';
    dialog.visible = true;
    dialog.title = "添加菜单";
  }
  /** 展开/折叠操作 */
  const handleToggleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value;
    toggleExpandAll(menuList.value, isExpandAll.value)
  }
  /** 展开/折叠所有 */
  const toggleExpandAll = (data, status) => {
    data.forEach((item) => {
      menuTableRef.value?.toggleRowExpansion(item, status)
      if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
    })
  }
  /** 修改按钮操作 */
  const handleUpdate = async (row) => {
    reset();
    await getTreeselect(); 
    if(row.parent_uid == ''){
        row.parent_uid = '0'
    }
    form.value = row; 
    dialog.visible = true;
    dialog.title = "修改菜单";
  }
  /** 提交按钮 */
  const submitForm = () => {
    try {
        menuFormRef.value?.validate(async (valid) => {
        if (valid) { 
            form.value.uid ? await updateMenu(form.value) : await addMenu(form.value);
            ElMessage.success('操作成功');
            dialog.visible = false;
            await getList();
        }
        })
    } catch (err) { 
        ElMessage.error('操作失败');
    }

  }

  const handleDelete = async (row) => { 
    try { 
        await ElMessageBox.confirm(
            `确认要删除"${row.permission_name}"的数据项?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ); 
        const menuid = row?.uid;  
        const res = await delMenu(menuid);
        if(res.meta.code !== 200){
            ElMessage.error(res.data.message);
            return;
        } 
        await getList();
        ElMessage.success(`${row.permission_name}权限删除成功`); 
    } catch (err) {  
        const errorMsg = err?.toString() || ''; 
        if (errorMsg.includes('cancel') || 
            errorMsg.includes('取消') || 
            errorMsg === 'cancel' || 
            err === 'cancel') { 
            return;
        }    
        if (errorMsg.includes('close') || err === 'close') { 
            return;
        } 
        ElMessage.error(`${row.permission_name}权限删除失败`);
    }    
  }
  
  onMounted(() => {
    getList();
  });
  </script>
  