<template>
    <div class="container">
      <svg-icon name="wallet-bg" class="bg-img" />
      <div class="user-info-body">
        <div class="user-info-lf">
          <van-image
            width="28px"
            height="28px"
            round
            :src="walletStore.avatar"
          />
          <div class="user-info">
            <div class="user-info-name" @click="showWallet = true">
              <div>{{ walletStore.username }}</div>
              <svg-icon style="width: 16px; height: 16px;margin-left: 3px;" name="down" />
            </div>
            <div class="user-info-key-body">
              <span class="user-info-key-body-text">{{ formatAddress(walletStore.account) }}</span>
              <svg-icon class="im-copy-btn" style="width: 16px; height: 16px;" name="copy" :data-clipboard-text="walletStore.account"/>
            </div>
          </div>
        </div>
        <div class="network">
          <van-image width="20px" height="20px" round :src="walletStore.accountIcon"/>
          <div class="network-name">{{ walletStore.accountName  }}</div>
        </div>
      </div>
      <div class="amount">
        <div class="amount-item-box">
          <div>Total assets</div>
          <div class="amount-item">
            <div class="item-text">
              <svg-icon class="my" style="width: 28px; height: 28px;" name="my" />
              <div>{{isShow?totalMoney:'****'}}</div>
            </div>
            <svg-icon  style="width: 16px; height: 16px;" :name="isShow?'eyes':'seyes'" @click="isShow = !isShow"/>
          </div>
        </div>
        <svg-icon style="width: 24px; height: 24px; margin-right: 27px;" name="right" @click="goToPageDetail"/>
      </div>
      <div class="card-box">
        <div class="box-cont" @click="goToPage('exchange')">
          <svg-icon class="box-cont-icon" style="width: 30px; height: 30px;" name="1" />
          <div>元宝兑换</div>
        </div>
        <div class="box-cont" @click="goToPage('proceeds')">
          <svg-icon class="box-cont-icon" style="width: 30px; height: 30px;" name="2" />
          <div>收款</div>
        </div>
        <div class="box-cont" @click="goToPage('transferDetail')">
          <svg-icon class="box-cont-icon" style="width: 30px; height: 30px;" name="3" />
          <div>转账</div>
        </div>
        <div class="box-cont" @click="goToDapp">
          <svg-icon class="box-cont-icon" style="width: 30px; height: 30px;" name="4" />
          <div>竞赛</div>
        </div>
        <div class="box-cont">
          <svg-icon class="box-cont-icon" style="width: 30px; height: 30px;" name="5" />
          <div>区块浏览器</div>
        </div>
      </div>
      <div class="list-box">
        <div class="list-title">
          <div>代币</div>
          <svg-icon style="width: 24px; height: 24px;" name="add" @click="changePop(1)"/>
        </div>
        <div class="list-ul">
          <template v-for="(item,i) in walletStore.tokenList" :key="i">
            <div class="list-li" v-if="item.name == 'ACC' || !item.show" @click="changePop(2,item)">
              <div class="list-li-lf">
                <van-image width="30px" height="30px" round :src="item.logo"/>
                <div style="margin-left: 8px;">{{item.name}}</div>
              </div>
              <div class="list-li-ri">
                <div>{{item.balance}}</div>
                <div class="list-li-ri-num">${{item.money}}</div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <van-popup v-model:show="showWallet" position="bottom" round>
        <div class="pop-content">
          <div class="pop-title">
            <svg-icon style="width: 24px; height: 24px;" name="left-arrow" @click="showWallet = false"/>
            <div class="title">选择钱包</div>
          </div>
          <div class="tree">
            <div class="tree-lf">
              <div class="tree-lf-icon" v-for="(item,i) in networkList" :class="netWorkIndex == i?'active-bg':''" @click="changeNetwork(i)">
                <van-image lazy-load class="network-item-icon" :src="item.icon" />
              </div>
            </div>
            <div class="tree-ri">
              <div class="tree-ri-title">{{networkList[netWorkIndex]?.name}}</div>
              <div class="tree-ul">
                <div class="tree-li" 
                  v-for="(item,i) in currentWallets" 
                  :class="item.id == walletStore.id?'tree-active':''" @click="changeWallet(item)">
                  <van-image
                    width="37px"
                    height="37px"
                    round
                    :src="item.avatar"
                  />
                  <div class="tree-li-cont">
                    <div class="tree-li-text">{{ item.username }}</div>
                    <div class="tree-li-address">
                      <span>{{ formatAddress(item.account) }}</span>
                      <svg-icon 
                        class="im-copy-btn" 
                        style="width: 16px; height: 16px;margin-left: 2px;" 
                        name="copy" :data-clipboard-text="item.account"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="pop-btn" @click="addWallet">
            <van-button class="btn" type="primary" size="large" color="#4765DD"> 
              <svg-icon style="width: 24px; height: 24px;margin-right: 4px;" name="add1" />添加钱包
            </van-button>
          </div>
        </div>
      </van-popup>
      <van-popup v-model:show="showHistory" position="bottom" round style="height:500px">
        <div class="pop-content" style="height:500px">
          <div class="pop-title">
            <svg-icon style="width: 24px; height: 24px;" name="left-arrow" @click="showHistory = false"/>
            <div class="title">{{ type == 1?'添加代币':'历史记录' }}</div>
          </div>
          <!-- 1 -->
          <div class="pop-ul" v-if="type == 1">
            <div class="pop-li" v-for="(item,i) in walletStore.tokenList">
              <div class="pop-li-lf" v-if="item.name != 'ACC'">
                <van-image
                  width="32px"
                  height="32px"
                  round
                  :src="item.logo"
                />
                <div style="margin-left: 6px;">
                  <div>{{item.name}}</div>
                  <div class="pop-address">{{ formatAddress(item.address) }}</div>
                </div>
              </div>
              <svg-icon v-if="item.name != 'ACC'" style="width: 20px; height: 20px;" :name="item.show?'add-icon':'del-icon'" @click="tokensHandle(item)"/>
            </div>
          </div>
          <!-- 2 -->
          <div class="pop-list" v-if="type == 2">
            <div class="pop-list-box" v-for="(item,i) in historyList">
              <svg-icon style="width: 24px; height: 24px;color: #fff;" :name="item.from?.hash == walletStore.account?'fs':'js'" />
              <div class="pop-list-ul">
                <div class="pop-list-li">
                  <div class="pop-list-li-title">{{item.from?.hash == walletStore.account?'发送':'接收'}}</div>
                  <div class="pop-list-li-status">成功</div>
                </div>
                <div class="pop-list-li">
                  <div>转账金额</div>
                  <div>{{item.value}}{{selectUrl.name}}</div>
                </div>
                <div class="pop-list-li">
                  <div>{{item.from?.hash == walletStore.account?'发送':'接收'}}时间</div>
                  <div>{{item.timestamp}}</div>
                </div>
                <div class="pop-list-li">
                  <div>收款地址</div>
                  <div>{{formatAddress(item.to?.hash)}}
                    <svg-icon class="im-copy-btn" style="width: 16px; height: 16px;" name="copy" :data-clipboard-text="item.to?.hash"/>
                  </div>
                </div>
                <div class="pop-list-li">
                  <div>hash</div>
                  <div>{{formatAddress(item.hash)}}
                    <svg-icon class="im-copy-btn" style="width: 16px; height: 16px;" name="copy" :data-clipboard-text="item.hash"/>
                  </div>
                </div>
                <div class="pop-list-li" v-if="selectUrl.name == 'ACC'">
                  <div>矿工费</div>
                  <div>{{item.gas_price}}ACC</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-popup>
    </div>
  </template>
  
  <script setup>
  import { useRouter } from 'vue-router'
  import { getNetwork } from '@/api/path/login.api'
  import { useWalletStore } from "@/stores/modules/walletStore";
  import { useSystemStore } from "@/stores/modules/systemStore";
  import {  transactions, tokenTransfers } from "@/api/path/backend.api";
  import { openDapp } from "@/composables/dAppView";
  import { cryptoEncode } from "@/utils/crypto";
  import { useCopy } from "@/hooks/use-copy.js";
  useCopy();

  const router = useRouter();
  const walletStore = useWalletStore();
  const systemStore = useSystemStore();

  const isShow = ref(true);
  const showWallet = ref(false);
  const showHistory = ref(false);
  const networkList = ref([]);
  const netWorkIndex = ref(0);
  const type = ref('');
  const historyList = ref([]);
  const selectUrl = ref({});
  const goToPage = (url) => {
    router.push(url)
  }
  // 跳转详情
  const goToPageDetail = () => {
    router.push({
      path: 'walletDetail',
      query:{
        id:walletStore.id
      }
    })
  }
  const changePop = (val,item) => {
    type.value = val;
    if(val == 2){
      getDetail(item);
      selectUrl.value = item;
      return;
    };
    showHistory.value = true;
  }
   // 查看历史记录
  const getDetail = (item) => {
    if(item.name == 'ACC'){
      getList();
    }else{
      getDBList(item.address);
    }
    showHistory.value = true;
  }
  const getList = async () => {
    const res = await transactions(walletStore.account);
    const items = res.items || []
    if (items.length > 0) {
      items.forEach(val => {
        val.timestamp = getDateTime(val.timestamp)
        val.gas_price = getPrice(val.fee.value).toFixed(9)
        if (val.value !== '0') {
          val.value = getPrice(val.value).toFixed(6)
        }
      })
      historyList.value = items
    }
  }
  const getDBList = async (DBaddress) => {
    const res = await tokenTransfers(walletStore.account,{
      params: {
        type: 'ERC-20,ERC-721,ERC-1155',
        filter: 'to | from',
        token: DBaddress
      }
    })
    const items = res.items || []
    if (items.length > 0) {
      items.forEach(val => {
        val.timestamp = getDateTime(val.timestamp)
        val.value = getPrice(val.total.value).toFixed(6)
        val.hash = val.transaction_hash
      })
      historyList.value = items
    }
  }
  // 计算总和
  const totalMoney = computed(() => {
    const list = walletStore.tokenList
    if (!Array.isArray(list) || list.length === 0) return 0
    let total = Number(list[0].money || 0)
    for (let i = 1; i < list.length; i++) {
      if (!list[i].show) {
        total += Number(list[i].money || 0)
      }
    }
    return Number(total.toFixed(4))
  })

  // 添加钱包
  const addWallet = () => {
    walletStore.accountName = networkList.value[netWorkIndex.value].name
    walletStore.accountIcon = networkList.value[netWorkIndex.value].icon
    walletStore.rpcUrl = networkList.value[netWorkIndex.value].url
    router.push({
      path: '/login',
      query:{
        isFirst:false
      }
    })
  }
  // 网络数据
  const initNetwork =  async () => {
    const { data } = await getNetwork({})
    networkList.value = data
  }
  const currentChainName = computed(() => networkList.value[netWorkIndex.value]?.name)

  // 当前链对应的钱包数组
  const currentWallets = computed(() => {
    return walletStore.walletList.filter(w => w.accountName === currentChainName.value)
  })
  // 切换网络
  const changeNetwork = (i) => {
    netWorkIndex.value = i;
  }
  // 切换钱包
  const changeWallet = (item) => {
    walletStore.switchWallet(item.id,item.account);
    showWallet.value = false;
  }
   // 代币显示隐藏
   const tokensHandle  = (item)=>{
    walletStore.changeToten(item.name)
  }
  // 更新代币信息
  const gethotTokens = async () => {
    await walletStore.updateTokenVal();
  }
  // 跳转竞赛
  const goToDapp = () => {
    const dapp = cryptoEncode(
      JSON.stringify({
        address: walletStore.account,
        privateKey: walletStore.privateKey,
      })
    );
    openDapp('http://192.168.0.70:8088/#/', { dapp });
  }

  const formatAddress = (address) => {
    if (!address) return '';
    return address.slice(0, 8) + '...' + address.slice(-6);
  };
  const getPrice = (price)=>{
		const num = (parseFloat(price) / Math.pow(10, 18));
		return num
	}
	const getDateTime=(isoString)=>{
		const date = new Date(isoString);
		const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
		return formattedDate;
	}
  onMounted(async ()=>{
    initNetwork();
    gethotTokens();
  })
  </script>
  
  <style lang="less" scoped>
  .container{
    position: relative;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 50px);
    .bg-img{ 
      height: 18.8rem; 
      min-width: 100%;        
      width: 100vw;
      position: absolute;
      top: -0.8rem;
      left: 0;
      z-index: -1;
    }
    .user-info-body{
      padding: 60px 17px 25px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .user-info-lf{
        display: flex;
        align-items: center;
        .user-info{
          margin-left: 11px;
          font-family: PingFang SC, PingFang SC;
          font-size: 10px;
          .user-info-name{
            font-weight: 500;
            color: #FFFFFF;
            display: flex;
            align-items: center;
            margin-bottom: 2px;
          }
          .user-info-key-body{
            font-weight: 400;
            color: rgba(255,255,255,0.6);
            display: flex;
            align-items: center;
            .user-info-key-body-text{
              margin-right: 4px;
            }
          }
        }
      }
      .network{
        display: flex;
        align-items: center;
        border-radius: 27px;
        border: 1px solid rgba(255,255,255,0.6);
        padding: 0 5px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 15px;
        color: #FFFFFF;
        height: 25px;
        line-height: 25px;
        box-sizing: border-box;
        .network-name{
          margin-left: 5px;
        }
      }
    }
    .amount{ 
      height: 102px;
      background-color: rgba(242, 242, 242, 0.2);
      backdrop-filter: blur(3px);  
      -webkit-backdrop-filter: blur(3px);  
      border-radius: 15px;
      margin: 0 17px 20px 17px;
      box-shadow:0 7px 10px #15277031;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 15px;
      color: #FFFFFF;
      &:before { 
        height: calc(100% - 4px);
        width: calc(100% - 4px);
        content: "";
        position: absolute;
        inset: 0;
        z-index: -1;
        padding: 2px; /* 边框宽度 */
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 0.2) 25%, rgba(255, 255, 255, 0.1) 50%,  rgba(255, 255, 255, 0.2) 75%, rgba(255, 255, 255, 0.6) 100%);//linear-gradient(135deg, #ffffff64, #ffffff2e); /* 渐变方向可调 */
        -webkit-mask: 
          linear-gradient(#fff 0 0) content-box, 
          linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        border-radius: 15px; /* 必须和父元素一致 */
        pointer-events: none; /* 避免遮挡点击 */

      }
      .amount-item-box{
        margin: 21px 21px 27px 27px;
      }
      .amount-item{
        margin-top: 7px;
        font-weight: 600;
        font-size: 25px;
        display: flex;
        position: relative;
        .item-text{
          display: flex;
          align-items: center;
          margin-right: 2px;
          .my{
            position: relative;
            top:1px;
          }
        }
      }
    }

  
    .card-box{
      background: #FFFFFF;
      box-shadow: 0px 4px 8px -2px rgba(25,75,137,0.25);
      border-radius: 17px;
      height: 78px;
      margin: 0 17px;
      padding: 15px 10px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #000000;
      .box-cont{
        width: calc(100% / 5);
        display: flex;
        flex-direction: column;
        align-items: center;
        .box-cont-icon{
          margin-bottom: 4px;
          color: #fff;
        }
      }
    }
    .list-box{
      background: #FFFFFF;
      border-radius: 12px;
      margin: 25px 17px;
      padding: 16px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: hidden;
      .list-title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 17px;
        color: #000000;
        margin-bottom: 23px;
      }
      .list-ul{
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: auto;
        .list-li{
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          margin-bottom: 12px;
          .list-li-lf{
            display: flex;
            align-items: center;
            font-size: 15px;
            color: #000000;
          }
          .list-li-ri{
            font-size: 12px;
            color: @font-color2;
            text-align: right;
            .list-li-ri-num{
              font-weight: 400;
              font-size: 10px;
              color: #8D8D8D;
            }
          }
        }
        .list-li:last-child{
          margin-bottom: 0;
        }
      }
      .list-ul::-webkit-scrollbar{
          width: 0;
      }
    }
    .pop-content{
      display: flex;
      flex-direction: column;
      .pop-title{
        padding: 17px;
        border-bottom: 1px solid #F2F2F2;
        display: flex;
        align-items: center;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 17px;
        color: #000000;
        .title{
          flex: 1;
          display: flex;
          justify-content: center;
        }
      }
      .tree{
        display: flex;
        height: 300px;
        overflow: hidden;
        .tree-lf{
          display: flex;
          flex-direction: column;
          width: 67px;
          overflow: auto;
          .tree-lf-icon{
            height: 67px;
            padding: 16px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .active-bg{
            background: #ECEFFC;
          }
        }
        .tree-lf::-webkit-scrollbar{
          width: 0;
        }
        .tree-ri{
          margin-left: 10px;
          margin-right: 17px;
          flex: 1;
          overflow: auto;
          .tree-ri-title{
            margin: 10px 0 4px;
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 15px;
            color: #000000;
          }
          .tree-ul{
            .tree-li{
              background: #F2F2F2;
              border-radius: 8px;
              border: 1px solid #F2F2F2;
              padding: 14px 16px;
              display: flex;
              align-items: center;
              margin-bottom: 12px;
              .tree-li-cont{
                margin-left: 12px;
                font-family: PingFang SC, PingFang SC;
                font-weight: 400;
                font-size: 12px;
                color: #8D8D8D;
                .tree-li-text{
                  font-weight: 500;
                  font-size: 15px;
                  color: @theme-color1;
                }
                .tree-li-address{
                  display: flex;
                  align-items: center;
                }
              }
            }
            .tree-active{
              background: #FAFBFF;
              border: 1px solid @theme-color1;
            }
          }
        }
        .tree-ri::-webkit-scrollbar{
          width: 0;
        }
      }
      .pop-btn{
        margin: 17px;
        .btn{
          height: 40px;
          border-radius: 50px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 15px;
          color: #FFFFFF;
        }
        :deep(.van-button__text) {
          display: flex;
          align-items: center;
        }
      }
      .pop-list{
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: auto;
        .pop-list-box{
          display: flex;
          padding: 17px 17px 0;
          .pop-list-ul{
            padding-bottom: 12px;
            flex: 1;
            margin-left: 8px;
            border-bottom: 1px solid #F2F2F2;
            box-sizing: border-box;
            .pop-list-li{
              display: flex;
              align-items: center;
              justify-content: space-between;
              font-family: PingFang SC, PingFang SC;
              margin-bottom: 4px;
              font-weight: 400;
              font-size: 12px;
              color: @font-color2;
              .pop-list-li-title{
                font-weight: 500;
                font-size: 15px;
                color: #000000;
              }
              .pop-list-li-status{
                font-weight: 500;
                font-size: 15px;
                color: @theme-color1 !important;
              }
            }
            .pop-list-li div:last-child{
              color: #8D8D8D;
            }
          }
        }
      }
      .pop-list::-webkit-scrollbar{
        width: 0;
      }
      .pop-ul{
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: auto;
        margin: 16px 16px 0;
        .pop-li{
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 16px;
          .pop-li-lf{
            display: flex;
            align-items: center;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #4F4F4F;
            .pop-address{
              font-size: 12px;
              color: #8D8D8D;
            }
          }
        }
      }
    }
  }
  </style>