import type { AdminRole } from '../../auth/roles'

export type DemoKpi = {
  label: string
  value: number
  status: string
  hint: string
}

export type DemoActivity = {
  id: number
  name: string
  description: string
  startTime: string
  endTime: string
  participants: number
  status: string
  config: {
    audience: string
    conversion: string
    reward: string
    budget: string
  }
  metrics: {
    visits: number
    shares: number
    conversions: number
    budgetUsed: number
  }
}

export type DemoAlert = {
  title: string
  detail: string
}

export type DemoUser = {
  id: string
  name: string
  email: string
  role: AdminRole
  status: '正常' | '冻结'
  managerName: string
}

export type DemoInvite = {
  id: string
  email: string
  role: AdminRole
  status: '待接受' | '已接受' | '已拒绝' | '已过期'
  invitedAt: string
  acceptedAt?: string
  expiredAt?: string
}

export type DemoReward = {
  id: string
  userName: string
  points: number
  status: string
  issuedAt: string
  batchId: string
  batchStatus: string
  note?: string
}

export type DemoRiskItem = {
  id: string
  type: string
  target: string
  status: string
  updatedAt: string
}

export type DemoRiskAlert = {
  id: string
  title: string
  detail: string
  status: '未处理' | '处理中' | '已关闭'
  updatedAt: string
}

export type DemoAuditLog = {
  id: string
  actor: string
  action: string
  resource: string
  createdAt: string
}

export type DemoNotification = {
  id: string
  title: string
  detail: string
  read: boolean
  createdAt: string
}

export type DemoNotificationInput = {
  title: string
  content: string
}

export type DemoRoleRequest = {
  id: string
  userId: string
  currentRole: AdminRole
  targetRole: AdminRole
  reason: string
  status: '待审批' | '已通过' | '已拒绝'
  requestedAt: string
}

export type DemoConfig = {
  key: string
  value: string
  description: string
}

const now = new Date()
const isoDays = (offset: number) => new Date(now.getTime() + offset * 86400000).toISOString()

const demoActivities: DemoActivity[] = [
  {
    id: 1,
    name: '裂变增长计划',
    description: '邀请好友注册，获取双倍奖励。',
    startTime: isoDays(-7),
    endTime: isoDays(21),
    participants: 1280,
    status: '进行中',
    config: {
      audience: '新注册用户与邀请达人',
      conversion: '完成注册并绑定手机号',
      reward: '每邀请 1 人奖励 20 积分',
      budget: '总预算 50,000 积分'
    },
    metrics: {
      visits: 48210,
      shares: 12800,
      conversions: 3840,
      budgetUsed: 32000
    }
  },
  {
    id: 2,
    name: '新用户召回活动',
    description: '召回沉默用户，提升活跃度。',
    startTime: isoDays(-21),
    endTime: isoDays(-2),
    participants: 640,
    status: '已结束',
    config: {
      audience: '30 天未登录用户',
      conversion: '完成首次分享',
      reward: '每邀请 1 人奖励 10 积分',
      budget: '总预算 20,000 积分'
    },
    metrics: {
      visits: 18200,
      shares: 6200,
      conversions: 1200,
      budgetUsed: 15000
    }
  }
]

const demoKpis: DemoKpi[] = [
  { label: '访问', value: 48210, status: '已同步', hint: '近 7 天访问次数' },
  { label: '分享', value: 12800, status: '已同步', hint: '累计分享次数' },
  { label: '转化', value: 3840, status: '已同步', hint: '累计转化人数' },
  { label: '新增', value: 920, status: '已同步', hint: '新增访问用户' }
]

const demoAlerts: DemoAlert[] = [
  { title: '回调失败率升高', detail: '最近 1 小时失败率 3.2%，建议检查回调服务。' }
]

const demoUsers: DemoUser[] = [
  { id: 'u-1001', name: '王晨', email: 'wangchen@demo.com', role: 'operation_manager', status: '正常', managerName: '演示管理员' },
  { id: 'u-1002', name: '李雪', email: 'lixue@demo.com', role: 'operation_specialist', status: '正常', managerName: '演示管理员' },
  { id: 'u-1003', name: '周宁', email: 'zhouning@demo.com', role: 'viewer', status: '冻结', managerName: '王晨' }
]

const demoRewards: DemoReward[] = [
  { id: 'r-2001', userName: '王晨', points: 120, status: '已发放', issuedAt: isoDays(-1), batchId: 'batch-01', batchStatus: '已完成' },
  { id: 'r-2002', userName: '李雪', points: 80, status: '待发放', issuedAt: isoDays(0), batchId: 'batch-02', batchStatus: '排队中' },
  { id: 'r-2003', userName: '周宁', points: 50, status: '发放失败', issuedAt: isoDays(-2), batchId: 'batch-02', batchStatus: '异常' }
]

