<template>
  <basic-container>
    <el-form :inline="true">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input v-model="queryParams.menuName" placeholder="请输入菜单名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
        <el-button :icon="Plus" type="primary" @click="addOrUpdateHandle(false)"> 新增 </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      border
      :data="menuList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildrens' }"
    >
      <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" />
      <el-table-column prop="icon" label="图标" align="center">
        <template #default="{ row }">
          <i :class="row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" />
      <el-table-column prop="path" label="组件路径" :show-overflow-tooltip="true" />
      <el-table-column prop="menuType" label="类型" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.menuType === '0'" type="success">左菜单</el-tag>
          <el-tag v-if="row.menuType === '2'" type="success">顶菜单</el-tag>
          <el-tag v-if="row.menuType === '1'" type="info">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="keepAlive" label="缓冲" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.keepAlive === '0'" type="info">关闭</el-tag>
          <el-tag v-if="row.keepAlive === '1'" type="success">开启</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="permission" label="权限标识" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="170" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <div class="table_btn">
            <el-button size="small" :icon="Plus" @click="addOrUpdateHandle(false, row.id)"> 新增 </el-button>
            <el-button size="small" :icon="Edit" @click="addOrUpdateHandle(true, row.id)">修改 </el-button>
            <el-button size="small" :icon="Delete" @click="handleDelete(row)">删除 </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="title" width="50%" :before-close="handleClose">
      <el-form :model="menuInfo" label-width="80px" ref="formRef" :rules="formRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单类型">
              <el-radio-group v-model="menuInfo.menuType" @change="dialogFormChange">
                <el-radio-button label="0">左菜单</el-radio-button>
                <el-radio-button label="1">按钮</el-radio-button>
                <!-- <el-radio-button label="2">顶菜单</el-radio-button> -->
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级菜单" prop="parentId">
              <el-tree-select
                placeholder="选择上级菜单"
                v-model="menuInfo.parentId"
                :data="menuOptions"
                check-strictly
                :render-after-expand="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="menuInfo.menuType === '0'">
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item v-if="menuInfo.menuType === '0'" label="图标" prop="icon">
                <avue-input-icon v-model="menuInfo.icon" :icon-list="iconList" />
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <el-input v-model="menuInfo.name" placeholder="请输入菜单名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="路由地址" prop="path">
                <el-input v-model="menuInfo.path" placeholder="请输入路由地址" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-if="menuInfo.menuType === '1'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <el-input v-model="menuInfo.name" placeholder="请输入菜单名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="权限标识" prop="permission">
                <el-input v-model="menuInfo.permission" placeholder="请权限标识" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="menuInfo.sortOrder" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="menuInfo.menuType === '0'" label="路由缓冲" prop="keepAlive">
              <el-radio-group v-model="menuInfo.keepAlive">
                <el-radio-button label="0">否</el-radio-button>
                <el-radio-button label="1">是</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMenu">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { IMenuForm } from "@/const/interface_type";

import { fetchMenuTree, getMenuObj, addMenuObj, delMenuObj, putMenuObj } from "@/api/admin";
interface Params {
  menuName: string;
}
const queryParams = ref<Params>({ menuName: "" }); // 搜索参数
const menuList = ref([]); // 表格数据
const loading = ref<boolean>(false); // 表格loading

const dialogVisible = ref<boolean>(false); // 弹窗是否展开
const title = ref<string>(""); // 弹窗标题
const formRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  parentId: [{ required: true, message: "上级菜单不能为空", trigger: "change" }],
  name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
  sortOrder: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
  path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  keepAlive: [{ required: true, message: "路由缓冲不能为空", trigger: "blur" }],
  permission: [{ required: true, message: "权限标识不能为空", trigger: "blur" }]
});
const menuInfo = ref<IMenuForm>({
  menuType: "0",
  parentId: "",
  name: "",
  path: "",
  permission: "",
  sortOrder: 999,
  keepAlive: "1"
}); // 菜单详情
const menuOptions = ref<any>([]); // 菜单目录

// 获取列表
const getList = () => {
  loading.value = true;
  fetchMenuTree(queryParams.value).then((res: any) => {
    if (res.code === 0) {
      menuList.value = res.data;
      loading.value = false;
    }
  });
};

// 打开添加/修改菜单弹窗
const addOrUpdateHandle = (isEdit: boolean, id?: string) => {
  /** 查询菜单下拉树结构 */
  fetchMenuTree().then((res) => {
    const menu = [{ id: "-1", label: "根菜单", children: res.data }];
    menuOptions.value = filterList(menu);
  });
  dialogVisible.value = true;
  title.value = isEdit ? "修改" : "新增";
  if (id) menuInfo.value.parentId = id;
  if (isEdit && id) {
    getMenuObj(id).then((res: any) => {
      if (res.code === 0) {
        menuInfo.value = res.data;
      }
    });
  }
};

// 修改弹窗内容类型
const dialogFormChange = (val: string) => {
  if (val === "0") {
    menuInfo.value.permission = "";
  } else {
    menuInfo.value.path = "";
  }
};

// 删除菜单
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`是否确认删除名称为 “${row.name}” 的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delMenuObj(row.id).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`删除 “${row.name}” 成功`);
        getList();
      }
    });
  });
};

const filterList = (arr: any) => {
  const filterData = arr.map((item: any) => {
    return {
      label: item.label,
      value: item.id,
      children: item.children?.length ? filterList(item.children) : []
    };
  });
  return filterData;
};

// 提交新增/修改菜单
const submitMenu = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (title.value === "修改") {
        putMenuObj(menuInfo.value).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success("修改成功");
            clearDialogData();
          }
        });
      } else {
        addMenuObj(menuInfo.value).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success("添加成功");
            clearDialogData();
          }
        });
      }
    } else {
      return false;
    }
  });
};

// 新增/修改弹窗关闭前
const handleClose = (done: () => void) => {
  clearDialogData();
  done();
};

// 清空弹窗数据
const clearDialogData = () => {
  menuInfo.value = {
    menuType: "0",
    parentId: "",
    name: "",
    path: "",
    permission: "",
    sortOrder: 999,
    keepAlive: "1"
  };
  formRef.value?.clearValidate();
  dialogVisible.value = false;
  getList();
};

getList();
</script>
