<template>
  <div class="user-manage" v-loading="loading">
    <div class="search-form">
      <commonForm
        v-model="searchForm"
        :config="searchConfig"
        :items="searchItems"
        @submit="handleSearch"
        @reset="handleReset"
      />
    </div>
    <div class="table-container">
      <common-table
        :maxRows="10"
        :rowHeight="40"
        :data="tableData"
        :columns="tableColumns"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :indent="10"
        title="菜单管理"
        :border="true"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="id"
        default-expand-all
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentPageChange"
      >
        <template #header-actions>
          <el-button type="primary" @click="handleAdd">新增 </el-button>
        </template>

        <template #operations="{ row, index }">
          <el-button type="text" size="small"> 新增 </el-button>
          <el-button type="text" size="small" @click="handleEdit(row, index)">
            编辑
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(row, index)">
            删除
          </el-button>
        </template>
      </common-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <commonForm
        v-model="userForm"
        :config="formConfig"
        :items="formItems"
        :rules="formRules"
        @submit="handleFormSubmit"
        @reset="handleFormReset"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import commonForm from "@/components/common/commonForm.vue";
import CommonTable from "@/components/common/commonTable.vue";
import { da } from "element-plus/es/locales.mjs";

// 模拟树形菜单数据
const mockMenuData = [
  {
    id: 1,
    name: "系统管理",
    code: "system",
    app: "管理平台",
    type: "目录",
    icon: "Setting",
    order: 1,
    createdAt: "2024-01-01",
    children: [
      {
        id: 11,
        name: "用户管理",
        code: "user",
        app: "管理平台",
        type: "菜单",
        icon: "User",
        order: 1,
        createdAt: "2024-01-01",
        children: [
          {
            id: 111,
            name: "用户列表",
            code: "user-list",
            app: "管理平台",
            type: "菜单",
            icon: "List",
            order: 1,
            createdAt: "2024-01-01",
          },
          {
            id: 112,
            name: "用户详情",
            code: "user-detail",
            app: "管理平台",
            type: "菜单",
            icon: "Document",
            order: 2,
            createdAt: "2024-01-01",
          },
        ],
      },
      {
        id: 12,
        name: "角色管理",
        code: "role",
        app: "管理平台",
        type: "菜单",
        icon: "UserFilled",
        order: 2,
        createdAt: "2024-01-01",
      },
      {
        id: 13,
        name: "菜单管理",
        code: "menu",
        app: "管理平台",
        type: "菜单",
        icon: "Menu",
        order: 3,
        createdAt: "2024-01-01",
      },
    ],
  },
  {
    id: 2,
    name: "业务管理",
    code: "business",
    app: "业务平台",
    type: "目录",
    icon: "Briefcase",
    order: 2,
    createdAt: "2024-01-01",
    children: [
      {
        id: 21,
        name: "项目管理",
        code: "project",
        app: "业务平台",
        type: "菜单",
        icon: "FolderOpened",
        order: 1,
        createdAt: "2024-01-01",
      },
      {
        id: 22,
        name: "审批管理",
        code: "approval",
        app: "业务平台",
        type: "菜单",
        icon: "Select",
        order: 2,
        createdAt: "2024-01-01",
      },
    ],
  },
  {
    id: 3,
    name: "数据统计",
    code: "statistics",
    app: "分析平台",
    type: "目录",
    icon: "DataAnalysis",
    order: 3,
    createdAt: "2024-01-01",
    children: [
      {
        id: 31,
        name: "报表中心",
        code: "report",
        app: "分析平台",
        type: "菜单",
        icon: "PieChart",
        order: 1,
        createdAt: "2024-01-01",
      },
    ],
  },
];

const { proxy } = getCurrentInstance();
const loading = ref(false);

// 数据转换函数
const convertToTreeData = (apiData) => {
  return apiData.map((item) => ({
    value: item.id.toString(),
    label: item.name,
    children: item.children ? convertToTreeData(item.children) : [],
  }));
};

// 查询表单数据
const searchForm = ref({
  name: "",
  mobile: "",
});

// 查询表单配置
const searchConfig = {
  inline: true,
  labelWidth: "80px",
  showButtons: true,
  submitText: "查询",
  resetText: "重置",
};

// 查询表单项配置
const searchItems = [
  {
    type: "input",
    prop: "name",
    label: "菜单名称:",
    placeholder: "请输入菜单名称",
    clearable: true,
    span: 8,
  },
  {
    type: "input",
    prop: "mobile",
    label: "菜单编码:",
    placeholder: "请输入菜单编码",
    clearable: true,
    span: 8,
  },
];

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 表格列配置
const tableColumns = [
  {
    prop: "name",
    label: "菜单名称",
    width: 180,
    tree: true,
  },
  {
    prop: "code",
    label: "菜单编号",
    minWidth: 120,
  },
  {
    prop: "type",
    label: "菜单类型",
    minWidth: 100,
  },
  {
    prop: "icon",
    label: "菜单图标",
    minWidth: 100,
  },
  {
    prop: "order",
    label: "排序",
    minWidth: 80,
    align: "center",
  },
  {
    prop: "createdAt",
    label: "创建时间",
    width: 250,
    align: "center",
  },
  {
    prop: "operations",
    label: "操作",
    width: 200,
    slot: "operations",
    fixed: "right",
    align: "center",
  },
];

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增菜单");
const isEdit = ref(false);
const editIndex = ref(-1);

// 用户表单数据
const userForm = ref({
  name: "",
  departs: [],
  positions: [],
  roles: [],
  enable: "0",
});