const demoRiskItems: DemoRiskItem[] = [
  { id: 'risk-1', type: '黑名单', target: '138****1234', status: '生效', updatedAt: isoDays(-2) },
  { id: 'risk-2', type: '异常转化', target: 'IP: 10.10.2.24', status: '待核查', updatedAt: isoDays(-1) }
]

const demoRiskAlerts: DemoRiskAlert[] = [
  { id: 'alert-1', title: '回调失败率升高', detail: '最近 1 小时失败率 3.2%，建议检查回调服务。', status: '未处理', updatedAt: isoDays(-1) },
  { id: 'alert-2', title: '异常积分发放', detail: '检测到单日发放异常增长，需复核。', status: '处理中', updatedAt: isoDays(-2) }
]

const demoAuditLogs: DemoAuditLog[] = [
  { id: 'audit-1', actor: '演示管理员', action: '更新活动', resource: '活动 #1', createdAt: isoDays(-1) },
  { id: 'audit-2', actor: '演示管理员', action: '调整奖励规则', resource: '奖励方案 A', createdAt: isoDays(-3) }
]

const demoNotifications: DemoNotification[] = [
  { id: 'notice-1', title: '活动即将结束', detail: '裂变增长计划 3 天后结束', read: false, createdAt: isoDays(-1) },
  { id: 'notice-2', title: '回调异常提醒', detail: '请检查回调配置与重试策略', read: true, createdAt: isoDays(-4) }
]

const demoConfig: DemoConfig[] = [
  { key: 'callback.retry.max', value: '3', description: '回调最大重试次数' },
  { key: 'reward.batch.size', value: '200', description: '奖励批量发放大小' }
]

