<template>
  <section class="space-y-6">
    <header class="space-y-2">
      <h1 class="mos-title text-2xl font-semibold">审批中心</h1>
      <p class="mos-muted text-sm">处理角色变更与邀请审批。</p>
    </header>

    <!-- Tab切换 -->
    <div class="flex gap-2 border-b border-mosquito-line pb-2">
      <button
        v-for="tab in tabs"
        :key="tab.key"
        class="px-4 py-2 text-sm font-medium transition-colors"
        :class="activeTab === tab.key ? 'text-mosquito-brand border-b-2 border-mosquito-brand' : 'text-mosquito-ink/70 hover:text-mosquito-ink'"
        @click="switchTab(tab.key)"
      >
        {{ tab.label }}
      </button>
    </div>

    <!-- 待审批 -->
    <ListSection v-if="activeTab === 'pending'" :page="requestPage" :total-pages="requestTotalPages" @prev="requestPage--" @next="requestPage++">
      <template #title>待审批申请</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-44" v-model="requestQuery" placeholder="搜索用户" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="requestStart" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="requestEnd" />
        <input class="mos-input !py-1 !px-2 !text-xs w-48" v-model="batchRejectReason" placeholder="批量拒绝原因" />
      </template>
      <template #actions>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAllRequests">
          {{ allRequestsSelected ? '取消全选' : '全选' }}
        </button>
        <PermissionButton permission="approval.index.batch.handle.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchApprove">
          批量通过
        </PermissionButton>
        <PermissionButton permission="approval.index.batch.handle.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchReject">
          批量拒绝
        </PermissionButton>
      </template>
      <template #default>
        <div v-if="pagedRequests.length" class="space-y-3">
          <div v-for="request in pagedRequests" :key="request.id" class="rounded-xl border border-mosquito-line px-4 py-3">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-3">
                <input
                  type="checkbox"
                  class="h-4 w-4"
                  :checked="selectedRequestIds.includes(request.id)"
                  @click.stop
                  @change.stop="toggleRequestSelect(request.id)"
                />
                <div>
                  <div class="flex items-center gap-2">
                    <span class="text-sm font-semibold text-mosquito-ink">{{ request.title || '审批申请' }}</span>
                    <span
                      class="rounded-full px-2 py-0.5 text-[10px] font-semibold"
                      :class="getBizTypeClass(request.bizType || 'ROLE_CHANGE')"
                    >
                      {{ getBizTypeLabel(request.bizType || 'ROLE_CHANGE') }}
                    </span>
                  </div>
                  <div class="mos-muted text-xs">{{ request.description }}</div>
                  <div class="mos-muted text-xs">申请人：{{ getUserName(request.userId) }}</div>
                  <div v-if="request.reason" class="mos-muted text-xs">原因：{{ request.reason }}</div>
                </div>
              </div>
              <div class="flex items-center gap-2">
                <span
                  class="rounded-full px-2 py-1 text-[10px] font-semibold"
                  :class="slaClass(getSlaBadge(request.requestedAt).level)"
                >
                  {{ getSlaBadge(request.requestedAt).label }}
                </span>
                <PermissionButton permission="approval.execute.reject.ALL" variant="secondary" :hide-when-no-permission="true" @click="setRejecting(request.id)">
                  拒绝
                </PermissionButton>
                <PermissionButton permission="approval.execute.transfer.ALL" variant="secondary" :hide-when-no-permission="true" @click="showTransfer(request.id)">
                  转交
                </PermissionButton>
                <PermissionButton permission="approval.index.delegate.ALL" variant="secondary" :hide-when-no-permission="true" @click="showDelegate(request.id)">
                  委托
                </PermissionButton>
                <PermissionButton permission="approval.execute.approve.ALL" variant="primary" :hide-when-no-permission="true" @click="approve(request)">
                  通过
                </PermissionButton>
              </div>
            </div>
            <div v-if="rejectingId === request.id" class="mt-3 flex flex-wrap items-center gap-2">
              <input class="mos-input !py-1 !px-2 !text-xs flex-1" v-model="rejectReason" placeholder="请输入拒绝原因" />
              <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="cancelReject">取消</button>
              <button class="mos-btn mos-btn-accent !py-1 !px-2 !text-xs" @click="confirmReject(request)">确认拒绝</button>
            </div>
          </div>
        </div>
      </template>
      <template #empty>
        <div v-if="!pagedRequests.length" class="mt-4 text-sm text-mosquito-ink/60">暂无待审批申请</div>
      </template>
    </ListSection>

    <ListSection :page="invitePage" :total-pages="inviteTotalPages" @prev="invitePage--" @next="invitePage++">
      <template #title>邀请申请</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-44" v-model="inviteQuery" placeholder="搜索邮箱" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="inviteStart" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="inviteEnd" />
      </template>
      <template #actions>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAllInvites">
          {{ allInvitesSelected ? '取消全选' : '全选' }}
        </button>
        <PermissionButton permission="approval.index.batch.handle.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchAcceptInvites">
          批量通过
        </PermissionButton>
        <PermissionButton permission="approval.index.batch.handle.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchRejectInvites">
          批量拒绝
        </PermissionButton>
      </template>
      <template #default>
        <div v-if="pagedInvites.length" class="space-y-3">
          <div v-for="invite in pagedInvites" :key="invite.id" class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3">
            <div class="flex items-center gap-3">
              <input
                type="checkbox"
                class="h-4 w-4"
                :checked="selectedInviteIds.includes(invite.id)"
                @click.stop
                @change.stop="toggleInviteSelect(invite.id)"
              />
              <div>
                <div class="text-sm font-semibold text-mosquito-ink">{{ invite.email }}</div>
                <div class="mos-muted text-xs">角色：{{ roleLabel(invite.role) }}</div>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <PermissionButton permission="approval.execute.reject.ALL" variant="secondary" :hide-when-no-permission="true" @click="rejectInvite(invite)">
                拒绝
              </PermissionButton>
              <PermissionButton permission="approval.execute.approve.ALL" variant="primary" :hide-when-no-permission="true" @click="acceptInvite(invite)">
                通过
              </PermissionButton>
            </div>
          </div>
        </div>
      </template>
      <template #empty>
        <div v-if="!pagedInvites.length" class="mt-4 text-sm text-mosquito-ink/60">暂无待审批邀请</div>
      </template>
    </ListSection>

    <!-- 已审批 -->
    <ListSection v-if="activeTab === 'processed'" :page="processedPage" :total-pages="processedTotalPages" @prev="processedPage--" @next="processedPage++">
      <template #title>已审批记录</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-44" v-model="processedQuery" placeholder="搜索用户" />
      </template>
      <template #default>
        <div v-if="pagedProcessed.length" class="space-y-3">
          <div v-for="record in pagedProcessed" :key="record.id" class="rounded-xl border border-mosquito-line px-4 py-3">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm font-semibold text-mosquito-ink">{{ getUserName(record.userId) }}</div>
                <div class="mos-muted text-xs">审批结果：{{ record.result === 'APPROVE' ? '通过' : '拒绝' }}</div>
                <div class="mos-muted text-xs">审批意见：{{ record.comment || '无' }}</div>
                <div class="mos-muted text-xs">审批时间：{{ record.approvedAt }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #empty>
        <div v-if="!pagedProcessed.length" class="mt-4 text-sm text-mosquito-ink/60">暂无已审批记录</div>
      </template>
    </ListSection>

    <!-- 我提交的 -->
    <ListSection v-if="activeTab === 'my'" :page="myPage" :total-pages="myTotalPages" @prev="myPage--" @next="myPage++">
      <template #title>我提交的审批</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-44" v-model="myQuery" placeholder="搜索" />
      </template>
      <template #default>
        <div v-if="pagedMy.length" class="space-y-3">
          <div v-for="record in pagedMy" :key="record.id" class="rounded-xl border border-mosquito-line px-4 py-3">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm font-semibold text-mosquito-ink">{{ record.type }}</div>
                <div class="mos-muted text-xs">状态：{{ record.status }}</div>
                <div class="mos-muted text-xs">提交时间：{{ record.submittedAt }}</div>
              </div>
              <span
                class="rounded-full px-2 py-1 text-[10px] font-semibold"
                :class="record.status === '已通过' ? 'bg-green-100 text-green-600' : record.status === '已拒绝' ? 'bg-red-100 text-red-600' : 'bg-yellow-100 text-yellow-600'"
              >
                {{ record.status }}
              </span>
            </div>
          </div>
        </div>
      </template>
      <template #empty>
        <div v-if="!pagedMy.length" class="mt-4 text-sm text-mosquito-ink/60">暂无我提交的记录</div>
      </template>
    </ListSection>

    <!-- 转交弹窗 -->
    <div v-if="showTransferModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div class="w-96 rounded-xl bg-white p-6 shadow-xl">
        <h3 class="mb-4 text-lg font-semibold">转交审批</h3>
        <div class="space-y-4">
          <div>
            <label class="mb-1 block text-sm text-gray-600">目标用户ID</label>
            <input
              class="mos-input w-full"
              v-model="transferTargetId"
              placeholder="请输入目标用户ID"
            />
          </div>
          <div>
            <label class="mb-1 block text-sm text-gray-600">转交原因（可选）</label>
            <input
              class="mos-input w-full"
              v-model="transferComment"
              placeholder="请输入转交原因"
            />
          </div>
        </div>
        <div class="mt-6 flex justify-end gap-3">
          <button class="mos-btn mos-btn-secondary" @click="showTransferModal = false">取消</button>
          <button class="mos-btn mos-btn-primary" @click="confirmTransfer">确认转交</button>
        </div>
      </div>
    </div>

    <!-- 委托弹窗 -->
    <div v-if="showDelegateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div class="w-96 rounded-xl bg-white p-6 shadow-xl">
        <h3 class="mb-4 text-lg font-semibold">委托审批</h3>
        <div class="space-y-4">
          <div>
            <label class="mb-1 block text-sm text-gray-600">目标用户ID</label>
            <input
              class="mos-input w-full"
              v-model="delegateTargetId"
              placeholder="请输入目标用户ID"
            />
          </div>
          <div>
            <label class="mb-1 block text-sm text-gray-600">委托原因（可选）</label>
            <input
              class="mos-input w-full"
              v-model="delegateReason"
              placeholder="请输入委托原因"
            />
          </div>
        </div>
        <div class="mt-6 flex justify-end gap-3">
          <button class="mos-btn mos-btn-secondary" @click="showDelegateModal = false">取消</button>
          <button class="mos-btn mos-btn-primary" @click="confirmDelegate">确认委托</button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useUserStore, type RoleChangeRequest, type InviteRequest } from '../stores/users'
