<template>
  <section class="space-y-6">
    <ListSection
      :page="tab === 'staff' ? staffPage : activityPage"
      :total-pages="tab === 'staff' ? staffTotalPages : activityTotalPages"
      @prev="handlePrev"
      @next="handleNext"
    >
      <template #title>用户管理</template>
      <template #subtitle>管理运营成员与权限角色。</template>
      <template #filters>
        <div class="flex flex-wrap items-center gap-3">
          <div class="flex items-center gap-2 text-sm font-semibold">
            <button
              class="rounded-full px-3 py-1.5"
              :class="tab === 'staff' ? 'bg-mosquito-accent/10 text-mosquito-ink' : 'text-mosquito-ink/60'"
              data-test="tab-staff"
              @click="tab = 'staff'"
            >
              运营用户
            </button>
            <button
              class="rounded-full px-3 py-1.5"
              :class="tab === 'activity' ? 'bg-mosquito-accent/10 text-mosquito-ink' : 'text-mosquito-ink/60'"
              data-test="tab-activity"
              @click="switchToActivity()"
            >
              活动用户
            </button>
          </div>
          <div v-if="tab === 'staff'" class="flex flex-wrap items-center gap-2 text-xs text-mosquito-ink/70">
            <input class="mos-input !py-1 !px-2 !text-xs w-full md:w-56" v-model="staffQuery" placeholder="搜索姓名/邮箱" />
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="roleFilter">
              <option value="">全部角色</option>
              <option v-for="role in roleOptions" :key="role.value" :value="role.value">{{ role.label }}</option>
            </select>
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="statusFilter">
              <option value="">全部状态</option>
              <option value="正常">正常</option>
              <option value="冻结">冻结</option>
            </select>
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAllStaff">
              {{ allStaffSelected ? '取消全选' : '全选' }}
            </button>
            <PermissionButton permission="user.index.unfreeze.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchEnable">
              批量启用
            </PermissionButton>
            <PermissionButton permission="user.index.freeze.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchDisable">
              批量禁用
            </PermissionButton>
          </div>
          <div v-else class="flex flex-wrap items-center gap-3">
            <label class="text-xs text-mosquito-ink/70">活动</label>
            <select class="mos-input !py-1 !px-2 !text-xs" v-model.number="selectedActivityId" @change="loadActivityUsers">
              <option v-for="activity in activities" :key="activity.id" :value="activity.id">
                {{ activity.name }}
              </option>
            </select>
            <input class="mos-input !py-1 !px-2 !text-xs w-full md:w-56" v-model="activityQuery" placeholder="搜索昵称/手机号" />
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="activityStatusFilter">
              <option value="">全部状态</option>
              <option value="已注册">已注册</option>
              <option value="未注册">未注册</option>
            </select>
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="loadActivityUsers">刷新</button>
          </div>
        </div>
      </template>
      <template #actions>
        <PermissionButton permission="user.index.export.ALL" variant="secondary" :hide-when-no-permission="true" @click="handleExportUsers">
          导出用户
        </PermissionButton>
        <RouterLink v-if="tab === 'staff'" to="/users/invite" class="mos-btn mos-btn-accent">邀请用户</RouterLink>
      </template>
      <template #default>
        <div v-if="tab === 'staff'" class="space-y-3">
          <div
            v-for="user in pagedUsers"
            :key="user.id"
            class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3 transition hover:bg-mosquito-bg/60"
          >
            <div class="flex items-center gap-3">
              <input
                type="checkbox"
                class="h-4 w-4"
                :checked="selectedStaffIds.includes(user.id)"
                @click.stop
                @change.stop="toggleSelect(user.id)"
              />
              <RouterLink :to="`/users/${user.id}`" class="flex flex-col">
                <span class="text-sm font-semibold text-mosquito-ink">{{ user.name }}</span>
                <span class="mos-muted text-xs">{{ user.email }}</span>
              </RouterLink>
            </div>
            <div class="flex items-center gap-3 text-xs text-mosquito-ink/70">
              <span class="rounded-full bg-mosquito-accent/10 px-2 py-1 text-[10px] font-semibold text-mosquito-brand">{{ roleLabel(user.role) }}</span>
              <span>{{ user.status }}</span>
              <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click.stop="requestRole(user)">
                申请变更
              </button>
              <PermissionButton
                v-if="user.status === '冻结'"
                permission="user.index.unfreeze.ALL"
                variant="secondary"
                :hide-when-no-permission="true"
                @click.stop="toggleUser(user)"
              >
                启用
              </PermissionButton>
              <PermissionButton
                v-else
                permission="user.index.freeze.ALL"
                variant="secondary"
                :hide-when-no-permission="true"
                @click.stop="toggleUser(user)"
              >
                禁用
              </PermissionButton>
            </div>
          </div>
        </div>
        <div v-else-if="pagedActivityUsers.length" class="space-y-3" data-test="activity-users-list">
          <div
            v-for="friend in pagedActivityUsers"
            :key="friend.nickname + friend.maskedPhone"
            data-test="activity-user-row"
            class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3"
          >
            <div>
              <div class="text-sm font-semibold text-mosquito-ink">{{ friend.nickname }}</div>
              <div class="mos-muted text-xs">{{ friend.maskedPhone }}</div>
            </div>
            <div class="text-xs text-mosquito-ink/70">{{ friend.status }}</div>
          </div>
        </div>
      </template>
      <template #empty>
        <div
          v-if="tab === 'activity' && !pagedActivityUsers.length"
          data-test="activity-users-empty"
          class="rounded-xl border border-dashed border-mosquito-line p-4 text-sm text-mosquito-ink/60"
        >
          暂无活动用户数据
        </div>
      </template>
    </ListSection>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useDataService } from '../services'