// 用户表单配置
const formConfig = {
  labelWidth: "100px",
  showButtons: true,
  submitText: "保存",
  resetText: "取消",
};

// 用户表单项配置
const formItems = computed(() => [
  {
    type: "select",
    prop: "name",
    label: "父级菜单：",
    placeholder: "请选择顶级菜单",
    span: 12,
    required: true,
    rules: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
  },
  {
    type: "radio",
    prop: "",
    label: "菜单类型：",
    span: 12,
    options: [
      {
        label: "目录",
        value: "1",
      },
      {
        label: "菜单",
        value: "0",
      },
    ],
  },
  {
    type: "input",
    prop: "mobile",
    label: "菜单名称：",
    placeholder: "请输入菜单名称",
    span: 12,
    required: true,
    rules: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  },
  {
    type: "input",
    prop: "",
    label: "菜单编号：",
    placeholder: "请输入菜单编号",
    span: 12,
    required: true,
    rules: [{ required: true, message: "请输入菜单编号", trigger: "blur" }],
  },
  {
    type: "input",
    prop: "",
    label: "Vue组件：",
    placeholder: "请输入Vue组件",
    span: 12,
  },
  {
    type: "input",
    prop: "",
    label: "路由名称：",
    placeholder: "请输入路由名称",
    span: 12,
  },
  {
    type: "input",
    prop: "",
    label: "路由地址：",
    placeholder: "请输入路由地址",
    span: 12,
  },
  {
    type: "input",
    prop: "",
    label: "排序：",
    placeholder: "请输入排序",
    span: 12,
  },
  {
    type: "radio",
    prop: "",
    label: "显示状态：",
    span: 12,
    options: [
      { label: "显示", value: "0" },
      { label: "隐藏", value: "1" },
    ],
  },
  {
    type: "radio",
    prop: "",
    label: "嵌套模式：",
    span: 12,
    options: [
      { label: "是", value: "0" },
      { label: "否", value: "1" },
    ],
  },
  {
    type: "upload",
    prop: "",
    label: "菜单图标：",
    span: 12,
  },
]);

// 表单验证规则
const formRules = {};

// 事件处理函数
const handleSearch = (formData) => {
  currentPage.value = 1;
  loadTableData();
};

const handleReset = () => {
  searchForm.value = {
    name: "",
    mobile: "",
  };
  currentPage.value = 1;
  loadTableData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadTableData();
};

const handleCurrentPageChange = (page) => {
  currentPage.value = page;
  loadTableData();
};

// 新增用户
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增菜单";
  userForm.value = {
    name: "",
    departs: [],
    positions: [],
    roles: [],
    enable: "0",
  };
  dialogVisible.value = true;
};
let currentID = ref();
// 编辑
const handleEdit = (row, index) => {
  isEdit.value = true;
  dialogTitle.value = "编辑用户";
  editIndex.value = index;
  //   proxy.$post({
  //     url: "/api/user/manage/getUserInfo",
  //     data: { id: row.id },
  //     callback: (data) => {
  //       userForm.value = { ...data };
  //       currentID.value = data.id;
  //     },
  //     error: (err) => {
  //       ElMessage.error("编辑失败:", err);
  //     },
  //   });
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row, index) => {
  try {
    // await ElMessageBox.confirm(`确定要删除用户"${row.name}"吗？`, "提示", {
    //   confirmButtonText: "确定",
    //   cancelButtonText: "取消",
    //   type: "warning",
    // });
    // proxy.$post({
    //   url: "/api/user/manage/deleteUser",
    //   data: { id: row.id },
    //   callback: (data) => {
    //     dialogVisible.value = false;
    //     loadTableData();
    //     ElMessage.success("删除成功");
    //   },
    //   error: (err) => {
    //     ElMessage.error("删除失败:", err);
    //   },
    // });
    // loadTableData();
  } catch {}
};

const handleFormSubmit = (formData) => {
  if (isEdit.value) {
    // 编辑用户
    const updateUser = {
      ...formData,
    };
    // proxy.$post({
    //   url: "/api/user/manage/updateUser",
    //   data: updateUser,
    //   callback: (data) => {
    //     dialogVisible.value = false;
    //     loadTableData();
    //     ElMessage.success("用户信息更新成功");
    //   },
    //   error: (err) => {
    //     ElMessage.error("用户信息更新失败:", err);
    //   },
    // });
  } else {
    // 新增用户
    const newUser = {
      ...formData,
    };
    // proxy.$post({
    //   url: "/api/user/manage/createUser",
    //   data: newUser,
    //   callback: (data) => {
    //     dialogVisible.value = false;
    //     loadTableData();
    //     ElMessage.success("用户添加成功");
    //   },
    //   error: (err) => {
    //     ElMessage.error("用户添加失败:", err);
    //   },
    // });
  }
};

const handleFormReset = () => {
  dialogVisible.value = false;
};

const handleDialogClose = () => {
  dialogVisible.value = false;
};

// 表格数据
const loadTableData = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/user/menu/treeMenu",
    data: {
      ...searchForm.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      tableData.value = data;
      total.value = data.count;
      loading.value = false;
    },
    error: (err) => {
      loading.value = false;
      ElMessage.error("加载数据失败");
    },
  });
};

onMounted(() => {
  loadTableData();
});
</script>

<style scoped lang="less">
.user-manage {
  padding: 20px;
  background: rgba(157, 188, 218, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .search-form {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;
  }

  .table-container {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}
</style>
