<template>
  <h2 class="ops-page-title">用户管理</h2>

  <div class="ops-card">
    <div class="ops-toolbar admin-users-toolbar">
      <a-input
        v-model:value="filter.keyword"
        class="admin-users-search"
        placeholder="搜索姓名 / 手机号 / 邮箱"
        allow-clear
        @press-enter="reload"
        @change="onKeywordChange"
      />
      <a-select
        v-model:value="filter.status"
        class="admin-users-status"
        :options="statusOptions"
        placeholder="状态"
        allow-clear
        @change="reload"
      />
      <a-button @click="reload">刷新</a-button>
      <span class="admin-users-toolbar__spacer" />
      <a-button type="primary" @click="openCreate">新增用户</a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="rows"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'identity'">
          <div class="identity-cell">
            <strong>{{ displayUserName(record) }}</strong>
            <span>#{{ record.id }}</span>
          </div>
        </template>
        <template v-else-if="column.key === 'phone'">
          {{ record.phone }}
        </template>
        <template v-else-if="column.key === 'email'">
          {{ record.email || '—' }}
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === 'active' ? 'green' : 'red'">
            {{ record.status === 'active' ? '启用' : '停用' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'role'">
          <a-tag :color="roleColor(record.tenant_role)">
            {{ roleLabel(record.tenant_role) }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'kol'">
          <a-space>
            <a-tag :color="kolColor(record.kol_status)">
              {{ kolLabel(record.kol_status) }}
            </a-tag>
            <a-tag v-if="record.kol_market_enabled" color="green">市场展示</a-tag>
          </a-space>
        </template>
        <template v-else-if="column.key === 'plan'">
          <div class="plan-cell">
            <a-space>
              <a-tag>{{ record.plan_name || record.plan_code || '—' }}</a-tag>
              <a-tag :color="record.subscription_status === 'active' ? 'green' : 'default'">
                {{ record.subscription_status || '—' }}
              </a-tag>
            </a-space>
            <span
              :class="[
                'plan-cell__expiry',
                { 'plan-cell__expiry--expired': isExpired(record.subscription_end_at) },
              ]"
            >
              {{ formatSubscriptionEnd(record.subscription_end_at) }}
            </span>
          </div>
        </template>
        <template v-else-if="column.key === 'tenant'">
          <span v-if="record.tenant_id">#{{ record.tenant_id }}</span>
          <span v-else class="muted-text">—</span>
        </template>
        <template v-else-if="column.key === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-else-if="column.key === 'actions'">
          <div class="table-actions-row">
            <a-tooltip title="编辑">
              <a-button
                type="text"
                shape="circle"
                size="small"
                class="action-btn action-edit"
                @click="openEdit(record)"
              >
                <EditOutlined />
              </a-button>
            </a-tooltip>

            <a-tooltip title="KOL身份">
              <a-button
                type="text"
                shape="circle"
                size="small"
                class="action-btn action-kol"
                @click="openKol(record)"
              >
                <IdcardOutlined />
              </a-button>
            </a-tooltip>

            <a-tooltip title="恢复套餐默认额度">
              <a-popconfirm
                title="确认恢复当前套餐默认额度？文章生成次数和 AI 点数会恢复到套餐默认值。"
                :ok-button-props="{ danger: true, loading: resetUsageLoadingId === record.id }"
                @confirm="resetPlanUsage(record)"
              >
                <a-button type="text" shape="circle" size="small" class="action-btn action-reset">
                  <ReloadOutlined />
                </a-button>
              </a-popconfirm>
            </a-tooltip>

            <a-tooltip title="重置密码">
              <a-button
                type="text"
                shape="circle"
                size="small"
                class="action-btn action-key"
                @click="openResetPassword(record)"
              >
                <KeyOutlined />
              </a-button>
            </a-tooltip>

            <a-tooltip title="清除登录锁定">
              <a-popconfirm
                title="确认清除该用户的登录锁定状态？"
                :ok-button-props="{ loading: resetLoginLockLoadingId === record.id }"
                @confirm="resetLoginLock(record)"
              >
                <a-button type="text" shape="circle" size="small" class="action-btn action-unlock">
                  <UnlockOutlined />
                </a-button>
              </a-popconfirm>
            </a-tooltip>

            <a-tooltip :title="record.status === 'active' ? '停用用户' : '启用用户'">
              <a-popconfirm
                :title="record.status === 'active' ? '确认停用该用户？' : '确认启用该用户？'"
                @confirm="toggleStatus(record)"
              >
                <a-button
                  type="text"
                  shape="circle"
                  size="small"
                  :class="[
                    'action-btn',
                    record.status === 'active' ? 'action-revoke' : 'action-play',
                  ]"
                >
                  <StopOutlined v-if="record.status === 'active'" />
                  <PlayCircleOutlined v-else />
                </a-button>
              </a-popconfirm>
            </a-tooltip>
          </div>
        </template>
      </template>
    </a-table>
  </div>

  <a-modal
    v-model:open="createOpen"
    title="新增用户"
    :confirm-loading="createLoading"
    @ok="submitCreate"
    @cancel="resetCreate"
  >
    <a-form layout="vertical" :model="createForm">
      <a-form-item label="手机号" required>
        <a-input v-model:value="createForm.phone" placeholder="电话号码" />
      </a-form-item>
      <a-form-item label="姓名">
        <a-input v-model:value="createForm.name" placeholder="可选" />
      </a-form-item>
      <a-form-item label="邮箱">
        <a-input v-model:value="createForm.email" placeholder="可选" />
      </a-form-item>
      <a-form-item label="初始密码" required help="至少 8 位">
        <a-input-password v-model:value="createForm.password" placeholder="≥ 8 位" />
      </a-form-item>
      <a-form-item label="用户角色" required>
        <a-select v-model:value="createForm.role" :options="roleOptions" />
      </a-form-item>
      <a-form-item label="初始套餐" required>
        <a-select v-model:value="createForm.plan_code" :options="planOptions" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    v-model:open="editOpen"
    :title="editTarget ? `编辑 ${displayUserName(editTarget)}` : '编辑用户'"
    :confirm-loading="editLoading"
    @ok="submitEdit"
    @cancel="editOpen = false"
  >
    <a-form layout="vertical" :model="editForm">
      <a-form-item label="手机号" required>
        <a-input v-model:value="editForm.phone" />
      </a-form-item>
      <a-form-item label="姓名">
        <a-input v-model:value="editForm.name" />
      </a-form-item>
      <a-form-item label="邮箱">
        <a-input v-model:value="editForm.email" placeholder="可选" />
      </a-form-item>
      <a-form-item label="用户角色" required>
        <a-select v-model:value="editForm.role" :options="roleOptions" />
      </a-form-item>
      <a-form-item label="套餐" required>
        <a-select
          v-model:value="editForm.plan_code"
          :options="planOptions"
          @change="onEditPlanChange"
        />
      </a-form-item>
      <a-form-item label="会员到期日" required>
        <a-date-picker
          v-model:value="editForm.subscription_end_date"
          class="admin-users-date-picker"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allow-clear="false"
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    v-model:open="kolOpen"
    :title="kolTarget ? `设置 ${displayUserName(kolTarget)} 的 KOL 身份` : 'KOL 身份'"
    :confirm-loading="kolLoading"
    @ok="submitKol"
    @cancel="kolOpen = false"
  >
    <a-form layout="vertical" :model="kolForm">
      <a-form-item label="KOL 身份" required>
        <a-switch
          v-model:checked="kolForm.enabled"
          checked-children="开通"
          un-checked-children="停用"
        />
      </a-form-item>
      <a-form-item label="KOL 昵称">
        <a-input v-model:value="kolForm.display_name" placeholder="默认使用姓名或手机号" />
      </a-form-item>
      <a-form-item label="市场展示">
        <a-switch
          v-model:checked="kolForm.market_enabled"
          :disabled="!kolForm.enabled"
          checked-children="展示"
          un-checked-children="不展示"
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    v-model:open="resetOpen"
    :title="resetTarget ? `重置 ${displayUserName(resetTarget)} 的密码` : '重置密码'"
    :confirm-loading="resetLoading"
    @ok="submitResetPassword"
    @cancel="resetOpen = false"
  >
    <a-form layout="vertical">
      <a-form-item label="新密码" required help="至少 8 位">
        <a-input-password v-model:value="resetPasswordValue" placeholder="≥ 8 位" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {
  EditOutlined,
  IdcardOutlined,
  KeyOutlined,
  PlayCircleOutlined,
  ReloadOutlined,
  StopOutlined,
  UnlockOutlined,
} from '@ant-design/icons-vue'
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'

import { showOpsError } from '@/lib/errors'
import { http } from '@/lib/http'

interface AdminUserRow {
  id: number
  email: string | null
  phone: string
  name: string | null
  status: string
  tenant_id: number | null
  tenant_name: string | null
  tenant_status: string | null
  tenant_role: string | null
  primary_workspace_id: number | null
  plan_code: string | null
  plan_name: string | null
  subscription_status: string | null
  subscription_end_at: string | null
  kol_profile_id: number | null
  kol_display_name: string | null
  kol_status: string | null
  kol_market_enabled: boolean | null
  created_at: string
  updated_at: string
}

interface PlanItem {
  id: number
  code: string
  name: string
  status: string
  duration_secs: number
  article_limit: number
  ai_points_monthly: number
  brand_limit: number
}

interface RoleItem {
  code: string
  name: string
  description: string
  permissions: string[]
}

interface ListResult {
  items: AdminUserRow[]
  total: number
  page: number
  size: number
}

interface ResetPlanUsageResult {
  user: AdminUserRow
  reset: {
    article_reservations: number
    article_amount: number
    ai_point_reservations: number
    ai_points_amount: number
  }
}

interface ResetLoginLockResult {
  id: number
  redis_deleted_keys: number
  fallback_deleted_keys: number
  redis_scan_patterns: string[]
  redis_addr?: string
  redis_db: number
}

const filter = reactive({
  keyword: '',
  status: undefined as string | undefined,
})

const statusOptions = [
  { label: '启用', value: 'active' },
  { label: '停用', value: 'disabled' },
]

const columns: TableColumnsType<AdminUserRow> = [
  { title: '用户', key: 'identity', width: 180 },
  { title: '手机号', key: 'phone', width: 160 },
  { title: '邮箱', key: 'email', width: 220 },
  { title: '状态', key: 'status', width: 100 },
  { title: '角色', key: 'role', width: 120 },
  { title: '套餐', key: 'plan', width: 180 },
  { title: 'KOL', key: 'kol', width: 180 },
  { title: '空间', key: 'tenant', width: 100 },
  { title: '创建时间', key: 'created_at', width: 180 },
  { title: '操作', key: 'actions', width: 300 },
]

const rows = ref<AdminUserRow[]>([])
const plans = ref<PlanItem[]>([])
const roles = ref<RoleItem[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)

const pagination = computed<TablePaginationConfig>(() => ({
  current: page.value,
  pageSize: size.value,
  total: total.value,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
}))

const planOptions = computed(() =>
  plans.value.map((plan) => ({
    label: `${plan.name} (${plan.code})`,
    value: plan.code,
  })),
)

const roleOptions = computed(() =>
  roles.value.map((role) => ({
    label: role.name,
    value: role.code,
  })),
)

let keywordTimer: number | null = null

function onKeywordChange() {
  if (keywordTimer) window.clearTimeout(keywordTimer)
  keywordTimer = window.setTimeout(() => {
    page.value = 1
    void reload()
  }, 300)
}

async function reload() {
  loading.value = true
  try {
    const result = await http.get<ListResult>('/admin-users', {
      keyword: filter.keyword || undefined,
      status: filter.status || undefined,
      page: page.value,
      size: size.value,
    })
    rows.value = result.items
    total.value = result.total
  } catch (error) {
    showOpsError(error)
  } finally {
    loading.value = false
  }
}

async function loadMeta() {
  try {
    const [planResult, roleResult] = await Promise.all([
      http.get<PlanItem[]>('/plans'),
      http.get<RoleItem[]>('/roles'),
    ])
    plans.value = planResult
    roles.value = roleResult
  } catch (error) {
    showOpsError(error)
  }
}

function onTableChange(pag: TablePaginationConfig) {
  page.value = pag.current ?? 1
  size.value = pag.pageSize ?? 20
  void reload()
}

const createOpen = ref(false)
const createLoading = ref(false)
const createForm = reactive({
  phone: '',
  name: '',
  email: '',
  password: '',
  role: 'tenant_admin',
  plan_code: '',
})

function resetCreate() {
  createForm.phone = ''
  createForm.name = ''
  createForm.email = ''
  createForm.password = ''
  createForm.role = 'tenant_admin'
  createForm.plan_code = defaultPlanCode()
  createOpen.value = false
}

function openCreate() {
  resetCreate()
  createOpen.value = true
}

async function submitCreate() {
  const phone = normalizePhone(createForm.phone)
  if (!phone) {
    message.warning('请输入有效手机号')
    return
  }
  if (createForm.password.length < 8) {
    message.warning('初始密码至少 8 位')
    return
  }
  if (!createForm.role || !createForm.plan_code) {
    message.warning('请选择用户角色和套餐')
    return
  }
  createLoading.value = true
  try {
    await http.post('/admin-users', {
      phone,
      name: createForm.name.trim(),
      email: createForm.email.trim(),
      password: createForm.password,
      role: createForm.role,
      plan_code: createForm.plan_code,
    })
    message.success('新建成功')
    resetCreate()
    void reload()
  } catch (error) {
    showOpsError(error)
  } finally {
    createLoading.value = false
  }
}

const editOpen = ref(false)
const editLoading = ref(false)
const editTarget = ref<AdminUserRow | null>(null)
const editForm = reactive({
  phone: '',
  name: '',
  email: '',
  role: 'tenant_admin',
  plan_code: '',
  subscription_end_date: '',
})

function openEdit(row: AdminUserRow) {
  editTarget.value = row
  editForm.phone = row.phone
  editForm.name = row.name ?? ''
  editForm.email = row.email ?? ''
  editForm.role = row.tenant_role ?? 'tenant_admin'
  editForm.plan_code = row.plan_code ?? defaultPlanCode()
  editForm.subscription_end_date = row.subscription_end_at
    ? dayjs(row.subscription_end_at).format('YYYY-MM-DD')
    : estimatePlanEndDate(editForm.plan_code)
  editOpen.value = true
}

function onEditPlanChange(value: unknown) {
  if (typeof value === 'string') {
    editForm.subscription_end_date = estimatePlanEndDate(value)
  }
}

async function submitEdit() {
  if (!editTarget.value) return
  const phone = normalizePhone(editForm.phone)
  if (!phone) {
    message.warning('请输入有效手机号')
    return
  }
  if (!editForm.role || !editForm.plan_code) {
    message.warning('请选择用户角色和套餐')
    return
  }
  if (!editForm.subscription_end_date) {
    message.warning('请选择会员到期日')
    return
  }
  const originalEndDate = editTarget.value.subscription_end_at
    ? dayjs(editTarget.value.subscription_end_at).format('YYYY-MM-DD')
    : ''
  const subscriptionEndAt = dayjs(editForm.subscription_end_date).endOf('day').toISOString()
  editLoading.value = true
  try {
    await http.patch(`/admin-users/${editTarget.value.id}`, {
      phone,
      name: editForm.name.trim(),
      email: editForm.email.trim(),
    })
    if (editForm.plan_code !== editTarget.value.plan_code) {
      await http.post(`/admin-users/${editTarget.value.id}/plan`, {
        plan_code: editForm.plan_code,
      })
    }
    if (editForm.role !== editTarget.value.tenant_role) {
      await http.post(`/admin-users/${editTarget.value.id}/role`, {
        role: editForm.role,
      })
    }
    if (editForm.subscription_end_date !== originalEndDate) {
      await http.post(`/admin-users/${editTarget.value.id}/subscription-expiry`, {
        end_at: subscriptionEndAt,
      })
    }
    message.success('用户设置已更新')
    editOpen.value = false
    void reload()
  } catch (error) {
    showOpsError(error)
  } finally {
    editLoading.value = false
  }
}

const resetUsageLoadingId = ref<number | null>(null)

async function resetPlanUsage(row: AdminUserRow) {
  resetUsageLoadingId.value = row.id
  try {
    const result = await http.post<ResetPlanUsageResult>(`/admin-users/${row.id}/reset-plan-usage`)
    message.success(`已恢复到套餐默认额度：${planQuotaLabel(result.user.plan_code)}`)
    rows.value = rows.value.map((item) => (item.id === row.id ? result.user : item))
    void reload()
  } catch (error) {
    showOpsError(error)
  } finally {
    resetUsageLoadingId.value = null
  }
}

const resetLoginLockLoadingId = ref<number | null>(null)

async function resetLoginLock(row: AdminUserRow) {
  resetLoginLockLoadingId.value = row.id
  try {
    const result = await http.post<ResetLoginLockResult>(`/admin-users/${row.id}/reset-login-lock`)
    if (result.redis_deleted_keys > 0) {
      message.success(`登录锁定已清除，已删除 ${result.redis_deleted_keys} 个 Redis key`)
    } else if (result.fallback_deleted_keys > 0) {
      message.success(`登录锁定已清除，已清理 ${result.fallback_deleted_keys} 个本机保护状态`)
    } else {
      message.warning('未发现登录锁 Redis key，请检查 ops-api 与 admin-web 使用的 Redis 地址和 DB 是否一致')
    }
  } catch (error) {
    showOpsError(error)
  } finally {
    resetLoginLockLoadingId.value = null
  }
}

const resetOpen = ref(false)
const resetLoading = ref(false)
const resetTarget = ref<AdminUserRow | null>(null)
const resetPasswordValue = ref('')

function openResetPassword(row: AdminUserRow) {
  resetTarget.value = row
  resetPasswordValue.value = ''
  resetOpen.value = true
}

async function submitResetPassword() {
  if (!resetTarget.value) return
  if (resetPasswordValue.value.length < 8) {
    message.warning('新密码至少 8 位')
    return
  }
  resetLoading.value = true
  try {
    await http.post(`/admin-users/${resetTarget.value.id}/password`, {
      password: resetPasswordValue.value,
    })
    message.success('密码已重置')
    resetOpen.value = false
  } catch (error) {
    showOpsError(error)
  } finally {
    resetLoading.value = false
  }
}

const kolOpen = ref(false)
const kolLoading = ref(false)
const kolTarget = ref<AdminUserRow | null>(null)
const kolForm = reactive({
  enabled: false,
  display_name: '',
  market_enabled: false,
})

function openKol(row: AdminUserRow) {
  kolTarget.value = row
  kolForm.enabled = row.kol_status === 'active'
  kolForm.display_name = row.kol_display_name ?? displayUserName(row)
  kolForm.market_enabled = Boolean(row.kol_market_enabled)
  kolOpen.value = true
}

async function submitKol() {
  if (!kolTarget.value) return
  kolLoading.value = true
  try {
    await http.post(`/admin-users/${kolTarget.value.id}/kol`, {
      enabled: kolForm.enabled,
      display_name: kolForm.display_name.trim(),
      market_enabled: kolForm.enabled ? kolForm.market_enabled : false,
    })
    message.success('KOL 身份已更新')
    kolOpen.value = false
    void reload()
  } catch (error) {
    showOpsError(error)
  } finally {
    kolLoading.value = false
  }
}

async function toggleStatus(row: AdminUserRow) {
  const next = row.status === 'active' ? 'disabled' : 'active'
  try {
    await http.post(`/admin-users/${row.id}/status`, { status: next })
    message.success(next === 'active' ? '已启用' : '已停用')
    void reload()
  } catch (error) {
    showOpsError(error)
  }
}

function normalizePhone(value: string): string {
  const phone = value.trim().replace(/[\s-]/g, '')
  return /^\+?\d{6,20}$/.test(phone) ? phone : ''
}

function displayUserName(row: AdminUserRow): string {
  return row.name || row.phone || row.email || `#${row.id}`
}

function defaultPlanCode(): string {
  return plans.value[0]?.code ?? 'free'
}

function planQuotaLabel(planCode: string | null): string {
  const plan = plans.value.find((item) => item.code === planCode)
  if (!plan) return '文章和 AI 点数按当前套餐默认值重置'
  return `文章 ${plan.article_limit} 次，AI 点数 ${plan.ai_points_monthly} 点`
}

function estimatePlanEndDate(planCode: string): string {
  const durationSecs = plans.value.find((plan) => plan.code === planCode)?.duration_secs
  if (!durationSecs || durationSecs <= 0) {
    return dayjs().format('YYYY-MM-DD')
  }
  return dayjs().add(durationSecs, 'second').format('YYYY-MM-DD')
}

function roleLabel(role: string | null): string {
  return roles.value.find((item) => item.code === role)?.name ?? role ?? '—'
}

function roleColor(role: string | null): string {
  if (role === 'tenant_admin') return 'blue'
  if (role === 'editor') return 'purple'
  if (role === 'viewer') return 'default'
  return 'default'
}

function kolLabel(status: string | null): string {
  if (status === 'active') return '已开通'
  if (status === 'suspended') return '已停用'
  if (status === 'closed') return '已关闭'
  return '未开通'
}

function kolColor(status: string | null): string {
  if (status === 'active') return 'gold'
  if (status === 'suspended') return 'default'
  if (status === 'closed') return 'red'
  return 'default'
}

function formatSubscriptionEnd(value: string | null): string {
  if (!value) return '到期：—'
  return `到期：${dayjs(value).format('YYYY-MM-DD')}`
}

function isExpired(value: string | null): boolean {
  return Boolean(value && dayjs(value).isBefore(dayjs()))
}

function formatDate(value: string): string {
  return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  void loadMeta()
  void reload()
})
</script>

<style scoped>
.admin-users-toolbar {
  align-items: center;
}

.admin-users-search {
  width: 280px;
}

.admin-users-status {
  width: 140px;
}

.admin-users-date-picker {
  width: 100%;
}

.admin-users-toolbar__spacer {
  flex: 1;
}

.identity-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.plan-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 170px;
}

.plan-cell__expiry {
  color: #64748b;
  font-size: 12px;
  line-height: 18px;
}

.plan-cell__expiry--expired {
  color: #dc2626;
}

.identity-cell span,
.muted-text {
  color: #94a3b8;
  font-size: 12px;
}

.action-unlock :deep(.anticon) {
  color: #16a34a;
}
</style>