import { useDataService } from '../services'
import { useAuditStore } from '../stores/audit'
import { useAuthStore } from '../stores/auth'
import ListSection from '../components/ListSection.vue'
import PermissionButton from '../components/PermissionButton.vue'
import { getSlaBadge, normalizeRejectReason } from '../utils/approval'
import { RoleLabels, type AdminRole } from '../auth/roles'

// 审批状态映射（与 ApiDataService.ts 保持一致）
const mapApprovalStatus = (status: string): '待审批' | '已通过' | '已拒绝' => {
  switch (status) {
    case 'PENDING':
    case 'PROCESSING':
      return '待审批'
    case 'APPROVED':
    case 'COMPLETED':
      return '已通过'
    case 'REJECTED':
    case 'CANCELLED':
      return '已拒绝'
    default:
      return '待审批'
  }
}

// Tab配置
const tabs = [
  { key: 'pending', label: '待审批' },
  { key: 'processed', label: '已审批' },
  { key: 'my', label: '我提交' }
]
const activeTab = ref('pending')

// 转交弹窗
const showTransferModal = ref(false)
const transferTargetId = ref('')
const transferComment = ref('')
const transferringRequestId = ref<string | null>(null)

// 委托弹窗
const showDelegateModal = ref(false)
const delegateTargetId = ref('')
const delegateReason = ref('')
const delegatingRequestId = ref<string | null>(null)

