import { historyCancel, historyDelete, historyDetail, historyDownload } from "../../../utils/request"

type DetailStatus = 'done' | 'processing' | 'failed'

const emptyDetail = {
  taskId: '',
  title: '',
  status: 'done',
  statusText: '',
  progress: 0,
  pageTitle: '作品详情',
  pageClass: 'success-page',
  videoUrl: '',
  coverUrl: '',
  duration: '',
  createTime: '',
  finishTime: '',
  failureTime: '',
  failureStage: '',
  failureReason: '',
  scriptText: '',
  avatar: { name: '默认数字人', imageUrl: '' },
  voice: { name: '默认音色', audioUrl: '' },
  background: { name: '默认背景', coverUrl: '', imageUrl: '' },
  steps: [] as any[],
  avatarImage: '/static/images/my/image.png',
  backgroundImage: '/static/images/my/image.png',
  videoCover: '/static/images/my/image.png',
  failureMessage: '生成失败，请稍后重试',
  failureDisplayTime: '',
  successTime: '',
  taskDisplayId: '',
  scriptDisplayText: '暂无文案',
}

Page({
  data: {
    status: 'done' as DetailStatus,
    isFailed: false,
    isProcessing: false,
    pageTitle: '作品详情',
    pageClass: 'success-page',
    taskId: '',
    detail: emptyDetail as any,
    progressStyle: 'width: 0%;',
  },

  onLoad(query: Record<string, string | undefined>) {
    const status: DetailStatus = query.status === 'failed'
      ? 'failed'
      : query.status === 'processing'
        ? 'processing'
        : 'done'

    this.setStatus(status, query.taskId || '')
    if (query.taskId) {
      this.loadDetail(query.taskId)
    }
  },

  loadDetail(taskId: string) {
    wx.showLoading({ title: '加载中' })
    historyDetail(taskId).then((res: any) => {
      wx.hideLoading()
      if (res.code) {
        wx.showModal({ title: '温馨提示', content: res.message || '获取详情失败', showCancel: false })
        return
      }

      const data = res.data || {}
      const detail = { ...emptyDetail, ...data }
      detail.avatar = { ...emptyDetail.avatar, ...(data.avatar || {}) }
      detail.voice = { ...emptyDetail.voice, ...(data.voice || {}) }
      detail.background = { ...emptyDetail.background, ...(data.background || {}) }
      detail.avatarImage = detail.avatar.imageUrl || '/static/images/my/image.png'
      detail.backgroundImage = detail.background.coverUrl || detail.background.imageUrl || '/static/images/my/image.png'
      detail.videoCover = detail.coverUrl || detail.avatar.imageUrl || '/static/images/my/image.png'
      detail.failureMessage = detail.failureReason || '生成失败，请稍后重试'
      detail.failureDisplayTime = detail.failureTime || detail.finishTime || detail.createTime
      detail.successTime = detail.finishTime || detail.createTime
      detail.taskDisplayId = detail.taskId || taskId
      detail.scriptDisplayText = detail.scriptText || '暂无文案';

      let status = '';
      if (detail.status === 'failed') {
        status = 'failed';
      } else {
        status = detail.status === 'processing' ? 'processing' : 'done';
      }
      this.setData({
        detail,
        progressStyle: 'width: ' + Math.max(0, Math.min(100, Number(+detail.progress))) + '%;',
      })
      this.setStatus(status as DetailStatus, detail.taskId || taskId)
    }).catch(() => {
      wx.hideLoading()
      wx.showModal({ title: '温馨提示', content: '网络异常，请稍后再试', showCancel: false })
    })
  },

  setStatus(status: DetailStatus, taskId: string) {
    this.setData({
      status,
      isFailed: status === 'failed',
      isProcessing: status === 'processing',
      pageTitle: status === 'failed' ? '失败详情' : status === 'processing' ? '生成详情' : '作品详情',
      pageClass: status === 'failed' ? 'failed-page' : status === 'processing' ? 'processing-page' : 'success-page',
      taskId,
    })
  },

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

  handleDownload() {
    if (!this.data.taskId) return

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

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

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

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

  handleViewCopy() {
    this.handleCopyText()
  },

  handleCopyText() {
    const detail = this.data.detail || {}
    const text = detail.scriptText || ''
    if (!text) {
      wx.showToast({ title: '暂无文案', icon: 'none' })
      return
    }
    wx.setClipboardData({ data: text })
  },

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

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

  handleBackToHistory() {
    wx.switchTab({ url: '/pages/history/history' })
  },

  handleCancel() {
    if (!this.data.taskId) return

    wx.showModal({
      title: '确认取消',
      content: '确定取消当前生成任务吗？',
      success: (modal) => {
        if (!modal.confirm) return
        historyCancel(this.data.taskId).then((res: any) => {
          if (res.code) {
            wx.showModal({ title: '温馨提示', content: res.message || '取消失败', showCancel: false })
            return
          }
          wx.showToast({ title: '已取消', icon: 'success' })
          this.loadDetail(this.data.taskId)
        })
      },
    })
  },

  handleDelete() {
    if (!this.data.taskId) return

    wx.showModal({
      title: '确认删除',
      content: '删除后将不再展示该创作记录',
      success: (modal) => {
        if (!modal.confirm) return
        historyDelete(this.data.taskId).then((res: any) => {
          if (res.code) {
            wx.showModal({ title: '温馨提示', content: res.message || '删除失败', showCancel: false })
            return
          }
          wx.showToast({ title: '已删除', icon: 'success' })
          setTimeout(() => this.handleBackToHistory(), 400)
        })
      },
    })
  },
})



