<template>
  <div class="system-manage-container role-manage" v-loading="loading">
    <div class="system-manage-header">
      <div class="header-left">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="名称查询">
            <el-input v-model="searchForm.name" clearable @keydown.enter="handleSearch"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="header-right">
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增角色</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="system-manage-content manage-content">
      <common-table
        :autoHeight="true"
        :maxRows="10"
        :rowHeight="40"
        :data="tableData"
        :columns="tableColumns"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        title=""
        :index="true"
        :border="true"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentPageChange"
      >
        <template #operations="{ row, index }">
          <el-button link type="primary" size="small" @click="handleEdit(row, index)">
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row, index)">
            删除
          </el-button>
          <!-- <el-button type="text" size="small">数据权限 </el-button> -->
        </template>
      </common-table>
    </div>

    <el-dialog class="add-dialog"
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
      @close="cancelRoleForm"
      :close-on-click-modal="false" :close-on-press-escape="false"
    >
      <el-form :model="roleFormData" ref="roleForm" :rules="roleRules" label-width="100">
        <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleFormData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="key">
            <el-input v-model="roleFormData.key" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="菜单配置">
          <el-tree ref="treeRef"
              v-model="roleFormData.menus"
              :data="treeData"
              node-key="id"
              :props="{label: 'name'}"
              showCheckbox
              @check="selectMenus"
          />
        </el-form-item>
      </el-form>
      <template #footer>
          <div class="dialog-footer">
              <el-button @click="cancelRoleForm">取消</el-button>
              <el-button type="primary" @click="saveRoleForm">保存</el-button>
          </div>
      </template>
      <!-- <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="菜单配置" :close-on-click-modal="false" :close-on-press-escape="false"d>
      <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 CommonTable from "@/components/common/commonTable.vue";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const treeData = ref([]);
const treeRef = ref(null);

// 查询表单数据
const searchForm = ref({});

// 表格数据
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: 100,
    slot: "operations",
    fixed: "right",
    align: "center",
  },
];

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

// 用户表单数据
const roleForm = ref();
const roleFormData = ref({});
const roleRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" }
  ],
  key: [
    { required: true, message: "请输入角色标识", trigger: "blur" }
  ]
};
// 事件处理函数
const handleSearch = (formData) => {
  currentPage.value = 1;
  loadTableData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadTableData();
};

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

// 新增角色
const handleAdd = () => {
  dialogTitle.value = "新增角色";
  dialogVisible.value = true;
};
// 编辑
const handleEdit = (row, index) => {
  dialogTitle.value = "编辑角色";
  proxy.$post({
    url: "/api/user/role/getRole",
    data: { id: row.id },
    callback: (data) => {
      roleFormData.value = { ...data };
      if (data.menus && data.menus.length) {
        treeRef.value.setCheckedKeys(data.menus);
      }
    },
    error: (err) => {
      ElMessage.error("编辑失败:", err);
    },
  });
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row, index) => {
    ElMessageBox.confirm(`确定要删除角色"${row.name}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      proxy.$post({
        url: "/api/user/role/deleteRole",
        data: { id: row.id },
        callback: (data) => {
          ElMessage.success("删除成功");
          loadTableData();
        },
        error: (err) => {
          ElMessage.error("删除失败:", err);
        },
      });
    });
};

const saveRoleForm = () => {
  roleForm.value.validate(valid => {
    if (valid) {
      let url = roleFormData.value.id ? "updateRole" : "createRole";
      proxy.$post({
        url: "/api/user/role/" + url,
        data: roleFormData.value,
        callback: (data) => {
          ElMessage.success(dialogTitle.value + "成功");
          cancelRoleForm();
          loadTableData();
        },
        error: (err) => {
          ElMessage.error(dialogTitle.value + "失败:", err);
        }
      });
    }
  })
};
const cancelRoleForm = () => {
  roleFormData.value = {};
  roleForm.value.resetFields();
  treeRef.value.setCheckedKeys([]);
  dialogVisible.value = false;
}
const selectMenus = () => {
  // 使用 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 写回表单数据，供提交使用
  roleFormData.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">
  @import "@/styles/manage.less";
.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>