import { RouterLink } from 'vue-router'
import { useAuditStore } from '../stores/audit'
import { useUserStore } from '../stores/users'
import { useActivityStore } from '../stores/activities'
import { useAuthStore } from '../stores/auth'
import ListSection from '../components/ListSection.vue'
import PermissionButton from '../components/PermissionButton.vue'
import { RoleLabels, type AdminRole } from '../auth/roles'

// 15角色体系选项
const roleOptions = computed(() => {
  const roles: { value: string; label: string }[] = []
  for (const [key, label] of Object.entries(RoleLabels)) {
    roles.push({ value: key, label })
  }
  return roles
})

type UserItem = {
  id: string
  name: string
  email: string
  role: string
  status: string
  managerName?: string
}

type ActivityUser = {
  nickname: string
  maskedPhone: string
  status: string
}

import type { UserAccount } from '../stores/users'

const users = ref<UserAccount[]>([])
const service = useDataService()
const auditStore = useAuditStore()
const userStore = useUserStore()
const activityStore = useActivityStore()
const authStore = useAuthStore()
const tab = ref<'staff' | 'activity'>('staff')
const activityUsers = ref<ActivityUser[]>([])
const activities = ref<{ id: number; name: string }[]>([])
const selectedActivityId = ref<number>(0)
const staffQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const selectedStaffIds = ref<string[]>([])
const activityQuery = ref('')
const activityStatusFilter = ref('')
const staffPage = ref(0)
const staffPageSize = 6
const staffTotal = ref(0)
const activityPage = ref(0)
const activityPageSize = 6

onMounted(async () => {
  await loadStaffUsers()
  const [invites, requests] = await Promise.all([
    service.getInvites(),
    service.getRoleRequests()
  ])
  userStore.init(users.value, invites, requests)
  activities.value = activityStore.items.map((item) => ({ id: item.id, name: item.name }))
  selectedActivityId.value = activities.value[0]?.id ?? 0
})

// 加载员工用户（后端分页）
const loadStaffUsers = async () => {
  try {
    const result = await service.getUsersPage({
      page: staffPage.value,
      size: staffPageSize,
      keyword: staffQuery.value || undefined,
      status: statusFilter.value || undefined,
      role: roleFilter.value || undefined
    })
    // 处理分页响应
    const pageResult = result as { items?: any[]; total?: number }
    if (pageResult && typeof pageResult === 'object' && 'items' in pageResult && Array.isArray(pageResult.items)) {
      users.value = pageResult.items
      staffTotal.value = typeof pageResult.total === 'number' ? pageResult.total : pageResult.items.length
    } else if (Array.isArray(result)) {
      users.value = result
      staffTotal.value = result.length
    } else {
      users.value = []
      staffTotal.value = 0
    }
  } catch (error) {
    console.error('Failed to load staff users:', error)
    users.value = []
    staffTotal.value = 0
  }
}

const toggleUser = async (user: UserItem) => {
  const isFreezing = user.status !== '冻结'
  try {
    await userStore.toggleUserStatus(user.id)
    auditStore.addLog(isFreezing ? '冻结用户' : '解冻用户', user.name)
  } catch (error) {
    console.error('用户状态变更失败:', error)
    alert('操作失败: ' + (error as Error).message)
  }
}

const requestRole = (user: UserItem) => {
  userStore.requestRoleChange(user.id, 'super_admin' as AdminRole, '需要更高权限')
  auditStore.addLog('提交角色变更申请', user.name)
}

const roleLabel = (role: string) => {
  return RoleLabels[role as AdminRole] || role
}

const resolveUserId = () => {
  const raw = authStore.user?.id ?? ''
  const parsed = Number(raw)
  return Number.isNaN(parsed) || parsed <= 0 ? 1 : parsed
}

const loadActivityUsers = async () => {
  if (!selectedActivityId.value) {
    activityUsers.value = []
    return
  }
  activityUsers.value = await service.getInvitedFriends(selectedActivityId.value, resolveUserId(), 0, 20)
}

const switchToActivity = async () => {
  tab.value = 'activity'
  await loadActivityUsers()
}

