const versionUtils = require('../../utils/version')
const versionConfig = require('../../config/version')

Page({
  data: {
    currentVersion: '',
    versionName: '',
    versionList: [],
    categoryList: [],
    isV2OrAbove: false,
    useNewUI: false
  },

  onLoad() {
    this.loadVersionInfo()
  },

  onShow() {
    this.loadVersionInfo()
  },

  loadVersionInfo() {
    const currentVersion = versionUtils.getCurrentVersion()
    const versionInfo = versionUtils.getVersionInfo()
    const allVersions = versionConfig.getAllVersions()
    const categoryList = versionUtils.getCategoryList()
    const isV2OrAbove = versionUtils.isV2OrAbove()
    const useNewUI = versionUtils.getFeatureFlag('useNewUI')

    const versionList = allVersions.map(v => {
      const info = versionConfig.getVersionInfo(v)
      return {
        version: v,
        name: info ? info.name : v,
        description: info ? info.description : ''
      }
    })

    this.setData({
      currentVersion,
      versionName: versionInfo ? versionInfo.name : '',
      versionList,
      categoryList,
      isV2OrAbove,
      useNewUI
    })

    versionUtils.logVersionInfo()
  },

  switchVersion(e) {
    const { version } = e.currentTarget.dataset

    if (version === this.data.currentVersion) {
      wx.showToast({ title: '已是该版本', icon: 'none' })
      return
    }

    wx.showModal({
      title: '切换版本',
      content: `确定要切换到 ${version} 版本吗？切换后页面将重新加载。`,
      confirmColor: '#b06ab3',
      success: (res) => {
        if (res.confirm) {
          this.doSwitchVersion(version)
        }
      }
    })
  },

  doSwitchVersion(version) {
    wx.showLoading({ title: '切换中...' })

    try {
      const allVersions = versionConfig.getAllVersions()

      if (allVersions.includes(version)) {
        wx.setStorageSync('debugVersion', version)
        console.log(`[VersionDebug] 切换到版本: ${version}`)

        setTimeout(() => {
          wx.hideLoading()
          wx.showToast({ title: '切换成功', icon: 'success' })

          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/version-debug/version-debug'
            })
          }, 1000)
        }, 500)
      } else {
        wx.hideLoading()
        wx.showToast({ title: '版本不存在', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      console.error('切换版本失败', err)
      wx.showToast({ title: '切换失败', icon: 'none' })
    }
  },

  onShareAppMessage() {
    return {
      title: '版本调试工具',
      path: '/pages/version-debug/version-debug'
    }
  }
})
