<template>
  <PageContainer title="数据权限管理">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" @click="openCreateDrawer">新增策略</el-button>
      <el-button v-if="canRead" @click="load">刷新</el-button>
    </QueryToolbar>

    <el-card shadow="never" class="mb-md">
      <template #header>当前用户生效范围</template>
      <div class="lh-loose">
        <div>用户ID：{{ currentScope.userId ?? "-" }}</div>
        <div>项目范围：{{ currentScope.projectAll ? "全部" : (currentScope.projectIds || []).join(",") || "-" }}</div>
        <div>会议范围：{{ currentScope.meetingAll ? "全部" : (currentScope.meetingIds || []).join(",") || "-" }}</div>
        <div>用户范围：{{ currentScope.userAll ? "全部" : (currentScope.userIds || []).join(",") || "-" }}</div>
        <div>专家范围：{{ currentScope.expertAll ? "全部" : (currentScope.expertIds || []).join(",") || "-" }}</div>
        <div>导出权限：{{ currentScope.exportAllowed ? "允许" : "禁止" }}</div>
      </div>
    </el-card>

    <el-table :data="rows" class="mt-md">
      <el-table-column prop="policyName" label="策略名称" width="180" />
      <el-table-column label="当前账号命中" width="120">
        <template #default="{ row }">
          <el-tag v-if="(currentScope.matchedPolicyIds || []).includes(row.id)" type="success">命中</el-tag>
          <el-tag v-else type="info">未命中</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="projectScope" label="项目范围" width="100" :formatter="statusFormatter" />
      <el-table-column prop="projectIdsCsv" label="项目ID集" />
      <el-table-column prop="meetingScope" label="会议范围" width="100" :formatter="statusFormatter" />
      <el-table-column prop="meetingIdsCsv" label="会议ID集" />
      <el-table-column prop="userScope" label="用户范围" width="100" :formatter="statusFormatter" />
      <el-table-column prop="userIdsCsv" label="用户ID集" />
      <el-table-column prop="expertScope" label="专家范围" width="100" :formatter="statusFormatter" />
      <el-table-column prop="expertIdsCsv" label="专家ID集" />
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column label="操作" width="420">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="openEdit(row)">编辑</el-button>
          <el-button v-if="canManage" size="small" @click="openAssignRoles(row)">分配角色</el-button>
          <el-button v-if="canManage" size="small" @click="handleCopy(row.id)">复制</el-button>
          <el-button v-if="canManage && row.status !== 'ENABLED'" size="small" type="success" @click="handleEnable(row.id)">启用</el-button>
          <el-button v-else-if="canManage" size="small" type="warning" @click="handleDisable(row.id)">停用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="createVisible" title="新增策略" :size="DRAWER_SIZE.md" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="策略名称" prop="policyName">
          <el-input v-model="form.policyName" />
        </el-form-item>
        <el-form-item label="项目范围" prop="projectScope">
          <el-select v-model="form.projectScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.projectScope === 'IDS'" label="项目ID集" prop="projectIdsCsv">
          <el-input v-model="form.projectIdsCsv" placeholder="如 1001,1002" />
        </el-form-item>
        <el-form-item label="会议范围" prop="meetingScope">
          <el-select v-model="form.meetingScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.meetingScope === 'IDS'" label="会议ID集" prop="meetingIdsCsv">
          <el-input v-model="form.meetingIdsCsv" placeholder="如 2001,2002" />
        </el-form-item>
        <el-form-item label="用户范围" prop="userScope">
          <el-select v-model="form.userScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.userScope === 'IDS'" label="用户ID集" prop="userIdsCsv">
          <el-input v-model="form.userIdsCsv" placeholder="如 3001,3002" />
        </el-form-item>
        <el-form-item label="专家范围" prop="expertScope">
          <el-select v-model="form.expertScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.expertScope === 'IDS'" label="专家ID集" prop="expertIdsCsv">
          <el-input v-model="form.expertIdsCsv" placeholder="如 4001,4002" />
        </el-form-item>
        <el-form-item label="允许导出" prop="exportAllowed">
          <el-switch v-model="form.exportAllowed" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="editVisible" title="编辑策略" :width="DIALOG_WIDTH.md">
      <el-form ref="editFormRef" :model="editForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="策略名称" prop="policyName">
          <el-input v-model="editForm.policyName" />
        </el-form-item>
        <el-form-item label="项目范围" prop="projectScope">
          <el-select v-model="editForm.projectScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.projectScope === 'IDS'" label="项目ID集" prop="projectIdsCsv">
          <el-input v-model="editForm.projectIdsCsv" />
        </el-form-item>
        <el-form-item label="会议范围" prop="meetingScope">
          <el-select v-model="editForm.meetingScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.meetingScope === 'IDS'" label="会议ID集" prop="meetingIdsCsv">
          <el-input v-model="editForm.meetingIdsCsv" />
        </el-form-item>
        <el-form-item label="用户范围" prop="userScope">
          <el-select v-model="editForm.userScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.userScope === 'IDS'" label="用户ID集" prop="userIdsCsv">
          <el-input v-model="editForm.userIdsCsv" />
        </el-form-item>
        <el-form-item label="专家范围" prop="expertScope">
          <el-select v-model="editForm.expertScope">
            <el-option label="全部" value="ALL" />
            <el-option label="指定ID" value="IDS" />
            <el-option label="负责人" value="OWNER" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.expertScope === 'IDS'" label="专家ID集" prop="expertIdsCsv">
          <el-input v-model="editForm.expertIdsCsv" />
        </el-form-item>
        <el-form-item label="允许导出" prop="exportAllowed">
          <el-switch v-model="editForm.exportAllowed" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="assignVisible" title="分配角色" :width="DIALOG_WIDTH.sm">
      <el-radio-group v-model="assignMode" class="mb-sm">
        <el-radio label="APPEND">追加</el-radio>
        <el-radio label="REPLACE">替换</el-radio>
      </el-radio-group>
      <el-select v-model="selectedRoleIds" multiple filterable class="w-full" placeholder="选择角色（可多选）">
        <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id" />
      </el-select>
      <template #footer>
        <el-button @click="assignVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignRoles">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  assignDataPermissionRoles,
  copyDataPermission,
  createDataPermission,
  disableDataPermission,
  enableDataPermission,
  fetchDataPermissionRoles,
  fetchCurrentDataScope,
  fetchDataPermissions,
  fetchRoles,
  updateDataPermission,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.dataPermission.read));