export const demoDataService = {
  async getDashboard() {
    return {
      updatedAt: now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
      kpis: demoKpis,
      activities: demoActivities,
      alerts: demoAlerts
    }
  },
  async getActivities(params?: {
    page?: number
    size?: number
    status?: string
    keyword?: string
    startDate?: string
    endDate?: string
  }) {
    const page = params?.page ?? 0
    const size = params?.size ?? 6
    let filtered = [...demoActivities]

    // 本地筛选
    if (params?.status) {
      filtered = filtered.filter(a => a.status === params.status)
    }
    if (params?.keyword) {
      const kw = params.keyword.toLowerCase()
      filtered = filtered.filter(a => a.name.toLowerCase().includes(kw))
    }

    const start = page * size
    const items = filtered.slice(start, start + size)
    return {
      items,
      total: filtered.length,
      page: page + 1,
      size
    }
  },
  async getActivityById(id: number) {
    return demoActivities.find((item) => item.id === id) ?? null
  },

  // 获取活动参与者列表（Demo 模式）
  async getActivityParticipants(_activityId: number, _page = 0, _size = 1000) {
    // 返回模拟的参与者数据
    return [
      { id: 1, inviterUserId: 101, inviteeUserId: 102, email: 'user1@demo.com', status: '已完成', invitedAt: isoDays(-1) },
      { id: 2, inviterUserId: 101, inviteeUserId: 103, email: 'user2@demo.com', status: '已完成', invitedAt: isoDays(-2) },
      { id: 3, inviterUserId: 102, inviteeUserId: 104, email: 'user3@demo.com', status: '待确认', invitedAt: isoDays(0) }
    ]
  },

  // 获取活动奖励明细（Demo 模式）
  async getActivityRewards(_activityId: number) {
    // 返回模拟的奖励数据
    return [
      { userId: 101, userName: '用户A', points: 20, status: '已发放', issuedAt: isoDays(-1) },
      { userId: 102, userName: '用户B', points: 30, status: '已发放', issuedAt: isoDays(-2) },
      { userId: 103, userName: '用户C', points: 15, status: '待发放', issuedAt: isoDays(0) }
    ]
  },

  // 导出活动参与者 CSV
  async exportActivityParticipants(activityId: number) {
    const participants = await this.getActivityParticipants(activityId)
    const headers = ['用户ID', '邮箱', '状态', '邀请时间']
    const rows = participants.map((p: any) => [
      p.inviterUserId || '',
      p.email || '',
      p.status || '',
      p.invitedAt ? new Date(p.invitedAt).toLocaleString('zh-CN') : ''
    ])
    return { headers, rows }
  },

  // 导出活动奖励 CSV
  async exportActivityRewards(activityId: number) {
    const rewards = await this.getActivityRewards(activityId)
    const headers = ['用户', '积分', '状态', '发放时间']
    const rows = rewards.map((r: any) => [
      r.userName || r.userId || '',
      r.points || '',
      r.status || '',
      r.issuedAt ? new Date(r.issuedAt).toLocaleString('zh-CN') : ''
    ])
    return { headers, rows }
  },

  async getUsers() {
    return demoUsers
  },

  // 获取用户分页列表（演示模式）
  async getUsersPage(params?: {
    page?: number
    size?: number
    keyword?: string
    status?: string
  }) {
    const page = params?.page ?? 0
    const size = params?.size ?? 6
    let filtered = [...demoUsers]

    // 本地筛选
    if (params?.keyword) {
      const kw = params.keyword.toLowerCase()
      filtered = filtered.filter(u =>
        u.name.toLowerCase().includes(kw) ||
        u.email.toLowerCase().includes(kw)
      )
    }
    if (params?.status) {
      filtered = filtered.filter(u => u.status === params.status)
    }

    const start = page * size
    const items = filtered.slice(start, start + size)
    return {
      items,
      total: filtered.length,
      page: page + 1,
      size
    }
  },
  async getInvites(): Promise<DemoInvite[]> {
    return [
      {
        id: 'invite-1',
        email: 'newuser@demo.com',
        role: 'operation_manager',
        status: '待接受',
        invitedAt: isoDays(-1)
      },
      {
        id: 'invite-2',
        email: 'expired@demo.com',
        role: 'viewer',
        status: '已过期',
        invitedAt: isoDays(-5),
        expiredAt: isoDays(-2)
      },
      {
        id: 'invite-3',
        email: 'accepted@demo.com',
        role: 'super_admin',
        status: '已接受',
        invitedAt: isoDays(-6),
        acceptedAt: isoDays(-4)
      }
    ]
  },
  async getRoleRequests(): Promise<DemoRoleRequest[]> {
    return [
      {
        id: 'role-1',
        userId: 'u-1002',
        currentRole: 'operation_specialist',
        targetRole: 'operation_manager',
        reason: '需要管理活动权限',
        status: '待审批',
        requestedAt: isoDays(-2)
      }
    ]
  },
  async getRewards() {
    return demoRewards
  },
  // 演示模式下的奖励操作（本地状态变更）
  async grantReward(_id: number) {
    return true
  },
  async cancelReward(_id: number, _reason: string) {
    return true
  },
  async exportRewards(_params?: { status?: string; rewardType?: string; startDate?: string; endDate?: string }) {
    // 演示模式返回空Blob
    return new Blob([''], { type: 'text/csv' })
  },
  async batchGrantRewards(_ids: number[]) {
    return true
  },
  async getRiskItems() {
    return demoRiskItems
  },
  async getRiskAlerts() {
    return demoRiskAlerts
  },
  async getAuditLogs() {
    return demoAuditLogs
  },
  async getNotifications() {
    return demoNotifications
  },
  async addNotification(payload: DemoNotificationInput) {
    const item: DemoNotification = {
      id: `notice-${Date.now()}`,
      title: payload.title,
      detail: payload.content,
      read: false,
      createdAt: new Date().toISOString()
    }
    demoNotifications.unshift(item)
    return item
  },
  // 演示态审批处理方法
  async handleApproval(_recordId: string, _action: string, _comment?: string) {
    console.log('[Demo] 处理审批 (无实际效果)')
    return true
  },
  // 演示态批量审批处理方法
  async batchHandleApproval(_recordIds: string[], _action: string, _comment?: string) {
    console.log('[Demo] 批量处理审批 (无实际效果)')
    return { successCount: _recordIds.length, failCount: 0, results: [] }
  },
  // 演示态审批转交方法
  async transferApproval(_recordId: string, _transferTo: string, _comment?: string) {
    console.log('[Demo] 转交审批 (无实际效果)')
    return true
  },
  // 演示态审批委托方法
  async delegateApproval(_recordId: string, _delegateTo: string, _reason?: string) {
    console.log('[Demo] 委托审批 (无实际效果)')
    return true
  },
  async getConfig() {
    return demoConfig
  },
  async getInvitedFriends(_activityId: number, _userId: number, _page: number, _size: number) {
    return [
      { nickname: '邀请用户 A', maskedPhone: '138****1024', status: '已注册' },
      { nickname: '邀请用户 B', maskedPhone: '139****2048', status: '未注册' }
    ]
  },

  // 演示态邀请管理方法（向后兼容）
  async createInvite(_email: string, _role: string) {
    console.log('[Demo] 创建邀请')
    return { id: 'demo-' + Date.now() }
  },
  async deleteInvite(_id: number | string) {
    console.log('[Demo] 删除邀请', _id)
    return true
  },
  async resendInvite(_id: number | string) {
    console.log('[Demo] 重发邀请', _id)
    return true
  },
  async expireInvite(_id: number | string) {
    console.log('[Demo] 设置邀请过期', _id)
    return true
  },

  // ========== 带分页的方法（演示态） ==========

  async getRewardsPage(_page: number, _size: number) {
    return { items: demoRewards, total: demoRewards.length, page: 1, size: 10 }
  },

  async getRiskAlertsPage(_page: number, _size: number) {
    return { items: demoRiskAlerts, total: demoRiskAlerts.length, page: 1, size: 10 }
  },

  async getAuditLogsPage(_page: number, _size: number) {
    return { items: demoAuditLogs, total: demoAuditLogs.length, page: 1, size: 10 }
  },

  async getNotificationsPage(_page: number, _size: number) {
    return { items: demoNotifications, total: demoNotifications.length, page: 1, size: 10 }
  },

  async markNotificationRead(_id: number) {
    console.log('[Demo] 标记通知已读', _id)
    return true
  },

  async markAllNotificationsRead() {
    console.log('[Demo] 标记全部通知已读')
    demoNotifications.forEach(n => n.read = true)
    return true
  },

  async batchMarkNotificationsRead(_ids: number[]) {
    console.log('[Demo] 批量标记通知已读', _ids)
    return true
  },

  async exportAuditLogs(_keyword?: string, _operation?: string, _user?: string) {
    console.log('[Demo] 导出审计日志')
    // 返回一个模拟的blob
    const csvContent = '操作人,动作,资源,时间\n' +
      demoAuditLogs.map(log =>
        `${log.actor},${log.action},${log.resource},${log.createdAt}`
      ).join('\n')
    const blob = new Blob([csvContent], { type: 'text/csv' })
    return blob
  },

  // ========== 风控规则 CRUD (Demo 模式) ==========
  async createRiskRule(rule: { type: string; target: string; status: string }) {
    console.log('[Demo] 创建风控规则', rule)
    const newRule = {
      id: `risk-${Date.now()}`,
      ...rule,
      updatedAt: new Date().toISOString()
    }
    demoRiskItems.push(newRule as any)
    return newRule
  },

  async updateRiskRule(id: string, rule: { type: string; target: string; status: string }) {
    console.log('[Demo] 更新风控规则', id, rule)
    const index = demoRiskItems.findIndex((r: any) => r.id === id)
    if (index >= 0) {
      demoRiskItems[index] = { ...demoRiskItems[index], ...rule, updatedAt: new Date().toISOString() }
    }
    return true
  },

  async toggleRiskRule(id: string) {
    console.log('[Demo] 切换风控规则状态', id)
    const item = demoRiskItems.find((r: any) => r.id === id)
    if (item) {
      item.status = item.status === '生效' ? '暂停' : '生效'
      item.updatedAt = new Date().toISOString()
    }
    return true
  },

  async handleRiskAlert(id: string, action: 'handle' | 'close') {
    console.log('[Demo] 处理风险告警', id, action)
    const alert = demoRiskAlerts.find((a: any) => a.id === id)
    if (alert) {
      if (action === 'handle') {
        alert.status = '处理中'
      } else {
        alert.status = '已关闭'
      }
      alert.updatedAt = new Date().toISOString()
    }
    return true
  },

  async batchHandleRiskAlerts(ids: string[]) {
    console.log('[Demo] 批量处理风险告警', ids)
    ids.forEach(id => {
      const alert = demoRiskAlerts.find((a: any) => a.id === id)
      if (alert && alert.status !== '已关闭') {
        alert.status = '处理中'
        alert.updatedAt = new Date().toISOString()
      }
    })
    return true
  },

  // ========== 审批中心 ==========
  async getProcessedApprovals(params?: {
    page?: number
    size?: number
    keyword?: string
  }) {
    console.log('[Demo] 获取已审批记录', params)
    return { items: [], total: 0, page: 1, size: 10 }
  },

  async getMyApprovals(params?: {
    page?: number
    size?: number
    keyword?: string
  }) {
    console.log('[Demo] 获取我提交的审批', params)
    return { items: [], total: 0, page: 1, size: 10 }
  }
}
