// pages/bot-list/bot-list.js
const app = getApp();

Page({
  data: {
    botList: [],
    statusText: {
      normal: '状态正常',
      abnormal: '状态异常',
      full: '已满人'
    },
    showQrModal: false,
    selectedBot: null,
    loading: true,
    refreshing: false,
    error: null,
    refreshTimer: null,
    lastUpdateTime: 0,
    lastUpdateTimeText: ''
  },

  onLoad() {
    this.loadBotData();
    this.startAutoRefresh();
  },

  onUnload() {
    this.clearAutoRefresh();
  },

  startAutoRefresh() {
    this.clearAutoRefresh();
    this.data.refreshTimer = setInterval(() => {
      if (Date.now() - this.data.lastUpdateTime > 30000) { // 30秒自动刷新
        this.loadBotData(false);
      }
      this.updateTimeText();
    }, 1000);
  },

  clearAutoRefresh() {
    if (this.data.refreshTimer) {
      clearInterval(this.data.refreshTimer);
      this.data.refreshTimer = null;
    }
  },

  updateTimeText() {
    const diff = Math.floor((Date.now() - this.data.lastUpdateTime) / 1000);
    let text = '';
    if (diff < 60) {
      text = `${diff}秒前更新`;
    } else if (diff < 3600) {
      text = `${Math.floor(diff / 60)}分钟前更新`;
    } else {
      text = `${Math.floor(diff / 3600)}小时前更新`;
    }
    this.setData({ lastUpdateTimeText: text });
  },

  async onPullRefresh() {
    this.setData({ refreshing: true });
    await this.loadBotData(false);
    this.setData({ refreshing: false });
  },

  loadBotData(showLoading = true) {
    if (showLoading) {
      this.setData({ loading: true, error: null });
    }

    return new Promise((resolve) => {
      app.apiRequest({
        url: `/myapp/api/bots/`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            this.handleDataSuccess(res.data);
          } else {
            this.handleDataError(res.data.error || '数据加载失败');
          }
        },
        fail: (err) => {
          this.handleDataError('网络请求失败');
          console.error('API请求失败:', err);
        },
        complete: () => {
          if (showLoading) {
            this.setData({ loading: false });
          }
          resolve();
        }
      });
    });
  },

  handleDataSuccess(response) {
    const formattedData = response.data.map(bot => ({
      ...bot,
      last_check: this.formatDateTime(bot.last_check),
      selected: false
    }));

    this.setData({
      botList: formattedData,
      lastUpdateTime: Date.now(),
      error: null
    });
    this.updateTimeText();
  },

  handleDataError(message) {
    this.setData({
      error: message,
      loading: false
    });
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  },

  formatDateTime(datetimeStr) {
    if (!datetimeStr) return '暂无数据';
    try {
      const date = new Date(datetimeStr);
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } catch {
      return datetimeStr;
    }
  },

  selectBot(e) {
    const bot = e.currentTarget.dataset.bot;
    const botList = this.data.botList.map(item => ({
      ...item,
      selected: item.wxid === bot.wxid
    }));
    this.setData({ botList });
  },

  copyAccount(e) {
    const account = e.currentTarget.dataset.account;
    wx.setClipboardData({
      data: account,
      success: () => {
        wx.showToast({ 
          title: '微信号已复制',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({ 
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  showQrcode(e) {
    const index = e.currentTarget.dataset.index;
    const selectedBot = this.data.botList[index];
    this.setData({
      showQrModal: true,
      selectedBot
    });
  },

  closeQrcode() {
    this.setData({ 
      showQrModal: false,
      selectedBot: null,
      botList: this.data.botList.map(bot => ({
        ...bot,
        selected: false
      }))
    });
  },

  preventBubble() {
    // 防止点击内容区域关闭弹窗
    return;
  },

  saveQrcode() {
    if (!this.data.selectedBot?.qrcode_url) {
      wx.showToast({
        title: '二维码地址无效',
        icon: 'none'
      });
      return;
    }

    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => this.doSaveImage(),
            fail: () => this.showAuthGuide()
          });
        } else {
          this.doSaveImage();
        }
      }
    });
  },

  doSaveImage() {
    wx.showLoading({ title: '保存中...' });
    wx.downloadFile({
      url: this.data.selectedBot.qrcode_url,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.hideLoading();
            wx.showToast({ 
              title: '已保存到相册',
              icon: 'success'
            });
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({ 
              title: '保存失败',
              icon: 'none'
            });
          }
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ 
          title: '图片下载失败',
          icon: 'none'
        });
      }
    });
  },

  showAuthGuide() {
    wx.showModal({
      title: '需要授权',
      content: '请允许保存图片到相册，以便保存二维码',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting();
        }
      }
    });
  },

  handleImageError() {
    wx.showToast({
      title: '二维码加载失败',
      icon: 'none'
    });
  }
});