// app.ts

import { CardData, Comment, IAppOption } from "../typings";
import envConfig from "./env";

App<IAppOption>({
  globalData: {
    token: "",
    userInfo: null,
    rawCardData: [
    ] ,
    processedCardsData: []
  },
  processedCardsData: [],
  onLaunch() {
    const token = wx.getStorageSync("ttk_token");
    if (token) {
      this.globalData.token = token;
    }
    const userinfo = wx.getStorageSync("ttk_userInfo");
    console.log("系统重启获取userinfo2：",userinfo)
    if (userinfo) {
        // ⭐️ 核心修复：将缓存中的 JSON 字符串解析为对象
        try {
            this.globalData.userInfo = JSON.parse(userinfo);
            console.log("系统重启获取userinfo：", this.globalData.userInfo);
        } catch (e) {
            console.error("解析本地缓存的 userInfo 失败", e);
            this.globalData.userInfo = null; // 确保在解析失败时清空数据
        }
    }
  },
  fetchRawCardData(): Promise<CardData[]> {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${envConfig.apiBaseUrl}/article/get`,
        method: "POST",
        data: {
          uid: this.globalData.userInfo && this.globalData.userInfo.uid || ""
        },
        success: (res) => {
          console.log("接收到的文章信息1：",res)
          if (res.data && res.data.success && Array.isArray(res.data.data)) {
            const rawData = res.data.data as CardData[];
            this.globalData.rawCardData = rawData;
            
            const processedData = this.processVoteData(rawData);
            this.globalData.processedCardsData = processedData;
            this.processedCardsData = processedData; 
            
            console.log("成功获取文评列表：", processedData);
            resolve(processedData);
          } else {
            console.log("接收到的文章信息2：",res)
            const error = new Error("接口返回格式不正确");
            console.error(error, res);
            reject(error);
          }
        },
        fail: (err) => {
          console.log("接收到的文章信息3：",res)
          console.error("拉取投票数据失败", err);
          reject(err);
        }
      });
    });
  },
   // 处理投票数据的方法
   processVoteData(rawData: CardData[]): CardData[] {
    return rawData.map(card => {
      // 计算每个选项的百分比
      const optionsWithPercentage = card.options.map(option => {
        const percentage = card.total_voters > 0 
          ? Math.round((option.votes / card.total_voters) * 100) 
          : 0;
        
        return {
          ...option,
          percentage,
          isSelected: false // 初始化选中状态
        };
      });
      
      return {
        ...card,
        options: optionsWithPercentage
      };
    });
  },
  setToken(token: string) {
    this.globalData.token = token;
    wx.setStorageSync("token", token); // 同步到缓存，持久化存储
  },
  // 提供清除 token 的方法（退出登录时使用）
  clearToken() {
    this.globalData.token = "";
    wx.removeStorageSync("token");
  },
  setUserInfo(userInfo: WechatMiniprogram.CustomUserInfo){
    this.globalData.userInfo = userInfo;
    // 可选：持久化存储到缓存（根据需求决定是否需要）
    wx.setStorageSync("userInfo", userInfo);
  },
  clearUserInfo(){
    this.globalData.userInfo = null;
    wx.removeStorageSync("userInfo")
  }
})