import { defineStore } from "pinia";
import Web3 from "web3";
import CryptoJS from "crypto-js";
import { cloneDeep, forEach } from "lodash";
import { sysLogin } from "@/common/login.js";
import { showNotify } from 'vant';
import router from '@/router/index'
import { hotTokens } from '@/api/path/login.api'
import { cryptoDecode } from "@/utils/crypto.js"


export const useWalletStore = defineStore("useWalletStore", {
  state: () => ({
    id: "", // name + @ + account
    isAuthenticated: false, // 登录状态
    account: null, // 钱包地址 
    tokenList: [],//代币数组
    privateKey: null, // 私钥
    encryptedKey: localStorage.getItem("encryptedKey") || null, // 加密后的密钥
    loading: false, // 加载状态
    error: null, // 错误信息
    chainId: null, // 链ID

    balance: "0", // 账户余额(ETH)

    rpcUrl: "", // ACC私有链RPC

    username: "", // 用户名
    avatar: "", // 头像

    accountName: "", //网络昵称
    accountIcon: "", // 网络头像
    accountPassword: null, // 密码
    accountHint: "", //  提示词
    words: "", // 助记词

    walletList: [], // 钱包列表
  }),
  persist: true,
  getters: {
    getWalletList() {
      return this.walletList;
    },
    getAccount(){
      return this.account
    }
  },
  actions: {
    async initWeb3() {
      try {
        window.$web3 = new Web3(this.rpcUrl);
        return window.$web3
      } catch (err) {
        console.log(err);
        this.error = "初始化区块链连接失败";
        return null;
      }
    },

    async getBalance() {
      if (!this.account || !window.$web3) {
        await this.initWeb3()
      }
      try {
        const weiBalance = await window.$web3.eth.getBalance(this.account);
        this.balance = await window.$web3.utils.fromWei(weiBalance, "ether");
        return this.balance;
      } catch (err) {
        this.error = "获取余额失败";
        return "0";
      }
    },
    async loginWithPrivateKey(isMnemonic = false) {
      this.loading = true;
      this.error = null;
      try {
        const web3 = window.$web3 || (await this.initWeb3());
        if (!web3) throw new Error("区块链连接失败");

        // 助记词路径
        // if (isMnemonic) {
        //   let wordArray;
        //   if (Array.isArray(this.words)) {
        //     if (this.words.length === 1 && typeof this.words[0] === "string") {
        //       wordArray = this.words[0].trim().split(/[\s,]+/).filter(Boolean);
        //     } else {
        //       wordArray = this.words.flat().map(w => String(w).trim()).filter(Boolean);
        //     }
        //   } else {
        //     wordArray = String(this.words)
        //       .trim()
        //       .split(/[\s,]+/)
        //       .filter(Boolean);
        //   }
        //   if (![12, 24].includes(wordArray.length)) {
        //     throw new Error("助记词应为12或24个单词");
        //   }
        //   const mnemonic = wordArray.join(" ");
        //   const hdwallet = web3.eth.accounts.wallet.create(1, mnemonic);
        //   this.privateKey = hdwallet[0].privateKey;
        // }        
        if (!/^0x[0-9a-fA-F]{64}$/.test(this.privateKey)) {
          throw new Error("私钥格式不正确");
        }
        // 创建账户对象
        const account = await web3.eth.accounts.privateKeyToAccount(this.privateKey);
        // 验证是否为合约地址
        const code = await web3.eth.getCode(account.address);
        if (code !== "0x") throw new Error("该地址是合约地址，不支持登录");

        this.account = account.address;
        this.isAuthenticated = true;
        this.chainId = `${await web3.eth.getChainId()}n`;
        this.id = `${this.account}@${this.accountName}`
        await sysLogin(this.account)
        this.addWallet()
        return {
          address: account.address,
          chainId: this.chainId,
          balance: this.balance,
        };
      } catch (err) {
        console.log("登录失败");
        this.error = err.message || "登录失败";
        throw err;
      } finally {
        this.$persist();
        this.loading = false;
      }
    },

    // 添加钱包
    addWallet() {
      const data = cloneDeep(this.$state)
      Reflect.deleteProperty(data, "walletList");
      if (this.walletList.length == 0) {
        this.walletList.push(data)
        this.addTokenList()
        return
      }
      const findIndex = this.walletList.findIndex(item => item.id === this.id);
      if (findIndex != -1) {
        this.walletList[findIndex] = data
      } else {
        this.walletList.push(data)
        this.addTokenList()
      }
    },
    // 删除钱包
    async deleteWallet(id, password) {
      const wallet = this.walletList.find(item => item.id === id);
      if (!wallet) {
        showNotify({ type: 'warning', message: '钱包不存在' });
        return;
      }
      if (cryptoDecode(wallet.accountPassword) !== password) {
        showNotify({ type: 'warning', message: '请输入正确的密码' });
        return;
      }
      // 删除钱包
      const newList = this.walletList.filter(item => item.id !== id);
      this.walletList = newList;
      if (id === this.id) {
        if (newList.length > 0) {
          // 切换到第一个钱包
          this.switchWallet(newList[0].id);
          await this.loginWithPrivateKey();
          router.push({
            path: '/wallet'
          })
        } else {
          // 当前钱包被删除，且没有其他钱包，清空状态并跳转
          for (const key in this.$state) {
            if (key !== 'walletList') {
              this.$state[key] = typeof this.$state[key] === 'string' ? '' : null;
            }
          }
          this.isAuthenticated = false;
          this.id = '';
          router.push({
            path: '/login'
          })
        }
      }
      this.$persist();
    },
    // 切换钱包
    async switchWallet(id,address) {
      const item = this.walletList.find(item => item.id === id);
      if (!item) {
        $msg($t("global.WalletDoesNotExist"))
      }
      forEach(this.$state, (_, key) => {
        if (key !== "walletList") {
          this.$state[key] = item[key];
        }
      })
      this.$persist();
      await sysLogin(address)
      await this.updateTokenVal();
    },
    // 修改钱包名称
    updateWalletName(id, newName) {
      if (id == this.id) {
        this.username = newName
      }
      const index = this.walletList.findIndex(item => item.id === id);
      if (index !== -1) {
        this.walletList[index].username = newName
      }
    },
    // 添加代币
    async addTokenList() {
      const findIndex = this.walletList.findIndex(item => item.id === this.id);
      const { data } = await hotTokens({ chain: this.accountName, address: this.account });
      this.tokenList = data;
      this.walletList[findIndex].tokenList = data;
    },
    changeToten(name) {
      const findIndex = this.walletList.findIndex(item => item.id === this.id);
      const index = this.tokenList.findIndex(item => item.name === name);
      this.tokenList[index].show = !this.tokenList[index].show
      this.walletList[findIndex].tokenList = this.tokenList;
    },
    // 更新当前选中钱包代币余额
    async updateTokenVal() {
      console.log('111',this.tokenList)
      const findIndex = this.walletList.findIndex(item => item.id === this.id);
      const { data } = await hotTokens({ chain: this.accountName, address: this.account });
      this.tokenList.forEach(el => {
        data.forEach(ele => {
          if (el.name == ele.name) {
            el.balance = ele.balance;
            el.money = ele.money
            el.rate = ele.rate
            el.cny = ele.cny
          }
        })
      })
      this.walletList[findIndex].tokenList = this.tokenList;
      return this.tokenList;
    }
  },
});
