<template>
  <div class="perm-admin-page">
    <!-- 页头 -->
    <div class="page-header">
      <div class="header-left">
        <div class="header-icon">
          <svg viewBox="0 0 24 24" width="28" height="28"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2z" fill="#409eff"/></svg>
        </div>
        <div>
          <h2 class="page-title">管理员权限</h2>
          <p class="page-desc">管理用户和管理员组的路由接口访问权限</p>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd" :icon="Plus">分配权限</el-button>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <div class="filter-left">
        <el-radio-group v-model="queryParams.owner_type" @change="handleOwnerTypeChange" size="default">
          <el-radio-button value="">全部</el-radio-button>
          <el-radio-button value="user">
            <svg viewBox="0 0 24 24" width="14" height="14" style="vertical-align:-2px;margin-right:3px"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/></svg>
            用户
          </el-radio-button>
          <el-radio-button value="group">
            <svg viewBox="0 0 24 24" width="14" height="14" style="vertical-align:-2px;margin-right:3px"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" fill="currentColor"/></svg>
            管理员组
          </el-radio-button>
        </el-radio-group>

        <!-- 用户选择 -->
        <div class="filter-selector" v-if="queryParams.owner_type === 'user'">
          <el-tag v-if="queryParams.user_id" type="primary" closable @close="clearQueryUser" effect="dark" round>
            {{ getQueryUserName() }}
          </el-tag>
          <el-button v-else size="small" @click="openQueryUserSelector" plain>
            <svg viewBox="0 0 24 24" width="14" height="14" style="margin-right:3px"><path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/></svg>
            选择用户
          </el-button>
        </div>
        <!-- 管理员组选择 -->
        <div class="filter-selector" v-if="queryParams.owner_type === 'group'">
          <el-tag v-if="queryParams.admin_group_id" type="success" closable @close="clearQueryGroup" effect="dark" round>
            {{ getQueryGroupName() }}
          </el-tag>
          <el-button v-else size="small" @click="openQueryGroupSelector" plain>
            <svg viewBox="0 0 24 24" width="14" height="14" style="margin-right:3px"><path d="M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3h7zM7 9H4V5h3v4zm10 6h3v4h-3v-4zm0-10v4h3V5h-3z" fill="currentColor"/></svg>
            选择管理员组
          </el-button>
        </div>
      </div>
      <div class="filter-right">
        <el-button @click="handleQuery" type="primary" :loading="loading" :icon="Search">查询</el-button>
        <el-button @click="resetQuery" :icon="Refresh">重置</el-button>
      </div>
    </div>

    <!-- 权限列表 -->
    <div class="table-wrap" v-loading="loading">
      <el-table :data="adminPermissionList" style="width: 100%" stripe border>
        <el-table-column prop="id" label="ID" width="70" align="center" />
        <el-table-column label="拥有者" min-width="200">
          <template #default="{ row }">
            <div class="owner-cell">
              <el-tag :type="row.ownerType === 'user' ? 'primary' : 'success'" size="small" effect="dark" round class="owner-type-tag">
                {{ row.ownerType === 'user' ? '用户' : '组' }}
              </el-tag>
              <span class="owner-name">{{ resolveOwnerName(row) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="权限路径" min-width="260">
          <template #default="{ row }">
            <div class="perm-path-cell" v-if="row.permission">
              <el-tag v-if="row.permission.method" :type="getMethodTag(row.permission.method)" size="small" class="method-tag">{{ row.permission.method }}</el-tag>
              <code class="path-code">{{ row.permission.path || '-' }}</code>
            </div>
            <span v-else class="text-muted">权限ID: {{ row.permissionId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限名称" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.permission?.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="访问级别" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getPermissionTypeTag(row.permissionType)" effect="dark" size="small" round>
              <span class="perm-type-inner">
                <svg v-if="row.permissionType === 4" viewBox="0 0 24 24" width="12" height="12"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/></svg>
                <svg v-else-if="row.permissionType === 3" viewBox="0 0 24 24" width="12" height="12"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>
                <svg v-else-if="row.permissionType === 2" viewBox="0 0 24 24" width="12" height="12"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" fill="currentColor"/></svg>
                <svg v-else-if="row.permissionType === 1" viewBox="0 0 24 24" width="12" height="12"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z" fill="currentColor"/></svg>
                <svg v-else viewBox="0 0 24 24" width="12" height="12"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z" fill="currentColor"/><path d="M7 11h10v2H7z" fill="currentColor"/></svg>
                {{ getPermissionTypeText(row.permissionType) }}
              </span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重" width="80" align="center">
          <template #default="{ row }">
            <span class="weight-badge">{{ row.weight }}</span>
          </template>
        </el-table-column>
        <el-table-column label="过期时间" width="170" align="center">
          <template #default="{ row }">
            <span v-if="isExpired(row.expireAt)" class="expire-expired">
              <svg viewBox="0 0 24 24" width="12" height="12" style="vertical-align:-1px;margin-right:2px"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" fill="#f56c6c"/></svg>
              {{ formatDate(row.expireAt) }}
            </span>
            <span v-else-if="isValidExpire(row.expireAt)" class="expire-normal">{{ formatDate(row.expireAt) }}</span>
            <el-tag v-else size="small" type="info" effect="plain">永不过期</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" link type="primary" @click="handleEdit(row)">
              <svg viewBox="0 0 24 24" width="14" height="14" style="margin-right:2px"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>
              编辑
            </el-button>
            <el-button size="small" link type="danger" @click="handleDelete(row)">
              <svg viewBox="0 0 24 24" width="14" height="14" style="margin-right:2px"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" fill="currentColor"/></svg>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="!loading && adminPermissionList.length === 0 && queryParams.owner_type" description="暂无权限数据" />
      <div v-if="!queryParams.owner_type && adminPermissionList.length === 0 && !loading" class="hint-block">
        <svg viewBox="0 0 24 24" width="40" height="40"><path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" fill="#c0c4cc"/></svg>
        <p>请选择拥有者类型并查询</p>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrap" v-if="total > 0">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          background
          @size-change="s => { queryParams.count = s; fetchAdminPermissionList() }"
          @current-change="p => { queryParams.page = p; fetchAdminPermissionList() }"
        />
      </div>
    </div>

    <!-- 选择器 -->
    <UserListSelector v-model="userSelectorVisible" :current-user-id="selectorTarget === 'query' ? queryParams.user_id : permissionForm.user_id" @confirm="handleUserSelectorConfirm" />
    <UserGroupSelector v-model="groupSelectorVisible" :current-group-id="selectorTarget === 'query' ? queryParams.admin_group_id : permissionForm.admin_group_id" admin-group @confirm="handleGroupSelectorConfirm" />
    <PermissionPathSelector v-model="permissionSelectorVisible" :current-permission-id="permissionForm.permission_id" @confirm="handlePermissionSelectorConfirm" />

    <!-- ==================== 分配 / 编辑权限弹窗 ==================== -->
    <el-dialog v-model="dialogVisible" :title="permissionForm.id ? '编辑权限' : '分配权限'" width="620px" append-to-body destroy-on-close>
      <el-form ref="permissionFormRef" :model="permissionForm" :rules="permissionRules" label-width="100px" label-position="right">
        <!-- 绑定类型 -->
        <el-form-item label="绑定类型" prop="owner_type">
          <el-radio-group v-model="permissionForm.owner_type" :disabled="!!permissionForm.id" @change="handleFormOwnerTypeChange">
            <el-radio value="user" border>
              <span class="radio-with-icon">
                <svg viewBox="0 0 24 24" width="14" height="14"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="#409eff"/></svg>
                用户
              </span>
            </el-radio>
            <el-radio value="group" border>
              <span class="radio-with-icon">
                <svg viewBox="0 0 24 24" width="14" height="14"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" fill="#67c23a"/></svg>
                管理员组
              </span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 用户选择 -->
        <el-form-item label="用户" prop="user_id" v-if="permissionForm.owner_type === 'user'">
          <div class="form-selector-row">
            <el-input :model-value="getFormUserName()" placeholder="点击右侧按钮选择用户" readonly class="selector-input" />
            <el-button @click="openFormUserSelector" :disabled="!!permissionForm.id" :icon="Search">选择</el-button>
            <el-button v-if="permissionForm.user_id && !permissionForm.id" type="danger" link @click="clearFormUser">清除</el-button>
          </div>
        </el-form-item>

        <!-- 管理员组选择 -->
        <el-form-item label="管理员组" prop="admin_group_id" v-if="permissionForm.owner_type === 'group'">
          <div class="form-selector-row">
            <el-input :model-value="getFormGroupName()" placeholder="点击右侧按钮选择管理员组" readonly class="selector-input" />
            <el-button @click="openFormGroupSelector" :disabled="!!permissionForm.id" :icon="Search">选择</el-button>
            <el-button v-if="permissionForm.admin_group_id && !permissionForm.id" type="danger" link @click="clearFormGroup">清除</el-button>
          </div>
        </el-form-item>

        <!-- 路径权限 -->
        <el-form-item label="路径权限" prop="permission_id">
          <div class="form-selector-row">
            <el-input :model-value="getFormPermissionName()" placeholder="点击右侧按钮选择路径权限" readonly class="selector-input" />
            <el-button @click="openPermissionSelector" :icon="Search">选择</el-button>
            <el-button v-if="permissionForm.permission_id" type="danger" link @click="clearFormPermission">清除</el-button>
          </div>
        </el-form-item>

        <!-- 访问级别 -->
        <el-form-item label="访问级别" prop="permission_type">
          <div class="perm-type-cards">
            <div v-for="pt in permTypeOptions" :key="pt.value"
              class="pt-card" :class="{ active: permissionForm.permission_type === pt.value, [`pt-${pt.key}`]: true }"
              @click="permissionForm.permission_type = pt.value"
            >
              <div class="pt-icon" v-html="pt.icon"></div>
              <span class="pt-label">{{ pt.label }}</span>
            </div>
          </div>
        </el-form-item>

        <!-- 权重 -->
        <el-form-item label="权重" prop="weight">
          <el-input-number v-model="permissionForm.weight" :min="0" :max="9999" style="width: 200px" />
          <span class="field-hint">数值越大优先级越高，默认 10</span>
        </el-form-item>

        <!-- 过期时间 -->
        <el-form-item label="过期时间">
          <el-date-picker v-model="permissionForm.expire_at" type="datetime" placeholder="留空表示永不过期" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import UserListSelector from '@/components/admin/UserListSelector.vue'
import UserGroupSelector from '@/components/admin/UserGroupSelector.vue'
import PermissionPathSelector from '@/components/admin/PermissionPathSelector.vue'
import {
  getPermissionListByAdmin,
  addPermissionAdmin,
  updatePermissionAdmin,
  deletePermissionAdmin,
  getPermissionList
} from '@/api/admin/Permission'
import { getUserList } from '@/api/admin/user'
import { getAdminGroupList } from '@/api/admin/group'
import { formatDate, timeToTimestamp } from '@/utils/tool'

// ==================== 权限类型选项 ====================
const permTypeOptions = [
  { value: 0, key: 'none', label: '无权限', icon: '<svg viewBox="0 0 24 24" width="20" height="20"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z" fill="currentColor"/><path d="M7 11h10v2H7z" fill="currentColor"/></svg>' },
  { value: 1, key: 'prohibit', label: '禁止', icon: '<svg viewBox="0 0 24 24" width="20" height="20"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z" fill="currentColor"/></svg>' },
  { value: 2, key: 'read', label: '读取', icon: '<svg viewBox="0 0 24 24" width="20" height="20"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" fill="currentColor"/></svg>' },
  { value: 3, key: 'write', label: '写入', icon: '<svg viewBox="0 0 24 24" width="20" height="20"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/></svg>' },
  { value: 4, key: 'all', label: '全部', icon: '<svg viewBox="0 0 24 24" width="20" height="20"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/></svg>' }
]

// ==================== 缓存数据 ====================
const UserOptions = ref([])
const GroupOptions = ref([])
const adminGroupOptions = ref([])
const permissionOptions = ref([])

// ==================== 筛选查询 ====================
const loading = ref(false)
const adminPermissionList = ref([])
const total = ref(0)
const queryParams = reactive({ owner_type: '', user_id: undefined, admin_group_id: undefined, page: 1, count: 20 })

const selectorTarget = ref('query')
const userSelectorVisible = ref(false)
const groupSelectorVisible = ref(false)
const permissionSelectorVisible = ref(false)

const clearQueryUser = () => { queryParams.user_id = undefined }
const clearQueryGroup = () => { queryParams.admin_group_id = undefined }

const getQueryUserName = () => {
  const u = UserOptions.value.find(u => u.UserId === queryParams.user_id)
  return u ? `${u.UserName} (ID: ${u.UserId})` : `用户 #${queryParams.user_id}`
}
const getQueryGroupName = () => {
  const g = GroupOptions.value.find(g => g.id === queryParams.admin_group_id) || adminGroupOptions.value.find(g => g.id === queryParams.admin_group_id)
  return g ? `${g.name} (ID: ${g.id})` : `组 #${queryParams.admin_group_id}`
}

const openQueryUserSelector = () => { selectorTarget.value = 'query'; userSelectorVisible.value = true }
const openQueryGroupSelector = () => { selectorTarget.value = 'query'; groupSelectorVisible.value = true }

const handleOwnerTypeChange = () => {
  queryParams.user_id = undefined
  queryParams.admin_group_id = undefined
  adminPermissionList.value = []
  total.value = 0
}

const handleQuery = () => {
  if (!queryParams.owner_type) {
    ElMessage.warning('请先选择拥有者类型')
    return
  }
  queryParams.page = 1
  fetchAdminPermissionList()
}

const resetQuery = () => {
  queryParams.owner_type = ''
  queryParams.user_id = undefined
  queryParams.admin_group_id = undefined
  queryParams.page = 1
  adminPermissionList.value = []
  total.value = 0
}

const fetchAdminPermissionList = async () => {
  if (!queryParams.owner_type) return
  loading.value = true
  try {
    const params = { ...queryParams }
    Object.keys(params).forEach(k => { if (params[k] === '' || params[k] == null) delete params[k] })
    const res = await getPermissionListByAdmin(params)
    if (res.data.code === 200) {
      adminPermissionList.value = res.data.data || []
      total.value = res.data.data?.length || 0
    } else {
      ElMessage.error(res.data.message || '获取权限列表失败')
    }
  } catch {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// ==================== 拥有者名称解析 ====================
const resolveOwnerName = (row) => {
  if (row.ownerType === 'user') {
    const u = UserOptions.value.find(u => u.UserId === row.userId)
    return u ? u.UserName : `用户 #${row.userId}`
  }
  const g = GroupOptions.value.find(g => g.id === row.groupId) || adminGroupOptions.value.find(g => g.id === row.groupId)
  return g ? g.name : `管理员组 #${row.groupId}`
}

// ==================== 表单 ====================
const dialogVisible = ref(false)
const submitting = ref(false)
const permissionFormRef = ref(null)
const selectedPermission = ref(null)

const permissionForm = reactive({
  id: undefined, user_id: undefined, admin_group_id: undefined,
  owner_type: '', permission_id: undefined, weight: 10, permission_type: 4, expire_at: ''
})

const permissionRules = {
  owner_type: [{ required: true, message: '请选择绑定类型', trigger: 'change' }],
  permission_id: [{ required: true, message: '请选择路径权限', trigger: 'change' }],
  permission_type: [{ required: true, message: '请选择访问级别', trigger: 'change' }]
}

const handleFormOwnerTypeChange = () => {
  if (permissionForm.owner_type === 'user') permissionForm.admin_group_id = undefined
  else if (permissionForm.owner_type === 'group') permissionForm.user_id = undefined
}

const clearFormUser = () => { permissionForm.user_id = undefined }
const clearFormGroup = () => { permissionForm.admin_group_id = undefined }
const clearFormPermission = () => { permissionForm.permission_id = undefined; selectedPermission.value = null }

const getFormUserName = () => {
  if (!permissionForm.user_id) return ''
  const u = UserOptions.value.find(u => u.UserId === permissionForm.user_id)
  return u ? `${u.UserName} (ID: ${u.UserId})` : `用户 #${permissionForm.user_id}`
}
const getFormGroupName = () => {
  if (!permissionForm.admin_group_id) return ''
  const g = GroupOptions.value.find(g => g.id === permissionForm.admin_group_id)
  return g ? `${g.name} (ID: ${g.id})` : `管理员组 #${permissionForm.admin_group_id}`
}
const getFormPermissionName = () => {
  if (!permissionForm.permission_id) return ''
  if (selectedPermission.value?.id === permissionForm.permission_id) {
    const p = selectedPermission.value
    return `${p.method || ''} ${p.path}${p.name ? ' - ' + p.name : ''}`
  }
  const p = permissionOptions.value.find(p => p.id === permissionForm.permission_id)
  return p ? `${p.method || ''} ${p.path}${p.name ? ' - ' + p.name : ''}` : `权限 #${permissionForm.permission_id}`
}

const openFormUserSelector = () => { selectorTarget.value = 'form'; userSelectorVisible.value = true }
const openFormGroupSelector = () => { selectorTarget.value = 'form'; groupSelectorVisible.value = true }
const openPermissionSelector = () => { permissionSelectorVisible.value = true }

const handleAdd = () => {
  const preOwnerType = queryParams.owner_type || ''
  const preUserId = preOwnerType === 'user' ? queryParams.user_id : undefined
  const preGroupId = preOwnerType === 'group' ? queryParams.admin_group_id : undefined
  Object.assign(permissionForm, { id: undefined, user_id: preUserId, admin_group_id: preGroupId, owner_type: preOwnerType, permission_id: undefined, weight: 10, permission_type: 4, expire_at: '' })
  selectedPermission.value = null
  permissionFormRef.value?.resetFields()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  let expireTime = ''
  if (row.expireAt && row.expireAt !== '0001-01-01T00:00:00Z') {
    const d = new Date(row.expireAt)
    if (!isNaN(d.getTime())) expireTime = d.toISOString().slice(0, 19).replace('T', ' ')
  }
  Object.assign(permissionForm, {
    id: row.id, user_id: row.userId, admin_group_id: row.groupId,
    owner_type: row.ownerType, permission_id: row.permissionId,
    weight: row.weight, permission_type: row.permissionType, expire_at: expireTime
  })
  if (row.permission) selectedPermission.value = row.permission
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该条权限记录？删除后不可恢复。', '确认删除', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' })
    .then(async () => {
      try {
        const res = await deletePermissionAdmin({ id: row.id })
        if (res.data.code === 200) { ElMessage.success('删除成功'); fetchAdminPermissionList() }
      } catch { ElMessage.error('删除失败') }
    }).catch(() => {})
}

const submitForm = () => {
  permissionFormRef.value?.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      const data = {
        owner_type: permissionForm.owner_type,
        permission_id: Number(permissionForm.permission_id),
        weight: Number(permissionForm.weight),
        permission_type: Number(permissionForm.permission_type)
      }
      if (permissionForm.owner_type === 'user') data.user_id = Number(permissionForm.user_id)
      else if (permissionForm.owner_type === 'group') data.admin_group_id = Number(permissionForm.admin_group_id)
      if (permissionForm.expire_at) data.expire_at = timeToTimestamp(permissionForm.expire_at)
      if (permissionForm.id) data.id = permissionForm.id

      const res = permissionForm.id ? await updatePermissionAdmin(data) : await addPermissionAdmin(data)
      if (res.data.code === 200) {
        ElMessage.success(permissionForm.id ? '修改成功' : '分配成功')
        dialogVisible.value = false
        fetchAdminPermissionList()
      } else {
        ElMessage.error(res.data.message || '操作失败')
      }
    } catch (e) {
      ElMessage.error(e.response?.data?.message || '操作失败')
    } finally {
      submitting.value = false
    }
  })
}

// ==================== 选择器回调 ====================
const handleUserSelectorConfirm = (user) => {
  if (!user) return
  const userId = user.user_id || user.UserId
  const userName = user.user_name || user.UserName
  if (!UserOptions.value.find(u => u.UserId === userId)) UserOptions.value.push({ UserId: userId, UserName: userName })

  if (selectorTarget.value === 'query') { queryParams.user_id = userId; fetchAdminPermissionList() }
  else { permissionForm.user_id = userId }
  userSelectorVisible.value = false
}

const handleGroupSelectorConfirm = (group) => {
  if (!group) return
  const gId = group.id || group.Id
  const gName = group.name || group.Name
  if (!GroupOptions.value.find(g => g.id === gId)) GroupOptions.value.push({ id: gId, name: gName })

  if (selectorTarget.value === 'query') { queryParams.admin_group_id = gId; fetchAdminPermissionList() }
  else { permissionForm.admin_group_id = gId }
  groupSelectorVisible.value = false
}

const handlePermissionSelectorConfirm = (perm) => {
  if (perm) { permissionForm.permission_id = perm.id; selectedPermission.value = perm }
  permissionSelectorVisible.value = false
}

// ==================== 工具函数 ====================
const getMethodTag = (m) => ({ GET: 'success', POST: 'primary', PUT: 'warning', DELETE: 'danger', PATCH: 'info' }[m?.toUpperCase()] || 'info')
const getPermissionTypeTag = (t) => ({ 0: 'info', 1: 'danger', 2: 'warning', 3: 'primary', 4: 'success' }[t] || 'info')
const getPermissionTypeText = (t) => ({ 0: '无权限', 1: '禁止', 2: '读取', 3: '写入', 4: '全部' }[t] || '未知')

const isValidExpire = (t) => t && t !== '0001-01-01T00:00:00Z' && !isNaN(new Date(t).getTime())
const isExpired = (t) => isValidExpire(t) && new Date(t).getTime() < Date.now()

// ==================== 初始化 ====================
onMounted(() => {
  getUserList({ page: 1, count: 50 }).then(r => { if (r.data.code === 200) UserOptions.value = r.data.data?.data || [] }).catch(() => {})
  getAdminGroupList({ page: 1, count: 50 }).then(r => { if (r.data.code === 200) adminGroupOptions.value = r.data.data?.data || [] }).catch(() => {})
  getPermissionList({ page: 1, count: 999 }).then(r => { if (r.data.code === 200) permissionOptions.value = r.data.data?.list || [] }).catch(() => {})
})
</script>

<style scoped>
.perm-admin-page { padding: 20px 24px; }

/* 页头 */
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
.header-left { display: flex; align-items: center; gap: 14px; }
.header-icon { width: 48px; height: 48px; border-radius: 12px; background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.page-title { margin: 0 0 2px; font-size: 20px; font-weight: 700; color: #1d2129; }
.page-desc { margin: 0; font-size: 13px; color: #86909c; }

/* 筛选栏 */
.filter-bar { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 16px; padding: 14px 18px; background: #f7f8fa; border-radius: 10px; border: 1px solid #ebeef5; }
.filter-left { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.filter-right { display: flex; gap: 8px; }
.filter-selector { display: flex; align-items: center; gap: 6px; }

/* 表格 */
.table-wrap { background: #fff; border: 1px solid #ebeef5; border-radius: 10px; padding: 0; overflow: hidden; }
.owner-cell { display: flex; align-items: center; gap: 8px; }
.owner-type-tag { flex-shrink: 0; }
.owner-name { font-weight: 500; color: #1d2129; }
.perm-path-cell { display: flex; align-items: center; gap: 6px; }
.method-tag { flex-shrink: 0; font-weight: 600; font-size: 11px; }
.path-code { font-size: 12px; font-family: 'Consolas','Monaco',monospace; color: #606266; background: #f0f2f5; padding: 2px 8px; border-radius: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.perm-type-inner { display: inline-flex; align-items: center; gap: 3px; }
.weight-badge { display: inline-block; min-width: 28px; text-align: center; padding: 2px 8px; background: #f0f2f5; border-radius: 10px; font-size: 12px; font-weight: 600; color: #606266; }
.text-muted { color: #a8abb2; font-size: 12px; }
.expire-expired { color: #f56c6c; font-weight: 500; font-size: 13px; }
.expire-normal { color: #606266; font-size: 13px; }

.hint-block { display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 60px 0; color: #c0c4cc; }
.hint-block p { margin: 0; font-size: 14px; }

.pagination-wrap { padding: 14px 18px; display: flex; justify-content: flex-end; border-top: 1px solid #f0f2f5; }

/* 弹窗表单 */
.form-selector-row { display: flex; align-items: center; gap: 8px; width: 100%; }
.selector-input { flex: 1; }
.radio-with-icon { display: inline-flex; align-items: center; gap: 4px; }
.field-hint { margin-left: 12px; font-size: 12px; color: #a8abb2; }

/* 权限类型卡片 */
.perm-type-cards { display: flex; gap: 8px; flex-wrap: wrap; }
.pt-card { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 12px 16px; border: 2px solid #ebeef5; border-radius: 8px; cursor: pointer; transition: all .2s; min-width: 70px; background: #fff; }
.pt-card:hover { border-color: #c0c4cc; background: #fafafa; }
.pt-card.active { border-color: var(--pt-color, #409eff); background: var(--pt-bg, #ecf5ff); }
.pt-icon { width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; color: #909399; }
.pt-card.active .pt-icon { color: var(--pt-color, #409eff); }
.pt-label { font-size: 12px; font-weight: 500; color: #606266; }
.pt-card.active .pt-label { color: var(--pt-color, #409eff); font-weight: 600; }

.pt-none { --pt-color: #909399; --pt-bg: #f4f4f5; }
.pt-prohibit { --pt-color: #f56c6c; --pt-bg: #fef0f0; }
.pt-read { --pt-color: #e6a23c; --pt-bg: #fdf6ec; }
.pt-write { --pt-color: #409eff; --pt-bg: #ecf5ff; }
.pt-all { --pt-color: #67c23a; --pt-bg: #f0f9eb; }
</style>
