<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input
            placeholder="请输入菜单名称"
            v-model="queryParams.menuName"
            clearable
            style="width: 240px"
            @keyup.enter.native="getList"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜单状态" prop="status">
          <el-select
            placeholder="请选择菜单状态"
            v-model="queryParams.status"
            clearable
            style="width: 240px"
            @keyup.enter.native="getList"
          >
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识" prop="auth">
          <el-input
            placeholder="请输入权限标识"
            v-model="queryParams.auth"
            clearable
            style="width: 240px"
            @keyup.enter.native="getList"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="getList">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
<!--        <el-col :span="1.5" v-auth="['system:role:update']">-->
<!--          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">修改</el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5" v-auth="['system:role:delete']">-->
<!--          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>-->
<!--        </el-col>-->
<!--        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleTableData"></KoiToolbar>-->
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="menuList"
        :default-expand-all="isExpandAll"
        row-key="menuId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        empty-text="暂时没有数据哟"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="menuId" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="菜单名称"
          prop="menuName"
          align="left"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="图标" prop="icon" align="center" width="100px">
          <template #default="scope">
            <!-- 使用 is 属性绑定组件名称 -->
            <div class="flex flex-justify-center">
              <el-icon v-if="scope.row.icon && scope.row.icon.indexOf('koi-') == '-1'" :size="20">
                <component :is="scope.row.icon"></component>
              </el-icon>
              <el-icon v-if="scope.row.icon && scope.row.icon.indexOf('koi-') == '0'" :size="20">
                <component is="KoiSvgIcon" :name="scope.row.icon"></component>
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="权限标识" prop="perms" align="center" width="200px" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="页面路径" prop="component" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否隐藏" prop="visible" align="center" :show-overflow-tooltip="true" width="100px">
          <template #default="scope">
            <el-tag :type="scope.row.visible == '1' ? 'danger' : 'primary'">
              {{ scope.row.visible == "1" ? "隐藏" : "显示" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路由path" prop="path" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="显示顺序" prop="orderNum" width="90px" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="新增" placement="top">
              <el-button
                type="primary"
                icon="Plus"
                circle
                plain
                @click="handleAdd(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加 OR 修改 -->
      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
        :height="500"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <!-- 菜单级联选择框 -->
                <el-form-item label="上级菜单">
                  <el-tree-select
                    v-model="form.parentId"
                    :data="menuOptions"
                    check-strictly
                    :render-after-expand="false"
                    :props="defaultProps"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <!-- 菜单级联选择框 -->
                <el-form-item label="菜单类型" prop="menuType">
                  <el-radio-group v-model="form.menuType">
                    <el-radio label="M">目录</el-radio>
                    <el-radio label="C">菜单</el-radio>
                    <el-radio label="F">按钮</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }" v-if="form.menuType !== 'F'">
                <div class="flex flex-items-center m-b-15px m-l-8px">
                  <el-form-item prop="icon"></el-form-item>
                  <div class="w-70px">菜单图标</div>
                  <KoiSelectIcon width="300" v-model="form.icon"></KoiSelectIcon>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="菜单名称" prop="menuName">
                  <el-input v-model="form.menuName" placeholder="请输入菜单名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="显示排序" prop="sorted" class="p-l-10px">
                  <el-input-number v-model="form.orderNum" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="路由参数" prop="name">
                  <el-input v-model="form.query" placeholder="例如：如：{id: 1, name: ry}" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }" class="p-l-10px">
                <el-form-item label="权限字符" prop="auth">
                  <el-input v-model="form.perms" placeholder="权限字符[system:user:list]" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.menuType !== 'F'">
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="页面路径" prop="component">
                  <el-input v-model="form.component" placeholder="请输入页面路径[system/user/index]" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.menuType !== 'F'">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="路由名称" prop="name">
                  <el-input v-model="form.name" placeholder="例如：user" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }" class="p-l-10px">
                <el-form-item label="路由Path" prop="path">
                  <el-input v-model="form.path" placeholder="例如：/user[唯一]" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.menuType !== 'F'">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="是否隐藏" prop="isHide">
                  <el-radio-group v-model="form.visible">
                    <el-radio value="1">是</el-radio>
                    <el-radio value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }" class="p-l-10px">
                <el-form-item label="是否缓存" prop="path">
                  <el-radio-group v-model="form.isCache">
                    <el-radio label="0">缓存</el-radio>
                    <el-radio label="1">不缓存</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.menuType !== 'F'">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="菜单状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio value="0">正常</el-radio>
                    <el-radio value="1">停用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="外链地址" prop="isLink">
                  <el-input v-model="form.isFrame" placeholder="请输入外链地址[输入值则判断为外链地址]" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="js" name="menu">
