Page({
  data: {
    generating: false, // 是否正在生成海报
    currentPoster: null, // 当前选中的海报模板
    currentGoods: null, // 当前选中的商品
    customText: '', // 自定义文案
    showGoodsSelect: false, // 是否显示商品选择
    showCustomText: false, // 是否显示自定义文案
    posterList: [
      {
        id: '1',
        name: '模板一',
        url: '/static/images/poster-1.jpg',
        type: 'goods' // 商品海报
      },
      {
        id: '2',
        name: '模板二',
        url: '/static/images/poster-2.jpg',
        type: 'profile' // 个人名片
      },
      {
        id: '3',
        name: '模板三',
        url: '/static/images/poster-3.jpg',
        type: 'custom' // 自定义海报
      }
    ],
    goodsList: [
      {
        id: '1',
        name: '商品名称商品名称商品名称',
        price: '99.00',
        image: '/static/images/goods-1.jpg'
      },
      {
        id: '2',
        name: '商品名称2',
        price: '199.00',
        image: '/static/images/goods-2.jpg'
      },
      {
        id: '3',
        name: '商品名称3',
        price: '299.00',
        image: '/static/images/goods-3.jpg'
      }
    ]
  },

  onLoad() {
    // 设置默认选中第一个模板
    this.setData({
      currentPoster: this.data.posterList[0]
    })
    this.checkTemplateType(this.data.posterList[0])
  },

  // 选择海报模板
  selectTemplate(e) {
    const id = e.currentTarget.dataset.id
    const poster = this.data.posterList.find(item => item.id === id)
    this.setData({ currentPoster: poster })
    this.checkTemplateType(poster)
  },

  // 检查模板类型,显示对应的选项
  checkTemplateType(poster) {
    this.setData({
      showGoodsSelect: poster.type === 'goods',
      showCustomText: poster.type === 'custom'
    })
  },

  // 选择商品
  selectGoods(e) {
    const id = e.currentTarget.dataset.id
    const goods = this.data.goodsList.find(item => item.id === id)
    this.setData({ currentGoods: goods })
    this.generatePoster()
  },

  // 文案输入
  onTextChange(e) {
    this.setData({
      customText: e.detail.value
    })
    this.generatePoster()
  },

  // 生成海报
  generatePoster() {
    if (this.data.generating) return

    this.setData({ generating: true })

    // TODO: 调用后端API生成海报
    setTimeout(() => {
      this.setData({ generating: false })
    }, 1500)
  },

  // 预览海报
  previewPoster() {
    if (!this.data.currentPoster) return
    wx.previewImage({
      urls: [this.data.currentPoster.url]
    })
  },

  // 保存海报
  savePoster() {
    if (!this.data.currentPoster) {
      return wx.showToast({
        title: '请先生成海报',
        icon: 'none'
      })
    }

    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.saveImage()
            },
            fail: () => {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存图片到相册',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        } else {
          this.saveImage()
        }
      }
    })
  },

  // 保存图片到相册
  saveImage() {
    wx.showLoading({
      title: '保存中...'
    })

    wx.downloadFile({
      url: this.data.currentPoster.url,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            })
          },
          fail: () => {
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        })
      },
      fail: () => {
        wx.showToast({
          title: '图片下载失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  onShareAppMessage() {
    return {
      title: '邀请你加入分销团队',
      path: '/pages/index/index?inviter=' + wx.getStorageSync('distributionId'),
      imageUrl: this.data.currentPoster?.url || '/static/images/share.jpg'
    }
  }
})