const store = useUserStore()
const service = useDataService()
const auditStore = useAuditStore()
const authStore = useAuthStore()
const rejectingId = ref<string | null>(null)
const rejectReason = ref('')
const batchRejectReason = ref('')
const requestQuery = ref('')
const inviteQuery = ref('')
const requestStart = ref('')
const requestEnd = ref('')
const inviteStart = ref('')
const inviteEnd = ref('')
const requestPage = ref(0)
const invitePage = ref(0)

// 已审批相关
const processedPage = ref(0)
const processedQuery = ref('')
const processedRecords = ref<any[]>([])
const processedTotal = ref(0)

// 我提交的相关
const myPage = ref(0)
const myQuery = ref('')
const myRecords = ref<any[]>([])
const myTotal = ref(0)

const switchTab = async (tab: string) => {
  activeTab.value = tab
  if (tab === 'processed') {
    // 加载已审批记录
    try {
      if (authStore.mode === 'real') {
        const result = await service.getProcessedApprovals({ page: processedPage.value, size: 6, keyword: processedQuery.value })
        processedRecords.value = (result.items || []).map((record: any) => ({
          id: String(record.id),
          userId: String(record.applicantId || ''),
          type: record.flowName || record.type || '角色变更',
          result: record.status === 'APPROVED' ? 'APPROVE' : 'REJECT',
          comment: record.comment || '',
          approvedAt: record.updatedAt || record.approvedAt || ''
        }))
        // 使用后端返回的总数
        processedTotal.value = typeof result.total === 'number' ? result.total
          : processedRecords.value.length
      } else {
        // 演示模式
        processedRecords.value = []
        processedTotal.value = 0
      }
    } catch (e) {
      console.error('Failed to load processed records:', e)
      service.addNotification({
        title: '加载失败',
        content: '获取已审批记录失败'
      })
    }
  } else if (tab === 'my') {
    // 加载我提交的记录
    try {
      if (authStore.mode === 'real') {
        const result = await service.getMyApprovals({ page: myPage.value, size: 6, keyword: myQuery.value })
        myRecords.value = (result.items || []).map((record: any) => ({
          id: String(record.id),
          type: record.flowName || record.type || '角色变更',
          status: mapApprovalStatus(record.status),
          submittedAt: record.createdAt || ''
        }))
        // 使用后端返回的总数
        myTotal.value = typeof result.total === 'number' ? result.total
          : myRecords.value.length
      } else {
        // 演示模式
        myRecords.value = []
        myTotal.value = 0
      }
    } catch (e) {
      console.error('Failed to load my records:', e)
      service.addNotification({
        title: '加载失败',
        content: '获取我提交的审批失败'
      })
    }
  }
}

