import { historyDownload, historyList } from "../../utils/request"

type FilterKey = 'all' | 'done' | 'processing' | 'failed'
type RecordStatus = 'done' | 'processing' | 'failed'

interface HistoryRecord {
  id: number
  taskId: string
  title: string
  scene: string
  avatar: string
  time: string
  duration: string
  status: RecordStatus
  statusText: string
  secondaryText: string
  sceneClass: string
  isDone: boolean
  isProcessing: boolean
  isFailed: boolean
  coverUrl: string
  coverImage: string
  videoUrl: string
  progress: number
}

Page({
  data: {
    filters: [
      { key: 'all', label: '全部', active: true },
      { key: 'done', label: '已完成', active: false },
      { key: 'processing', label: '生成中', active: false },
    ],
    activeFilter: 'all' as FilterKey,
    records: [] as HistoryRecord[],
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false,
  },

  onLoad() {
    this.loadRecords(true)
  },

  onShow() {
    this.loadRecords(true)
  },

  onPullDownRefresh() {
    this.loadRecords(true).finally(() => wx.stopPullDownRefresh())
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadRecords(false)
    }
  },

  loadRecords(reset = false) {
    if (this.data.loading) return Promise.resolve()

    const page = reset ? 1 : this.data.page + 1
    this.setData({ loading: true })

    return historyList(this.data.activeFilter, page, this.data.limit).then((res: any) => {
      if (res.code) {
        wx.showModal({ title: '温馨提示', content: res.message, showCancel: false })
        return
      }

      const list = (res.data.list as HistoryRecord[]).map((item) => ({
        ...item,
        coverImage: item.coverUrl
      }))
      this.setData({
        records: reset ? list : this.data.records.concat(list),
        page,
        hasMore: res.data.hasMore,
      })
    }).catch(() => {
      wx.showModal({ title: '温馨提示', content: '网络异常，请稍后再试', showCancel: false })
    }).finally(() => {
      this.setData({ loading: false })
    })
  },

  handleBack() {
    wx.navigateBack({
      fail: () => wx.switchTab({ url: '/pages/index/index' }),
    })
  },

  handleFilterTap(e: WechatMiniprogram.TouchEvent) {
    const activeFilter = e.currentTarget.dataset.key as FilterKey
    this.setData({
      activeFilter,
      filters: this.data.filters.map((item) => ({
        ...item,
        active: item.key === activeFilter,
      })),
    })
    this.loadRecords(true)
  },

  handleFailedTap() {
    this.setData({
      activeFilter: 'failed',
      filters: this.data.filters.map((item) => ({ ...item, active: false })),
    })
    this.loadRecords(true)
  },

  handleDetail(e: WechatMiniprogram.TouchEvent) {
    const rawStatus = String(e.currentTarget.dataset.status || '')
    const taskId = String(e.currentTarget.dataset.taskId || '')
    if (!taskId) return

    const status = rawStatus === 'failed' ? 'failed' : rawStatus === 'processing' ? 'processing' : 'done'
    wx.navigateTo({
      url: '/pages/historyPackage/historyDetail/index?status=' + status + '&taskId=' + encodeURIComponent(taskId),
    })
  },

  handleDownload(e: WechatMiniprogram.TouchEvent) {
    const taskId = String(e.currentTarget.dataset.taskId || '')
    if (!taskId) return

    wx.showLoading({ title: '获取下载地址' })
    historyDownload(taskId).then((res: any) => {
      wx.hideLoading()
      if (res.code) {
        wx.showModal({ title: '温馨提示', content: res.message || '下载失败', showCancel: false })
        return
      }

      const url = res.data.url
      if (url) {
        wx.setClipboardData({ data: url })
      } else {
        wx.showToast({ title: '暂无下载地址', icon: 'none' })
      }
    }).catch(() => {
      wx.hideLoading()
      wx.showModal({ title: '温馨提示', content: '网络异常，请稍后再试', showCancel: false })
    })
  },

  handleMore(e: WechatMiniprogram.TouchEvent) {
    this.handleDetail(e)
  },

  handleRetry() {
    wx.switchTab({ url: '/pages/index/index' })
  },
})

