import { defineStore } from "pinia";

const defaultUser = {
  id: "",
  nickName: "游客",
  avatar: "../static/user-icon.png",
  trio: 0, // 大于1表示完成了新手引导
  lvlName: "",
};

const getLvlName = (rankLvl, rankList = []) => {
  if (!rankList) return;
  let lvlName = "";
  rankList.some((r, index) => {
    lvlName = rankList[index].name;
    if (r.rank_id === rankLvl) {
      lvlName = rankList[index].name;
      return true;
    }
    return false;
  });
  return lvlName;
};

const getLvlImage = (rankLvl, rankList = []) => {
  if (!rankList) return;
  let lvlImage = "";
  rankList.some((r, index) => {
    if (r.rank_id === rankLvl) {
      lvlImage = rankList[index].icoin;
      return true;
    }
    return false;
  });
  return lvlImage;
};

// 定义游戏相关的 store
export default defineStore("store", {
  // 状态
  state: () => ({
    user: defaultUser,
    device: {
      deviceId: "",
      deviceName: "",
    },
    config: {},
    rankData: {
      rank: [],
      ringRank: [],
    },
  }),

  // 计算属性
  getters: {
    getUsername: (state) => {
      return state.user.username;
    },
  },

  // 方法
  actions: {
    getLvlName(rankLvl) {
      return getLvlName(rankLvl, this.config.randInfos);
    },
    getLvlImage(rankLvl) {
      return getLvlImage(rankLvl, this.config.randInfos);
    },
    updateRank(data = {}) {
      this.rankData = { ...(data || {}) };
    },
    async updateUser(user = {}) {
      this.user = { ...defaultUser, ...user };
      if (this.user.rankLvl !== undefined) {
        this.user.lvlName = getLvlName(
          this.user.rankLvl,
          this.config.randInfos
        );
      }
      this.user.lvlImage = getLvlImage(
        this.user.rankLvl,
        this.config.randInfos
      );
    },
    updateDevice(deviceId, deviceName) {
      this.device.deviceId = deviceId;
      this.device.deviceName = deviceName;
    },
    async updateConfig(config) {
      this.config = config;
      if (this.user.scores !== undefined) {
        this.user.lvlName = getLvlName(
          this.user.rankLvl,
          this.config.randInfos
        );
      }
      this.user.lvlImage = getLvlImage(
        this.user.rankLvl,
        this.config.randInfos
      );
    },
  },

  // 开启数据持久化
  persist: {
    enabled: true,
    strategies: [
      {
        storage: uni.getStorageSync,
        paths: ["user", "device", "config"], // 只持久化用户信息
      },
    ],
  },
});
