<template>
  <div class="user-manage" v-loading="loading">
    <!-- search form moved into table header to align with 新增 button -->
    <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-left>
          <div style="display:flex;align-items:center;gap:12px;">
            <commonForm
              v-model="searchForm"
              :config="searchConfig"
              :items="searchItems"
              @submit="handleSearch"
              @reset="handleReset"
            />
            <el-button type="primary" @click="handleAdd"> 新增 </el-button>
          </div>
        </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"
      >
        <template #menus>
          <el-tree
            :data="treeData"
            node-key="id"
            :props="{
              label: 'name',
              children: 'children'
            }"
            show-checkbox
            @check="hanldeSubmit"
            ref="treeRef"
          />
        </template>
      </commonForm>
    </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, nextTick } 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 treeRef = 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: "key",
    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: "",
  key: "",
  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: "input",
    prop: "key",
    label: "角色标识",
    placeholder: "请输入角色英文标识",
    span: 24,
    required: true,
    rules: [{ required: true, message: "请输入角色英文标识", trigger: "blur" }],
  },
  {
    type: "slot",
    prop: "menus",
    slotName: "menus",
    label: "菜单配置",
    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: "",
    key: "",
    menus: [],
  };
  // 清空树的已选项
  if (treeRef.value && treeRef.value.setCheckedKeys) {
    treeRef.value.setCheckedKeys([]);
  }
  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;
      // 如果返回了已选菜单，延后到下一个 DOM 更新周期再设置树的选中项（确保 tree 已渲染）
      if (data.menus && treeRef.value && treeRef.value.setCheckedKeys) {
        nextTick(() => {
          try {
            treeRef.value.setCheckedKeys(data.menus);
          } catch (e) {
            console.warn('setCheckedKeys failed:', e);
          }
        });
      }
    },
    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) => {
  // 在提交前确保同步树的选中项到 roleForm
  hanldeSubmit();

  if (isEdit.value) {
    // 编辑用户 - 以 roleForm.value 为准，附带 id
    const updateUser = {
      ...roleForm.value,
      id: currentID.value,
    };
    proxy.$post({
      url: "/api/user/role/updateRole",
      data: updateUser,
      callback: (data) => {
        dialogVisible.value = false;
        loadTableData();
        ElMessage.success("更新成功");
      },
      error: (err) => {
        ElMessage.error("更新失败:", err);
      },
    });
  } else {
    // 新增角色 - 以 roleForm.value 为准，包含 menus
    const newUser = {
      ...roleForm.value,
    };
    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 = () => {
  // 使用 treeRef 获取当前勾选节点
  const treeInst = treeRef.value;
  if (!treeInst) return;

  const checkedNodes = treeInst.getCheckedNodes ? treeInst.getCheckedNodes() : [];
  const halfCheckedNodes = treeInst.getHalfCheckedNodes
    ? treeInst.getHalfCheckedNodes()
    : [];

  const checkedIds = checkedNodes ? checkedNodes.map((node) => node.id) : [];
  const halfCheckedIds = halfCheckedNodes
    ? halfCheckedNodes.map((node) => node.id)
    : [];

  const allSelectedIds = Array.from(new Set([...checkedIds, ...halfCheckedIds]));

  // 把选中的菜单 id 写回表单数据，供提交使用
  roleForm.value.menus = allSelectedIds;
  return allSelectedIds;
};
// 表格数据
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/menu/treeMenu",
    data: {
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      treeData.value = 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>