import { nextTick, ref, reactive, onMounted } from "vue";
import { listMenu, getMenu, delMenu, addMenu, updateMenu } from "@/api/system/menu/index.ts";
import { handleTree } from "@/utils/ruoyi.js";
import { koiNoticeSuccess } from "@/utils/koi.ts";
import { ElMessageBox } from 'element-plus'

const loading = ref(true);
const showSearch = ref(true);
const menuList = ref([]);
const menuOptions = ref([]);
const title = ref("");
const open = ref(false);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const confirmLoading = ref(false);
// 添加 OR 修改对话框Ref
const koiDialogRef = ref();

const queryParams = reactive({
  menuName: undefined,
  visible: undefined,
  auth: undefined,
  status: '',
  menuStatus: undefined,
});
// 配置属性
const defaultProps = {
  children: "children",
  label: "menuName",
  value: "menuId"
};

const form = reactive({});

const rules = {
  menuName: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
  orderNum: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
  path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }]
};

onMounted(() => {
  getList();
});

const selected = (name) => {
  form.icon = name;
};

const getList = async () => {
  loading.value = true;
  const { data } = await listMenu(queryParams)
  menuList.value = handleTree(data, "menuId", 'parentId', 'children');
  loading.value = false;
};

const normalizer = (node) => {
  return {
    id: node.menuId,
    label: node.menuName,
    // **始终保持 children 是数组**
    children: node.children && node.children.length ? node.children : undefined,
    isLeaf: !node.children || node.children.length === 0 // 标记叶子节点
  };
};

const getTreeselect = () => {
  listMenu().then(response => {
    menuOptions.value = [];
    const menu = { menuId: 0, menuName: '主类目', children: [] };
    menu.children = handleTree(response.data, "menuId");
    menuOptions.value.push(menu);
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  Object.assign(form, {
    remark: null,
    menuName: "",
    parentName: null,
    parentId: 0,
    orderNum: 1,
    path: "",
    component: "",
    query: "",
    routeName: "",
    isFrame: "1",
    isCache: "0",
    menuType: "C",
    visible: "0",
    status: "0",
    perms: "",
    icon: "",
  });
};

const handleQuery = () => {
  getList();
};

const resetQuery = () => {
  Object.assign(queryParams,
    {
      menuName: undefined,
      visible: undefined,
      auth: undefined,
      status: '',
      menuStatus: undefined,
    }
  )
  getList();
};

const handleAdd = (row) => {
  reset();
  getTreeselect();
  form.parentId = row?.menuId || 0;
  koiDialogRef.value.koiOpen();
  title.value = "添加菜单";
};

const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

const handleUpdate = (row) => {
  getTreeselect();
  koiDialogRef.value.koiOpen();
  getMenu(row.menuId).then(response => {
    const data = response.data;
    Object.assign(form, data);
    open.value = true;
    title.value = "修改菜单";
  });
};

const handleCancel = () => {
  koiDialogRef.value.koiClose();
  form.value = []
};

const handleConfirm = () => {
  const data = { ...form };

  confirmLoading.value = true;
  if (data.menuId !== undefined) {
    updateMenu(data).then(() => {
      confirmLoading.value = false;
      koiNoticeSuccess("修改成功");
      koiDialogRef.value.koiQuickClose();
      getList();
    });
  } else {
    addMenu(data).then(() => {
      confirmLoading.value = false;
      koiNoticeSuccess("添加成功");
      koiDialogRef.value.koiQuickClose();
      getList();
    });
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除菜单?', 'Warning', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      delMenu(row.menuId).then(() => {
        getList();
      });
    })
    .catch(() => {})
};
</script>

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