const canManage = computed(() => authStore.hasPermission(PERMS.dataPermission.manage));
const rows = ref<any[]>([]);
const roles = ref<any[]>([]);
const createVisible = ref(false);
const form = ref({
  policyName: "新策略",
  projectScope: "ALL",
  projectIdsCsv: "",
  meetingScope: "ALL",
  meetingIdsCsv: "",
  userScope: "ALL",
  userIdsCsv: "",
  expertScope: "ALL",
  expertIdsCsv: "",
  moduleScope: "ALL",
  exportAllowed: false,
});
const editVisible = ref(false);
const assignVisible = ref(false);
const editId = ref<number | null>(null);
const editForm = ref<any>({});
const selectedPolicyId = ref<number | null>(null);
const selectedRoleIds = ref<number[]>([]);
const assignMode = ref<"APPEND" | "REPLACE">("APPEND");
const currentScope = ref<any>({});

const formRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const formRules = ref<FormRules>({
  policyName: [{ required: true, message: "请输入策略名称", trigger: "blur" }],
});

const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const openCreateDrawer = () => {
  form.value = {
    policyName: "新策略",
    projectScope: "ALL",
    projectIdsCsv: "",
    meetingScope: "ALL",
    meetingIdsCsv: "",
    userScope: "ALL",
    userIdsCsv: "",
    expertScope: "ALL",
    expertIdsCsv: "",
    moduleScope: "ALL",
    exportAllowed: false,
  };
  createVisible.value = true;
};

const load = async () => {
  if (!canRead.value) {
    rows.value = [];
    return;
  }
  const [resp, scopeResp] = await Promise.all([fetchDataPermissions(), fetchCurrentDataScope()]);
  rows.value = resp?.data?.list || [];
  currentScope.value = scopeResp?.data || {};
};

const loadRoles = async () => {
  const roleResp = await fetchRoles();
  roles.value = roleResp?.data?.list || [];
};

const handleCreate = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  await createDataPermission(form.value);
  ElMessage.success("策略创建成功");
  createVisible.value = false;
  await load();
};

const openEdit = (row: any) => {
  editId.value = row.id;
  editForm.value = {
    policyName: row.policyName,
    projectScope: row.projectScope,
    projectIdsCsv: row.projectIdsCsv,
    meetingScope: row.meetingScope,
    meetingIdsCsv: row.meetingIdsCsv,
    userScope: row.userScope || "ALL",
    userIdsCsv: row.userIdsCsv,
    expertScope: row.expertScope || "ALL",
    expertIdsCsv: row.expertIdsCsv,
    moduleScope: row.moduleScope,
    exportAllowed: !!row.exportAllowed,
  };
  editVisible.value = true;
};

const handleSaveEdit = async () => {
  if (!editId.value) return;

  if (!editFormRef.value) return;
  const valid = await editFormRef.value.validate().catch(() => false);
  if (!valid) return;

  await updateDataPermission(editId.value, editForm.value);
  ElMessage.success("策略更新成功");
  editVisible.value = false;
  await load();
};

const openAssignRoles = async (row: any) => {
  selectedPolicyId.value = row.id;
  const resp = await fetchDataPermissionRoles(row.id);
  selectedRoleIds.value = resp?.data || [];
  assignMode.value = "APPEND";
  assignVisible.value = true;
};

const handleAssignRoles = async () => {
  if (!selectedPolicyId.value) {
    return;
  }
  await assignDataPermissionRoles(selectedPolicyId.value, { roleIds: selectedRoleIds.value, assignMode: assignMode.value });
  ElMessage.success("角色分配成功");
  assignVisible.value = false;
};

const handleCopy = async (id: number) => {
  await copyDataPermission(id);
  ElMessage.success("策略复制成功");
  await load();
};

const handleEnable = async (id: number) => {
  await enableDataPermission(id);
  ElMessage.success("策略已启用");
  await load();
};

const handleDisable = async (id: number) => {
  await disableDataPermission(id);
  ElMessage.success("策略已停用");
  await load();
};

onMounted(async () => {
  await Promise.all([load(), loadRoles()]);
});
</script>
