/* AI_CHANGELOG
| 日期 | Prompt | 变更 |
|------|--------|------|
| 2026-03-23 | 角色路由+页面权限守卫 | onShow 添加 checkPageAccess 权限守卫 |
*/
import { checkPageAccess } from '../../utils/auth-guard'
import { fetchChatHistory } from '../../services/api'
import { formatRelativeTime } from '../../utils/time'

/** VI 规范 §6.2：AI 图标配色系统（6种） */
const ICON_GRADIENTS = [
  'linear-gradient(135deg, #667eea 0%, #4a5fc7 100%)', // indigo
  'linear-gradient(135deg, #764ba2 0%, #5b3080 100%)', // purple
  'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)', // red
  'linear-gradient(135deg, #e67e22 0%, #ca6c17 100%)', // orange
  'linear-gradient(135deg, #d4a017 0%, #b8860b 100%)', // yellow
  'linear-gradient(135deg, #2980b9 0%, #1a5276 100%)', // blue
]

/** 带展示标签的对话历史项 */
interface ChatHistoryDisplay {
  id: string
  title: string
  lastMessage: string
  timestamp: string
  customerName?: string
  /** 格式化后的时间标签 */
  timeLabel: string
  /** 图标背景渐变（VI §6.2 AI 图标配色，每条随机） */
  iconGradient: string
}

Page({
  data: {
    /** 页面状态：loading / empty / normal / error */
    pageState: 'loading' as 'loading' | 'empty' | 'normal' | 'error',
    /** 状态栏高度 */
    statusBarHeight: 0,
    /** 对话历史列表 */
    list: [] as ChatHistoryDisplay[],
  },

  onLoad() {
    const sysInfo = wx.getWindowInfo()
    this.setData({ statusBarHeight: sysInfo.statusBarHeight || 44 })
    this.loadData()
  },

  onShow() {
    // 权限守卫：检查登录状态、账号禁用、角色权限
    checkPageAccess('pages/chat-history/chat-history')
  },

  /** 加载数据 */
  async loadData() {
    this.setData({ pageState: 'loading' })
    wx.showLoading({ title: '加载中...', mask: true })

    try {
      const res = await fetchChatHistory()
      const list: ChatHistoryDisplay[] = (res.items || []).map((item: any) => ({
        id: String(item.id),
        title: item.title || '',
        lastMessage: item.lastMessage || '',
        timestamp: item.timestamp || '',
        customerName: item.customerName,
        timeLabel: formatRelativeTime(item.timestamp),
        iconGradient: ICON_GRADIENTS[Math.floor(Math.random() * ICON_GRADIENTS.length)],
      }))

      this.setData({
        list,
        pageState: list.length === 0 ? 'empty' : 'normal',
      })
    } catch {
      this.setData({ pageState: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  /** 返回上一页 */
  onBack() {
    wx.navigateBack()
  },

  /** 重试加载 */
  onRetry() {
    this.loadData()
  },

  /** 点击对话记录 → 跳转 chat 页面 */
  onItemTap(e: WechatMiniprogram.TouchEvent) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({ url: '/pages/chat/chat?historyId=' + id })
  },

  /** 下拉刷新 */
  async onPullDownRefresh() {
    await this.loadData()
    wx.stopPullDownRefresh()
  },
})