const processedTotalPages = computed(() => Math.max(1, Math.ceil(processedTotal.value / 6)))
const myTotalPages = computed(() => Math.max(1, Math.ceil(myTotal.value / 6)))

// 后端已返回当前页数据，直接使用
const pagedProcessed = computed(() => processedRecords.value)
const pagedMy = computed(() => myRecords.value)

// 加载已审批记录
const loadProcessedRecords = async () => {
  try {
    if (authStore.mode === 'real') {
      const result = await service.getProcessedApprovals({ page: processedPage.value, size: 6, keyword: processedQuery.value })
      processedRecords.value = (result.items || []).map((record: any) => ({
        id: String(record.id),
        userId: String(record.applicantId || ''),
        type: record.flowName || record.type || '角色变更',
        result: record.status === 'APPROVED' ? 'APPROVE' : 'REJECT',
        comment: record.comment || '',
        approvedAt: record.updatedAt || record.approvedAt || ''
      }))
      processedTotal.value = typeof result.total === 'number' ? result.total : processedRecords.value.length
    } else {
      processedRecords.value = []
      processedTotal.value = 0
    }
  } catch (e) {
    console.error('Failed to load processed records:', e)
  }
}

// 加载我提交的记录
const loadMyRecords = async () => {
  try {
    if (authStore.mode === 'real') {
      const result = await service.getMyApprovals({ page: myPage.value, size: 6, keyword: myQuery.value })
      myRecords.value = (result.items || []).map((record: any) => ({
        id: String(record.id),
        type: record.flowName || record.type || '角色变更',
        status: mapApprovalStatus(record.status),
        submittedAt: record.createdAt || ''
      }))
      myTotal.value = typeof result.total === 'number' ? result.total : myRecords.value.length
    } else {
      myRecords.value = []
      myTotal.value = 0
    }
  } catch (e) {
    console.error('Failed to load my records:', e)
  }
}

