<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
        :autoHeight="true"
        :maxRows="10"
        :rowHeight="40"
        :data="tableData"
        :columns="tableColumns"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        title="角色管理"
        :border="true"
        @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" @click="handleEdit(row, index)">
            编辑
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(row, index)">
            删除
          </el-button>
          <!-- <el-button type="text" size="small">数据权限 </el-button> -->
        </template>
      </common-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
      @close="handleDialogClose"
    >
      <commonForm
        v-model="roleForm"
        :config="formConfig"
        :items="formItems"
        :rules="formRules"
        @submit="handleFormSubmit"
        @reset="handleFormReset"
      />
    </el-dialog>
    <!-- <el-dialog v-model="menuVisible" title="菜单配置">
      <el-tree
        :data="treeData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        @node-click="handleNodeClick"
      >
      </el-tree>
       <template #footer>
        <el-button type="primary" @click="hanldeSubmit">保存</el-button>
        <el-button>取消</el-button>
      </template>
    </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 { proxy } = getCurrentInstance();
const loading = ref(false);
const treeData = ref([]);
const tree = ref(null);

// 数据转换函数
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,
  },
];

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

// 表格列配置
const tableColumns = [
  {
    prop: "name",
    label: "角色名称",
    minWidth: 100,
  },
  {
    prop: "createdAt",
    label: "创建时间",
    minWidth: 160,
  },
  {
    prop: "updatedAt",
    label: "更新时间",
    minWidth: 160,
  },
  {
    prop: "operations",
    label: "操作",
    width: 310,
    slot: "operations",
    fixed: "right",
    align: "center",
  },
];

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

// 用户表单数据
const roleForm = ref({
  name: "",
  menus: [],
});

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

// 用户表单项配置
const formItems = computed(() => [
  {
    type: "input",
    prop: "name",
    label: "角色名称",
    placeholder: "请输入角色名称",
    span: 24,
    required: true,
    rules: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  },
  {
    type: "tree",
    prop: "menus",
    label: "菜单配置",
    placeholder: "请选择菜单配置",
    data: treeData.value,
    clearable: true,
    filterable: true,
    checkStrictly: true,
    renderAfterExpand: false,
    showCheckbox: false,
    multiple: true,
    collapseTags: true,
    maxCollapseTags: 2,
    span: 24,
  },
]);

// 表单验证规则
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 handleNodeClick = (data, node, element) => {
  // console.log(data, "data");
  // console.log(node, "node");
  // console.log(element, "element");
};
// 新增用户
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增用户";
  roleForm.value = {
    name: "",
    menus: [],
  };
  dialogVisible.value = true;
};
let currentID = ref();
let currentRow = ref();
// 编辑
const handleEdit = (row, index) => {
  isEdit.value = true;
  dialogTitle.value = "编辑用户";
  editIndex.value = index;
  currentRow.value = row;
  proxy.$post({
    url: "/api/user/role/getRole",
    data: { id: row.id },
    callback: (data) => {
      roleForm.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/role/deleteRole",
      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,
      id: currentID.value,
      menus: Array.isArray(formData.menus) ? formData.menus : [],
    };
    proxy.$post({
      url: "/api/user/role/updateRole",
      data: updateUser,
      callback: (data) => {
        dialogVisible.value = false;
        loadTableData();
        ElMessage.success("更新成功");
      },
      error: (err) => {
        ElMessage.error("更新失败:", err);
      },
    });
  } else {
    // 新增角色
    const newUser = {
      ...formData,
    };
    proxy.$post({
      url: "/api/user/role/createRole",
      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 hanldeSubmit = () => {
  // 获取当前复选框选中的节点信息
  const checkedNodes = tree.value?.getCheckedNodes();
  const halfCheckedNodes = tree.value?.getHalfCheckedNodes();

  // 获取选中节点的ID
  const checkedIds = checkedNodes ? checkedNodes.map((node) => node.id) : [];
  const halfCheckedIds = halfCheckedNodes
    ? halfCheckedNodes.map((node) => node.id)
    : [];

  // 合并所有选中的节点ID（完全选中和半选中的）
  const allSelectedIds = [...checkedIds, ...halfCheckedIds];
};
// 表格数据
const loadTableData = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/user/role/listRole",
    data: {
      ...searchForm.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      tableData.value = data.rows;
      total.value = data.count;
      loading.value = false;
    },
    error: (err) => {
      loading.value = false;
      ElMessage.error("加载数据失败");
    },
  });
};

const handleTreeData = () => {
  proxy.$post({
    url: "/api/user/depart/treeDepart",
    data: {
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      treeData.value = convertToTreeData(data);
    },
    error: (err) => {
      ElMessage.error("加载数据失败");
    },
  });
};

onMounted(() => {
  loadTableData();
  handleTreeData();
});
</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);
  }
}
.el-tree {
  max-height: 500px;
  overflow-y: auto;
  &:not(:hover) {
    scrollbar-width: none;
    -ms-overflow-style: none;
    &::-webkit-scrollbar {
      display: none;
    }
  }
  &:hover {
    scrollbar-width: thin;
    &::-webkit-scrollbar {
      display: block;
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: rgba(144, 147, 153, 0.3);
      border-radius: 3px;
    }
    &::-webkit-scrollbar-track {
      background-color: transparent;
    }
  }
}
</style>
