<template>
  <div class="main">
    <!-- <div class="export-button pl-10">
      <el-button v-has="99102" type="primary" @click="onClick_add">
        创建账号
      </el-button>
    </div> -->
    <el-table border :data="tableData" style="
        width: 80%;
        font-size: 20px;
        overflow: hidden;
        border-radius: 4px;
        margin: 20px 0 0 50px;
      ">
      <el-table-column prop="id" label="ID" width="180" align="center" />
      <el-table-column prop="username" label="用户名" width="180" align="center" />
      <el-table-column prop="full_name" label="全名" width="300" align="center" />
      <el-table-column prop="email" label="邮箱" width="400" align="center" />
      <el-table-column fixed="right" label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" v-if="operationPermissions['c-2']"
            @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination v-if="total > 0" :page-sizes="[10, 20, 30, 40, 100]" :page-size="page.pageSize" :total="total"
        @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <el-dialog v-model="dialogFormVisible" title="编辑账号" width="500">
      <el-form :model="form">
        <el-form-item label="用户名">
          <el-input v-model="form.username" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role_ids" placeholder="Please select a zone">
            <el-option v-for="item in rolesData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitChange"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="orgRoleDialogVisible" title="用户机构与角色管理" width="70vw">
      <el-button type="primary" v-if="operationPermissions['c-2-1']" @click="handleAddOrgRole"
        style="margin: 10px">新增机构角色</el-button>
      <el-table :data="orgRoleTable" style="width: 100%">
        <el-table-column prop="organ_name" label="机构" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column prop="data_type" label="类型">
          <template #default="scope">
            <span>
              {{ scope.row.data_type === 1 ? '个人' : scope.row.data_type === 2 ? '本机构' : scope.row.data_type === 3 ?
                '机构及下辖机构' : '' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEditOrgRole(scope.row)"
              v-if="operationPermissions['c-2-2']">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteOrgRole(scope.row)"
              v-if="operationPermissions['c-2-3']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="isEditOrgRole" :title="EditOrgRoleTittle" width="700">
        <el-form :model="orgRoleForm" label-width="80px">
          <el-form-item label="机构">
            <el-tree-select v-model="orgRoleForm.organ_id" :data="orgList"
              :props="{ label: 'name', value: 'id', children: 'children' }" placeholder="请选择机构" clearable check-strictly
              style="width: 100%" />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="orgRoleForm.role_id" placeholder="请选择角色">
              <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="orgRoleForm.data_type" placeholder="请选择类型">
              <el-option :value="1" label="个人" />
              <el-option :value="2" label="本机构" />
              <el-option :value="3" label="机构及下辖机构" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="isEditOrgRole = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOrgRole">保存</el-button>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { useMenuStore } from "@/stores/menu.js"
const { operationPermissions } = useMenuStore();
const { proxy } = getCurrentInstance();
let tableData = ref([]);
let total = ref(0);
let dialogFormVisible = ref(false);
let rolesData = ref([]);
let page = reactive({
  userName: "",
  pageNo: 1,
  pageSize: 10,
});
let form = reactive({
  username: "",
  user_id: 0,
  role_ids: "",
});
// 新增：机构角色管理相关
const orgRoleDialogVisible = ref(false);
const orgRoleTable = ref([]);
const orgRoleForm = reactive({
  id: null,
  organ_id: null,
  org_name: "",
  role_id: null,
  role_name: "",
  data_type: null, // 新增
});
let tablePage = reactive({
  page: 1,
  page_size: 100,
});
const orgList = ref([]);
const roleList = ref([]);
const isEditOrgRole = ref(false);
const EditOrgRoleTittle = ref("");
const currentUserId = ref(''); // 当前用户ID

// 获取当前用户的机构和角色
const fetchUserOrgRoles = async (userId) => {
  // 假设接口返回 [{id, org_id, org_name, role_id, role_name}]
  const { records } = await proxy.$http.post(
    `/open-platform/userRoleOrgan/data-list`,
    { user_id: userId, ...tablePage }
  );
  console.log(records, "获取用户机构角色数据");
  orgRoleTable.value = records || [];
};
// 获取所有机构
const fetchOrgList = async () => {
  const { records } = await proxy.$http.get("/open-platform/organ/loadData");
  orgList.value = records || [];
};
// 获取所有角色
const fetchRoleList = async () => {
  const { records } = await proxy.$http.get("/open-platform/user/roles");
  roleList.value = records || [];
};

// 新增机构角色
const handleAddOrgRole = () => {
  EditOrgRoleTittle.value = "新增机构角色";
  isEditOrgRole.value = true;
  Object.assign(orgRoleForm, {
    id: null,
    organ_id: null,
    org_name: "",
    role_id: null,
    role_name: "",
    data_type: null, // 新增
  });
};
const handleEditOrgRole = (row) => {
  EditOrgRoleTittle.value = "编辑机构角色";
  isEditOrgRole.value = true;
  Object.assign(orgRoleForm, row);
};
// 删除机构角色
const handleDeleteOrgRole = async (row) => {
  await proxy.$http.post("/open-platform/userRoleOrgan/delete/" + row.id);
  fetchUserOrgRoles(currentUserId.value);
};
// 保存机构角色
const handleSaveOrgRole = async () => {
  orgRoleForm.user_id = currentUserId.value; // 设置当前用户ID
  if (orgRoleForm.id) {
    // 编辑
    await proxy.$http.post("/open-platform/userRoleOrgan/update", orgRoleForm);
  } else {
    await proxy.$http.post("/open-platform/userRoleOrgan/insert", orgRoleForm);
  }
  isEditOrgRole.value = false;
  fetchUserOrgRoles(currentUserId.value);
};

const init = () => {
  proxy.$http
    .get("/open-platform/user/users", {
      params: {
        ...page,
      },
    })
    .then((res) => {
      // console.log(res, "11");
      if (res.records && res.records.length > 0) {
        res.records.forEach((item) => {
          tableData.value.push(item);
        });
      } else {
        tableData.value = [];
      }
      total.value = res.total;
    });
};
init();
const handleCurrentChange = (val) => {
  page.pageNo = val;
  tableData.value = [];
  init();
};
const getRolesList = () => {
  proxy.$http.get("/open-platform/user/roles").then((res) => {
    if (res.records && res.records.length > 0) {
      rolesData.value = res.records;
    } else {
      rolesData.value = [];
    }
  });
};
getRolesList();
const handleEdit = (row) => {
  // dialogFormVisible.value = true
  // form.username = row.username
  // form.user_id = row.id
  // form.role_ids = row.role_ids ? row.role_ids[0] : ''
  currentUserId.value = row.id; // 保存当前用户ID
  // 新增：获取并展示机构角色
  fetchUserOrgRoles(row.id);
  fetchOrgList();
  fetchRoleList();
  orgRoleDialogVisible.value = true;
};
const submitChange = () => {
  form.role_ids = form.role_ids ? [form.role_ids] : [];
  proxy.$http.post("/open-platform/user/users/roles", form).then((res) => {
    if (res.code === 200) {
      proxy.$message.success("修改成功");
      dialogFormVisible.value = false;
      tableData.value = [];
      init();
    } else {
      proxy.$message.error(res.message || "修改失败");
    }
  });
};
</script>

<style lang="less" scoped>
:deep(.el-table th) {
  background-color: #eef6ff !important;
  /* 设置你想要的背景颜色 */
  color: #333;
  /* 设置表头文字颜色 */
  font-weight: bold;
  /* 设置表头文字加粗 */
}

.page {
  display: flex;
  justify-content: end;
  margin-top: 20px;
  padding-right: 10%;
}
</style>