// 监听已审批页码变化
watch(processedPage, () => {
  if (activeTab.value === 'processed') {
    loadProcessedRecords()
  }
})

// 监听已审批筛选变化
watch(processedQuery, () => {
  if (processedPage.value !== 0) {
    processedPage.value = 0
  } else {
    loadProcessedRecords()
  }
})

// 监听我提交页码变化
watch(myPage, () => {
  if (activeTab.value === 'my') {
    loadMyRecords()
  }
})

// 监听我提交筛选变化
watch(myQuery, () => {
  if (myPage.value !== 0) {
    myPage.value = 0
  } else {
    loadMyRecords()
  }
})

// 转交功能
const showTransfer = (requestId: string) => {
  transferringRequestId.value = requestId
  transferTargetId.value = ''
  showTransferModal.value = true
}

const confirmTransfer = async () => {
  if (!transferringRequestId.value || !transferTargetId.value) return

  try {
    // 调用后端转交API
    await service.transferApproval(transferringRequestId.value, transferTargetId.value, transferComment.value)
    auditStore.addLog('转交审批', `转交给用户: ${transferTargetId.value}`)
    service.addNotification({
      title: '转交成功',
      content: '审批已转交'
    })
    // 关闭弹窗
    showTransferModal.value = false
  } catch (error) {
    service.addNotification({
      title: '转交失败',
      content: error instanceof Error ? error.message : '转交失败'
    })
  }
  showTransferModal.value = false
}

// 委托功能
const showDelegate = (requestId: string) => {
  delegatingRequestId.value = requestId
  delegateTargetId.value = ''
  showDelegateModal.value = true
}

const confirmDelegate = async () => {
  if (!delegatingRequestId.value || !delegateTargetId.value) return

  try {
    // 调用后端委托API
    await service.delegateApproval(delegatingRequestId.value, delegateTargetId.value, delegateReason.value)
    auditStore.addLog('委托审批', `委托给用户: ${delegateTargetId.value}`)
    service.addNotification({
      title: '委托成功',
      content: '审批已委托'
    })
    // 关闭弹窗
    showDelegateModal.value = false
  } catch (error) {
    service.addNotification({
      title: '委托失败',
      content: error instanceof Error ? error.message : '委托失败'
    })
  }
  showDelegateModal.value = false
}

const pageSize = 6
const selectedRequestIds = ref<string[]>([])
const selectedInviteIds = ref<string[]>([])

onMounted(async () => {
  const [users, invites, requests] = await Promise.all([
    service.getUsers(),
    service.getInvites(),
    service.getRoleRequests()
  ])
  store.init(users, invites, requests)
})

const pendingRequests = computed(() => store.pendingRoleRequests)
const pendingInvites = computed(() => store.invites.filter((item) => item.status === '待接受'))

const roleLabel = (role: string) => {
  // 使用15角色体系的显示名称
  return RoleLabels[role as AdminRole] || role
}

const getUserName = (id: string) => store.byId(id)?.name ?? id

// 根据业务类型获取标签文字
const getBizTypeLabel = (bizType: string) => {
  const labels: Record<string, string> = {
    ROLE_CHANGE: '角色变更',
    SENSITIVE_EXPORT: '敏感导出',
    USER_FREEZE: '用户冻结',
    USER_UNFREEZE: '用户解冻',
    SYSTEM_CONFIG: '系统配置',
    ACTIVITY_CREATE: '活动创建',
    ACTIVITY_UPDATE: '活动更新',
    ACTIVITY_DELETE: '活动删除',
    REWARD_GRANT: '奖励发放'
  }
  return labels[bizType] || bizType
}

