import { backgroundTemplates, updateTaskBackground } from "../../../utils/request"

type Category = {
  id: string
  name: string
}

type BgTemplate = {
  id: number
  name: string
  scene: string
  category: string
  coverUrl?: string
  imageUrl?: string
  videoUrl?: string
  isRecommend?: number
}

function filterTemplates(category: string, templates: BgTemplate[]) {
  if (category === 'all') return templates
  return templates.filter((item) => item.category === category)
}

Page({
  data: {
    taskId: '',
    categories: [] as Category[],
    activeCategory: 'all',
    selectedTemplate: 0,
    allTemplates: [] as BgTemplate[],
    templates: [] as BgTemplate[],
    loading: false,
  },

  onLoad(options: any) {
    this.setData({ taskId: options.taskId || options.taskid || '' })
    this.loadBackgroundTemplates()
  },

  loadBackgroundTemplates() {
    this.setData({ loading: true })
    backgroundTemplates().then((res: any) => {
      const categories = res && !res.code && res.data ? (res.data.categories || []) : []
      const templates = res && !res.code && res.data ? (res.data.templates || []) : []
      const selectedTemplate = templates.length ? Number(templates[0].id) : 0
      this.setData({
        categories,
        allTemplates: templates,
        templates: filterTemplates(this.data.activeCategory, templates),
        selectedTemplate,
        loading: false,
      })
    }).catch(() => {
      this.setData({ loading: false })
      wx.showModal({ title: '温馨提示', content: '背景模板加载失败，请稍后再试', showCancel: false })
    })
  },

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

  handleCategorySelect(e: WechatMiniprogram.TouchEvent) {
    const activeCategory = e.currentTarget.dataset.id
    if (!activeCategory) return

    const templates = filterTemplates(activeCategory, this.data.allTemplates)
    this.setData({ activeCategory, templates })
  },

  handleTemplateSelect(e: WechatMiniprogram.TouchEvent) {
    const selectedTemplate = Number(e.currentTarget.dataset.id || 0)
    if (selectedTemplate <= 0) return

    this.setData({ selectedTemplate })
  },

  handleConfirm() {
    if (!this.data.taskId) {
      wx.showModal({ title: '温馨提示', content: '创作记录不存在', showCancel: false })
      return
    }
    if (this.data.selectedTemplate <= 0) {
      wx.showModal({ title: '温馨提示', content: '请选择背景模板', showCancel: false })
      return
    }

    wx.showLoading({ mask: true, title: '保存背景中' })
    updateTaskBackground(this.data.taskId, this.data.selectedTemplate).then((res: any) => {
      wx.hideLoading()
      if (!res.code) {
        wx.redirectTo({ url: '/pages/aiPackage/gen/index?taskId=' + encodeURIComponent(this.data.taskId) })
      } else {
        wx.showModal({ title: '温馨提示', content: res.message || '背景保存失败', showCancel: false })
      }
    }).catch(() => {
      wx.hideLoading()
      wx.showModal({ title: '温馨提示', content: '网络异常，请稍后再试', showCancel: false })
    })
  },
})
