<template>
  <div class="user-management-container">
    <a-page-header title="用户管理" subtitle="管理系统用户和订阅时长" />

    <a-card style="margin-bottom: 16px">
      <!-- 搜索和过滤 -->
      <div class="search-bar">
        <a-input-search
          v-model="searchKey"
          placeholder="搜索用户名或手机号..."
          allow-clear
          @search="handleSearch"
          style="width: 300px; margin-right: 16px"
        />
        <a-button type="primary" @click="refreshUsers">刷新列表</a-button>
      </div>

      <!-- 用户列表 -->
      <a-table
        :columns="columns"
        :data="filteredUsers"
        :loading="isLoading"
        :pagination="{ pageSize: 10 }"
        stripe
      >
        <!-- 用户名列 -->
        <template #username="{ record }">
          <div>
            <p style="margin: 0; font-weight: 500;">{{ record.username }}</p>
            <p style="margin: 4px 0 0 0; font-size: 12px; color: #999;">{{ record.email }}</p>
          </div>
        </template>

        <!-- 角色列 -->
        <template #role="{ record }">
          <a-tag :color="record.role === 'admin' ? 'red' : 'blue'">
            {{ record.role === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </template>

        <!-- 状态列 -->
        <template #status="{ record }">
          <a-tag :color="record.status === 'active' ? 'green' : 'gray'">
            {{ statusDisplay(record.status) }}
          </a-tag>
        </template>

        <!-- 订阅信息列 -->
        <template #subscription="{ record }">
          <div v-if="subscriptionMap[record.id]" class="subscription-info">
            <p style="margin: 0;">
              <span v-if="isSubscriptionExpired(record.id)" style="color: red; font-weight: 500;">
                已过期
              </span>
              <span v-else style="color: green; font-weight: 500;">
                剩余 {{ getRemainingDays(record.id) }} 天
              </span>
            </p>
            <p style="margin: 4px 0 0 0; font-size: 12px; color: #999;">
              过期时间: {{ formatDate(subscriptionMap[record.id].expires_at) }}
            </p>
          </div>
        </template>

        <!-- 操作列 -->
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="openExtendDialog(record)">
              延期
            </a-button>
            <a-button type="text" size="small" @click="openResetPasswordDialog(record)">
              重置密码
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 延期对话框 -->
    <a-modal
      v-model:visible="extendDialogVisible"
      title="延期用户订阅"
      @ok="handleExtend"
      @cancel="extendDialogVisible = false"
    >
      <a-form :model="extendForm" layout="vertical">
        <a-form-item label="用户">
          <p style="margin: 0;">{{ currentUser?.username }} ({{ currentUser?.email }})</p>
        </a-form-item>

        <a-form-item label="延期方式" required>
          <a-radio-group v-model="extendForm.type">
            <a-radio value="days">按天</a-radio>
            <a-radio value="months">按月</a-radio>
            <a-radio value="years">按年</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="数量" required>
          <a-input-number
            v-model="extendForm.amount"
            :min="1"
            :max="1000"
            placeholder="请输入数量"
          />
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea
            v-model="extendForm.reason"
            placeholder="延期原因（可选）"
            :rows="3"
            max-length="200"
          />
        </a-form-item>

        <a-alert
          type="info"
          title="预览"
          v-if="currentUser && subscriptionMap[currentUser.id]"
        >
          <template #default>
            <p style="margin: 0;">
              当前过期时间: {{ formatDate(subscriptionMap[currentUser.id].expires_at) }}
            </p>
            <p style="margin: 8px 0 0 0;">
              延期后: {{ formatDate(calculateNewExpireDate()) }}
            </p>
          </template>
        </a-alert>
      </a-form>
    </a-modal>

    <!-- 重置密码对话框 -->
    <a-modal
      v-model:visible="resetPasswordDialogVisible"
      title="重置用户密码"
      @ok="handleResetPassword"
      @cancel="resetPasswordDialogVisible = false"
    >
      <a-form :model="resetPasswordForm" layout="vertical">
        <a-form-item label="用户">
          <p style="margin: 0;">{{ currentUser?.username }} ({{ currentUser?.email }})</p>
        </a-form-item>

        <a-form-item label="新密码" required>
          <a-input-password
            v-model="resetPasswordForm.newPassword"
            placeholder="请输入新密码"
          />
        </a-form-item>

        <a-form-item label="确认密码" required>
          <a-input-password
            v-model="resetPasswordForm.confirmPassword"
            placeholder="请再次输入密码"
          />
        </a-form-item>

        <a-form-item label="重置原因">
          <a-textarea
            v-model="resetPasswordForm.reason"
            placeholder="重置原因（可选）"
            :rows="3"
            max-length="200"
          />
        </a-form-item>

        <a-alert type="warning" title="警告" closable>
          <template #default>
            <p style="margin: 0;">
              此操作将重置用户的密码，用户需要使用新密码登录。
            </p>
          </template>
        </a-alert>
      </a-form>
    </a-modal>

    <!-- 成功提示 -->
    <a-message v-if="successMessage" type="success" :content="successMessage" />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { reactive, ref, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import authService from '@/service/auth'

// 表格列定义
const columns = [
  { title: '用户信息', dataIndex: 'username', slotName: 'username', width: 200 },
  { title: '角色', dataIndex: 'role', slotName: 'role', width: 100 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 100 },
  { title: '订阅信息', dataIndex: 'subscription', slotName: 'subscription', width: 200 },
  { title: '操作', dataIndex: 'operations', slotName: 'operations', width: 150, align: 'center' }
]

// 数据和状态
const users = ref<any[]>([])
const subscriptionMap = ref<Record<number, any>>({})
const isLoading = ref(false)
const searchKey = ref('')
const successMessage = ref('')

// 对话框状态
const extendDialogVisible = ref(false)
const resetPasswordDialogVisible = ref(false)
const currentUser = ref<any>(null)

// 延期表单
const extendForm = reactive({
  type: 'days',
  amount: 1,
  reason: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  newPassword: '',
  confirmPassword: '',
  reason: ''
})

// 计算属性
const filteredUsers = computed(() => {
  if (!searchKey.value) {
    return users.value
  }
  const key = searchKey.value.toLowerCase()
  return users.value.filter(user =>
    user.username.toLowerCase().includes(key) ||
    user.email.toLowerCase().includes(key)
  )
})

// 获取用户列表
const loadUsers = async () => {
  isLoading.value = true
  try {
    // 临时虚拟数据用于演示（后续需要实现真正的 API）
    const mockUsers = [
      {
        id: 1,
        username: 'jianhua',
        email: '88066828@qq.com',
        role: 'admin',
        status: 'active',
        created_at: new Date().toISOString()
      }
    ]

    const mockSubscriptions: Record<number, any> = {
      1: {
        id: 1,
        user_id: 1,
        subscription_type: 'trial',
        expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
        created_at: new Date().toISOString()
      }
    }

    users.value = mockUsers
    subscriptionMap.value = mockSubscriptions

    console.log('✅ 已加载虚拟用户数据（演示用）')
  } catch (error: any) {
    Message.error(error.message || '获取用户列表失败')
  } finally {
    isLoading.value = false
  }
}

// 刷新用户列表
const refreshUsers = async () => {
  await loadUsers()
}

// 处理搜索
const handleSearch = () => {
  // 搜索已通过计算属性处理
}

// 打开延期对话框
const openExtendDialog = (user: any) => {
  currentUser.value = user
  extendForm.type = 'days'
  extendForm.amount = 1
  extendForm.reason = ''
  extendDialogVisible.value = true
}

// 打开重置密码对话框
const openResetPasswordDialog = (user: any) => {
  currentUser.value = user
  resetPasswordForm.newPassword = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordForm.reason = ''
  resetPasswordDialogVisible.value = true
}

// 处理延期
const handleExtend = async () => {
  try {
    if (!currentUser.value) return

    // 验证表单
    if (!extendForm.amount || extendForm.amount < 1) {
      Message.error('请输入有效的延期数量')
      return
    }

    if (extendForm.newPassword !== extendForm.confirmPassword) {
      Message.error('两次输入的密码不一致')
      return
    }

    // 调用 API（需要实现）
    // const result = await window.$mapi?.admin?.extendUserTime({
    //   userId: currentUser.value.id,
    //   days: calculateDays(extendForm.type, extendForm.amount),
    //   reason: extendForm.reason
    // })

    Message.success('已为用户延期')
    extendDialogVisible.value = false
    await refreshUsers()
  } catch (error: any) {
    Message.error(error.message || '延期失败')
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  try {
    if (!currentUser.value) return

    // 验证表单
    if (!resetPasswordForm.newPassword) {
      Message.error('请输入新密码')
      return
    }

    if (resetPasswordForm.newPassword !== resetPasswordForm.confirmPassword) {
      Message.error('两次输入的密码不一致')
      return
    }

    // 调用 API（需要实现）
    // const result = await window.$mapi?.admin?.resetUserPassword({
    //   userId: currentUser.value.id,
    //   newPassword: resetPasswordForm.newPassword,
    //   reason: resetPasswordForm.reason
    // })

    Message.success('已重置用户密码')
    resetPasswordDialogVisible.value = false
    await refreshUsers()
  } catch (error: any) {
    Message.error(error.message || '重置密码失败')
  }
}

// 辅助函数
const statusDisplay = (status: string): string => {
  const statusMap: Record<string, string> = {
    active: '活跃',
    inactive: '非活跃',
    suspended: '已禁用'
  }
  return statusMap[status] || status
}

const isSubscriptionExpired = (userId: number): boolean => {
  const subscription = subscriptionMap.value[userId]
  if (!subscription) return true
  const expiresAt = new Date(subscription.expires_at)
  return new Date() > expiresAt
}

const getRemainingDays = (userId: number): number => {
  const subscription = subscriptionMap.value[userId]
  if (!subscription) return 0
  const expiresAt = new Date(subscription.expires_at)
  const now = new Date()
  const diffTime = expiresAt.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays > 0 ? diffDays : 0
}

const formatDate = (dateStr: string): string => {
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN')
  } catch (error) {
    return dateStr
  }
}

const calculateNewExpireDate = (): string => {
  if (!currentUser.value || !subscriptionMap.value[currentUser.value.id]) {
    return ''
  }

  const subscription = subscriptionMap.value[currentUser.value.id]
  const currentDate = new Date(subscription.expires_at)

  if (extendForm.type === 'days') {
    currentDate.setDate(currentDate.getDate() + extendForm.amount)
  } else if (extendForm.type === 'months') {
    currentDate.setMonth(currentDate.getMonth() + extendForm.amount)
  } else if (extendForm.type === 'years') {
    currentDate.setFullYear(currentDate.getFullYear() + extendForm.amount)
  }

  return formatDate(currentDate.toISOString())
}

// 组件挂载
onMounted(async () => {
  await loadUsers()
})
</script>

<style scoped lang="less">
.user-management-container {
  padding: 16px;

  .search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }

  .subscription-info {
    p {
      margin: 4px 0;
      font-size: 13px;

      &:first-child {
        margin-top: 0;
      }
    }
  }
}
</style>