// 根据业务类型获取样式类
const getBizTypeClass = (bizType: string) => {
  const classes: Record<string, string> = {
    ROLE_CHANGE: 'bg-blue-100 text-blue-600',
    SENSITIVE_EXPORT: 'bg-purple-100 text-purple-600',
    USER_FREEZE: 'bg-red-100 text-red-600',
    USER_UNFREEZE: 'bg-green-100 text-green-600',
    SYSTEM_CONFIG: 'bg-yellow-100 text-yellow-600',
    ACTIVITY_CREATE: 'bg-emerald-100 text-emerald-600',
    ACTIVITY_UPDATE: 'bg-orange-100 text-orange-600',
    ACTIVITY_DELETE: 'bg-rose-100 text-rose-600',
    REWARD_GRANT: 'bg-cyan-100 text-cyan-600'
  }
  return classes[bizType] || 'bg-gray-100 text-gray-600'
}

const slaClass = (level: ReturnType<typeof getSlaBadge>['level']) => {
  if (level === 'danger') return 'bg-rose-100 text-rose-600'
  if (level === 'warning') return 'bg-amber-100 text-amber-600'
  return 'bg-mosquito-accent/10 text-mosquito-brand'
}

const approve = async (request: RoleChangeRequest) => {
  // 真实模式下调用后端API，演示模式下使用本地store
  if (authStore.mode === 'real') {
    try {
      await service.handleApproval(request.id, 'APPROVE', '审批通过')
      // 刷新数据
      const requests = await service.getRoleRequests()
      if (requests) {
        store.setRoleRequests(requests)
      }
      auditStore.addLog('审批通过角色变更', getUserName(request.userId))
      service.addNotification({
        title: '角色变更审批通过',
        content: `${getUserName(request.userId)} 角色变更已通过`
      })
    } catch (error) {
      service.addNotification({
        title: '审批失败',
        content: error instanceof Error ? error.message : '审批处理失败'
      })
    }
  } else {
    store.approveRoleChange(request.id, '演示管理员')
    auditStore.addLog('审批通过角色变更', getUserName(request.userId))
    service.addNotification({
      title: '角色变更审批通过',
      content: `${getUserName(request.userId)} 角色变更已通过`
    })
  }
}

const setRejecting = (id: string) => {
  rejectingId.value = id
  rejectReason.value = ''
}

const cancelReject = () => {
  rejectingId.value = null
  rejectReason.value = ''
}

const confirmReject = async (request: RoleChangeRequest) => {
  const reason = normalizeRejectReason(rejectReason.value, '未填写原因')
  if (authStore.mode === 'real') {
    try {
      await service.handleApproval(request.id, 'REJECT', reason)
      const requests = await service.getRoleRequests()
      if (requests) {
        store.setRoleRequests(requests)
      }
      auditStore.addLog('审批拒绝角色变更', `${getUserName(request.userId)}：${reason}`)
      service.addNotification({
        title: '角色变更审批拒绝',
        content: `${getUserName(request.userId)}：${reason}`
      })
    } catch (error) {
      service.addNotification({
        title: '审批失败',
        content: error instanceof Error ? error.message : '审批处理失败'
      })
    }
  } else {
    store.rejectRoleChange(request.id, '演示管理员', reason)
    auditStore.addLog('审批拒绝角色变更', `${getUserName(request.userId)}：${reason}`)
    service.addNotification({
      title: '角色变更审批拒绝',
      content: `${getUserName(request.userId)}：${reason}`
    })
  }
  cancelReject()
}

const acceptInvite = async (invite: InviteRequest) => {
  if (authStore.mode === 'real') {
    try {
      await service.handleApproval(invite.id, 'APPROVE', '邀请通过')
      const invites = await service.getInvites()
      if (invites) {
        store.setInvites(invites)
      }
      auditStore.addLog('审批通过邀请', invite.email)
      service.addNotification({
        title: '邀请审批通过',
        content: `${invite.email} 已通过`
      })
    } catch (error) {
      service.addNotification({
        title: '审批失败',
        content: error instanceof Error ? error.message : '审批处理失败'
      })
    }
  } else {
    store.acceptInvite(invite.id)
    auditStore.addLog('审批通过邀请', invite.email)
    service.addNotification({
      title: '邀请审批通过',
      content: `${invite.email} 已通过`
    })
  }
}