const handlePrev = () => {
  if (tab.value === 'staff') {
    staffPage.value -= 1
  } else {
    activityPage.value -= 1
  }
}

const handleNext = () => {
  if (tab.value === 'staff') {
    staffPage.value += 1
  } else {
    activityPage.value += 1
  }
}

const filteredUsers = computed(() => {
  return users.value.filter((user) => {
    const matchesQuery =
      user.name.includes(staffQuery.value) || user.email.includes(staffQuery.value)
    const matchesRole = roleFilter.value ? user.role === roleFilter.value : true
    const matchesStatus = statusFilter.value ? user.status === statusFilter.value : true
    return matchesQuery && matchesRole && matchesStatus
  })
})

// 监听筛选条件变化，重置页码并重新加载
watch([staffQuery, roleFilter, statusFilter], () => {
  // 如果当前页不是第一页，先回到第一页（这会自动触发loadStaffUsers）
  if (staffPage.value !== 0) {
    staffPage.value = 0
  } else {
    // 如果已经在第一页，直接重新加载
    loadStaffUsers()
  }
})

// 监听页码变化，重新加载数据
watch(staffPage, () => {
  loadStaffUsers()
})

const staffTotalPages = computed(() => Math.max(1, Math.ceil(staffTotal.value / staffPageSize)))

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

const allStaffSelected = computed(() => {
  return filteredUsers.value.length > 0 && filteredUsers.value.every((user) => selectedStaffIds.value.includes(user.id))
})

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

const selectAllStaff = () => {
  if (allStaffSelected.value) {
    selectedStaffIds.value = []
  } else {
    selectedStaffIds.value = filteredUsers.value.map((user) => user.id)
  }
}

const batchEnable = async () => {
  const frozenUsers = users.value.filter(
    (user) => selectedStaffIds.value.includes(user.id) && user.status === '冻结'
  )
  for (const user of frozenUsers) {
    try {
      await userStore.toggleUserStatus(user.id)
      auditStore.addLog('批量解冻用户', user.name)
    } catch (error) {
      console.error(`解冻用户 ${user.name} 失败:`, error)
    }
  }
}

const batchDisable = async () => {
  const activeUsers = users.value.filter(
    (user) => selectedStaffIds.value.includes(user.id) && user.status === '正常'
  )
  for (const user of activeUsers) {
    try {
      await userStore.toggleUserStatus(user.id)
      auditStore.addLog('批量冻结用户', user.name)
    } catch (error) {
      console.error(`冻结用户 ${user.name} 失败:`, error)
    }
  }
}

// 敏感用户导出处理
const handleExportUsers = async () => {
  const apiService = service as any
  try {
    // 先检查是否有已批准的敏感导出审批
    const hasApproval = await apiService.hasApprovedSensitiveExport()

    if (hasApproval) {
      // 有审批，直接导出
      const blob = await apiService.exportUsersWithSensitive()
      downloadBlob(blob, 'users_export.csv')
      auditStore.addLog('导出用户', '敏感数据导出')
    } else {
      // 无审批，弹窗询问是否提交审批申请
      const reason = prompt('导出敏感数据需要审批，请输入导出原因：')
      if (reason) {
        await apiService.submitSensitiveExportApproval(reason)
        alert('审批申请已提交，请等待审批通过后再导出')
        auditStore.addLog('提交导出审批', reason)
      }
    }
  } catch (error: any) {
    if (error.message === 'NEED_APPROVAL') {
      const reason = prompt('导出敏感数据需要审批，请输入导出原因：')
      if (reason) {
        try {
          await apiService.submitSensitiveExportApproval(reason)
          alert('审批申请已提交，请等待审批通过后再导出')
          auditStore.addLog('提交导出审批', reason)
        } catch (submitError) {
          console.error('提交审批失败:', submitError)
          alert('提交审批失败: ' + (submitError as Error).message)
        }
      }
    } else {
      console.error('导出失败:', error)
      alert('导出失败: ' + error.message)
    }
  }
}

// 下载blob为文件
const downloadBlob = (blob: Blob, filename: string) => {
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  window.URL.revokeObjectURL(url)
}

const filteredActivityUsers = computed(() => {
  return activityUsers.value.filter((item) => {
    const matchesQuery =
      item.nickname.includes(activityQuery.value) || item.maskedPhone.includes(activityQuery.value)
    const matchesStatus = activityStatusFilter.value ? item.status === activityStatusFilter.value : true
    return matchesQuery && matchesStatus
  })
})

watch([activityQuery, activityStatusFilter], () => {
  activityPage.value = 0
})

const activityTotalPages = computed(() => Math.max(1, Math.ceil(filteredActivityUsers.value.length / activityPageSize)))

const pagedActivityUsers = computed(() => {
  const start = activityPage.value * activityPageSize
  return filteredActivityUsers.value.slice(start, start + activityPageSize)
})
</script>
