import EV, { EV_TYPE } from "../mgr/EV";
import Utils from "../utils/Utils";
import { WalletManager } from "../web3/WalletManager";
import { GoodsId } from "./GoodsId";
import WsM from "./WsM";
import { EventTarget } from "cc";

export class GoodInfo {
  id: number;
  count: number;
}

export class SeasonInfo {
  id: number;
  startTimeAt: number;
  endTimeAt: number;
  gamePassNum: number;
}

export class GameInfo {
  gameId: number;
  gameUser: number;
  myRewardPog: number;
  remainPog: number;
  seasonPog: number;
}
export class UserInfo {
  userId: number; // 用户id
  userName: string; // 用户名
  walletAddress: string; // 用户钱包
  systemWalletAddress: string; // 系统钱包
  season: SeasonInfo;
  currentTime: number; // 当前时间
  goodList: GoodInfo[];

  gameList: GameInfo[];
}

export class BindWalletResult {
  walletAddress: string;
  systemWalletAddress: string;
}

export class BadgeInfo {
  id: number; // 徽章id
  type: number; // 徽章类型
  num: number; // 数量
  addition: number; // 加成
}

export class MyBadgeInfo {
  badgeList: BadgeInfo[];
}
export default class UserM {
  isBindWallet(): boolean {
    return (
      this.data?.walletAddress != null && this.data?.walletAddress.length > 0
    );
  }
  async getBadgeList( ) {
    let result = await WsM.ins.syncRequest(20002, {});
    
    return result;
  }
  getGamePassCount() {
    return this.data?.season?.gamePassNum ?? 0;
  }
  addGoods(id: number, count: number) {
    let good = this.data.goodList.find((item) => item.id == id);
    if (good) {
      good.count += count;
    } else {
      this.data.goodList.push({ id: id, count: count });
    }
    this.refreshGoods(this.data.goodList);
  }
  subtractGoods(id: number, count: number) {
    let good = this.data.goodList.find((item) => item.id == id);
    if (good) {
      good.count -= count;
      if (good.count < 0) {
        good.count = 0;
      }
    }
    this.refreshGoods(this.data.goodList);
  }
  getGradeAddValue(): number {
    return 30;
  }
  getGradeName() {
    return "BRONZE";
  }
  getGrade(): number {
    return 1;
  }

  getDisPlayGoods(): GoodInfo[] {
    let DisplayIds = [
      GoodsId.FREE_ITEM_BOX,
      GoodsId.ITEM_BOX,
      GoodsId.FREE_POG_BOX,
      GoodsId.POG_BOX,
      GoodsId.GAME_PASS,
      GoodsId.GAME_PASS_SHARD,
      GoodsId.POG_CRITICAL_CARD,
    ];
    //不改變目標庫，換方式實現
    let list = [];
    for (let i = 0; i < this.data.goodList.length; i++) {
      let item = this.data.goodList[i];
      if (DisplayIds.indexOf(item.id) != -1) {
        if (item.count > 0) {
          list.push(item);
        }
      }
    }
    // 排序， 按照 DisplayIds的顺序倒序
    list = list.sort((a, b) => {
      return DisplayIds.indexOf(a.id) - DisplayIds.indexOf(b.id);
    });

    return list;
  }

  getEsTogDisplay(): string {
    return Utils.formatNumber(this.getGoodsCount(GoodsId.ES_TOG), 0);
  }
  getTogDisplay(): string {
    return Utils.formatNumber(this.getGoodsCount(GoodsId.TOG), 0);
  }
  getPogDisplay(): string {
    return Utils.formatNumber(this.getGoodsCount(GoodsId.POG), 0);
  }
  refreshGoods(goodList: GoodInfo[]) {
    this.data.goodList = goodList;
    EV.ins.emit(EV_TYPE.USER_GOOD_REFRESH, this.data.goodList);
  }
  getGoodsCount(id: number): number {
    return this.data.goodList.find((item) => item.id == id)?.count ?? 0;
  }
  getSeasonEndTimeText(): string {
    return Utils.formateDateRemaining(this.data.season.endTimeAt);
  }
  getUserName(): string {
    return this.data ? this.data.userName : "UnLogin";
  }
  private static _ins: UserM;
  public static get ins(): UserM {
    return (UserM._ins ??= new UserM());
  }
  public data: UserInfo;
  public async userInfo(): Promise<UserInfo> {
    if (this.data != null) {
      return this.data;
    }
    let result = await this.refreshInfo();
    return result;
  }

  async refreshInfo() {
    let result = await WsM.ins.syncRequest(20001, {});
    console.log("userInfo", result);

    Utils.setServerTime(result.currentTime);
    this.data = result;

    EV.ins.emit(EV_TYPE.USER_GOOD_REFRESH, this.data.goodList);
    return result;
  }

  refreshData() {
    this.data = null;
    this.userInfo();
  }

  public systemWalletAddress: string = "";

  async bindWallet(address: string): Promise<BindWalletResult> {
    return new Promise((resolve, reject) => {
      WsM.ins
        .syncRequest(23002, { wallet: address })
        .then((result) => {
          if (result) {
            this.systemWalletAddress = result.systemWalletAddress;
            resolve(result);
          } else {
            WalletManager.ins.disconnect();
          }
        })
        .catch((err) => {
          WalletManager.ins.disconnect();
          reject(err);
        });
    });
  }
}