const rejectInvite = async (invite: InviteRequest) => {
  if (authStore.mode === 'real') {
    try {
      await service.handleApproval(invite.id, 'REJECT', '邀请拒绝')
      const invites = await service.getInvites()
      if (invites) {
        store.setInvites(invites)
      }
      auditStore.addLog('审批拒绝邀请', invite.email)
      service.addNotification({
        title: '邀请审批拒绝',
        content: `${invite.email} 已拒绝`
      })
    } catch (error) {
      service.addNotification({
        title: '审批失败',
        content: error instanceof Error ? error.message : '审批处理失败'
      })
    }
  } else {
    invite.status = '已拒绝'
    auditStore.addLog('审批拒绝邀请', invite.email)
    service.addNotification({
      title: '邀请审批拒绝',
      content: `${invite.email} 已拒绝`
    })
  }
}

const filteredRequests = computed(() => {
  return pendingRequests.value.filter((request) => {
    const matchesQuery = getUserName(request.userId).includes(requestQuery.value)
    const startOk = requestStart.value ? new Date(request.requestedAt).getTime() >= new Date(requestStart.value).getTime() : true
    const endOk = requestEnd.value ? new Date(request.requestedAt).getTime() <= new Date(requestEnd.value).getTime() : true
    return matchesQuery && startOk && endOk
  })
})

const filteredInvites = computed(() => {
  return pendingInvites.value.filter((invite) => {
    const matchesQuery = invite.email.includes(inviteQuery.value)
    const startOk = inviteStart.value ? new Date(invite.invitedAt).getTime() >= new Date(inviteStart.value).getTime() : true
    const endOk = inviteEnd.value ? new Date(invite.invitedAt).getTime() <= new Date(inviteEnd.value).getTime() : true
    return matchesQuery && startOk && endOk
  })
})

const requestTotalPages = computed(() => Math.max(1, Math.ceil(filteredRequests.value.length / pageSize)))
const inviteTotalPages = computed(() => Math.max(1, Math.ceil(filteredInvites.value.length / pageSize)))

const pagedRequests = computed(() => {
  const start = requestPage.value * pageSize
  return filteredRequests.value.slice(start, start + pageSize)
})

const pagedInvites = computed(() => {
  const start = invitePage.value * pageSize
  return filteredInvites.value.slice(start, start + pageSize)
})

watch([requestQuery, requestStart, requestEnd], () => {
  requestPage.value = 0
})

watch([inviteQuery, inviteStart, inviteEnd], () => {
  invitePage.value = 0
})

const allRequestsSelected = computed(() => {
  return filteredRequests.value.length > 0 && filteredRequests.value.every((req) => selectedRequestIds.value.includes(req.id))
})

const allInvitesSelected = computed(() => {
  return filteredInvites.value.length > 0 && filteredInvites.value.every((invite) => selectedInviteIds.value.includes(invite.id))
})

const toggleRequestSelect = (id: string) => {
  if (selectedRequestIds.value.includes(id)) {
    selectedRequestIds.value = selectedRequestIds.value.filter((item) => item !== id)
  } else {
    selectedRequestIds.value = [...selectedRequestIds.value, id]
  }
}

const toggleInviteSelect = (id: string) => {
  if (selectedInviteIds.value.includes(id)) {
    selectedInviteIds.value = selectedInviteIds.value.filter((item) => item !== id)
  } else {
    selectedInviteIds.value = [...selectedInviteIds.value, id]
  }
}

const selectAllRequests = () => {
  if (allRequestsSelected.value) {
    selectedRequestIds.value = []
  } else {
    selectedRequestIds.value = filteredRequests.value.map((req) => req.id)
  }
}

const selectAllInvites = () => {
  if (allInvitesSelected.value) {
    selectedInviteIds.value = []
  } else {
    selectedInviteIds.value = filteredInvites.value.map((inv) => inv.id)
  }
}

const batchApprove = async () => {
  const idsToApprove = filteredRequests.value
    .filter((req) => selectedRequestIds.value.includes(req.id))
    .map((req) => req.id)
  if (idsToApprove.length === 0) return

  if (authStore.mode === 'real') {
    try {
      await service.batchHandleApproval(idsToApprove, 'APPROVE', '批量审批通过')
      const requests = await service.getRoleRequests()
      if (requests) {
        store.setRoleRequests(requests)
      }
      auditStore.addLog('批量审批通过', `${idsToApprove.length} 条角色变更申请`)
      service.addNotification({
        title: '批量审批通过',
        content: `已通过 ${idsToApprove.length} 条申请`
      })
    } catch (error) {
      service.addNotification({
        title: '批量审批失败',
        content: error instanceof Error ? error.message : '批量审批处理失败'
      })
    }
  } else {
    filteredRequests.value
      .filter((req) => selectedRequestIds.value.includes(req.id))
      .forEach(approve)
  }
  selectedRequestIds.value = []
}

const batchReject = async () => {
  const reason = normalizeRejectReason(batchRejectReason.value)
  const idsToReject = filteredRequests.value
    .filter((req) => selectedRequestIds.value.includes(req.id))
    .map((req) => req.id)
  if (idsToReject.length === 0) return

  if (authStore.mode === 'real') {
    try {
      await service.batchHandleApproval(idsToReject, 'REJECT', reason)
      const requests = await service.getRoleRequests()
      if (requests) {
        store.setRoleRequests(requests)
      }
      auditStore.addLog('批量审批拒绝', `${idsToReject.length} 条角色变更申请：${reason}`)
      service.addNotification({
        title: '批量审批拒绝',
        content: `已拒绝 ${idsToReject.length} 条申请`
      })
    } catch (error) {
      service.addNotification({
        title: '批量审批失败',
        content: error instanceof Error ? error.message : '批量审批处理失败'
      })
    }
  } else {
    filteredRequests.value
      .filter((req) => selectedRequestIds.value.includes(req.id))
      .forEach((req) => {
        store.rejectRoleChange(req.id, '演示管理员', reason)
        auditStore.addLog('审批拒绝角色变更', `${getUserName(req.userId)}：${reason}`)
        service.addNotification({
          title: '角色变更审批拒绝',
          content: `${getUserName(req.userId)}：${reason}`
        })
      })
  }
  selectedRequestIds.value = []
  batchRejectReason.value = ''
}

const batchAcceptInvites = async () => {
  const idsToAccept = filteredInvites.value
    .filter((inv) => selectedInviteIds.value.includes(inv.id))
    .map((inv) => inv.id)
  if (idsToAccept.length === 0) return

  if (authStore.mode === 'real') {
    try {
      await service.batchHandleApproval(idsToAccept, 'APPROVE', '批量邀请通过')
      const invites = await service.getInvites()
      if (invites) {
        store.setInvites(invites)
      }
      auditStore.addLog('批量审批通过', `${idsToAccept.length} 条邀请申请`)
      service.addNotification({
        title: '批量邀请审批通过',
        content: `已通过 ${idsToAccept.length} 条邀请`
      })
    } catch (error) {
      service.addNotification({
        title: '批量审批失败',
        content: error instanceof Error ? error.message : '批量审批处理失败'
      })
    }
  } else {
    filteredInvites.value
      .filter((inv) => selectedInviteIds.value.includes(inv.id))
      .forEach(acceptInvite)
  }
  selectedInviteIds.value = []
}

const batchRejectInvites = async () => {
  const idsToReject = filteredInvites.value
    .filter((inv) => selectedInviteIds.value.includes(inv.id))
    .map((inv) => inv.id)
  if (idsToReject.length === 0) return

  if (authStore.mode === 'real') {
    try {
      await service.batchHandleApproval(idsToReject, 'REJECT', '批量邀请拒绝')
      const invites = await service.getInvites()
      if (invites) {
        store.setInvites(invites)
      }
      auditStore.addLog('批量审批拒绝', `${idsToReject.length} 条邀请申请`)
      service.addNotification({
        title: '批量邀请审批拒绝',
        content: `已拒绝 ${idsToReject.length} 条邀请`
      })
    } catch (error) {
      service.addNotification({
        title: '批量审批失败',
        content: error instanceof Error ? error.message : '批量审批处理失败'
      })
    }
  } else {
    filteredInvites.value
      .filter((inv) => selectedInviteIds.value.includes(inv.id))
      .forEach(rejectInvite)
  }
  selectedInviteIds.value = []
}
</script>
