<template>
  <t-dialog
    :footer="false"
    @close="closeDialog"
    placement="center"
    :visible="hasPayDialog"
    :draggable="true"
    class="pay-dialog-box"
  >
    <template #header>
      <h2>支付界面</h2>
    </template>
    <template #body>
      <div class="pay-body-box">
        <div class="pay-body-line">
          <div>充值金额</div>
          <div>${{ price }}</div>
        </div>
        <div class="pay-body-line">
          <div>{{ defaBtn.label }}</div>
          <div>{{ price }}</div>
        </div>
        <div class="Payment-Method">
          <p>支付方式</p>
          <div class="Pay-img-box">
            <div
              v-for="(item, index) in Imgs"
              :key="item.img"
              class="pay-img"
              :class="{ active: moring(item.value) }"
              @click="changeb(item.value, index)"
            >
              <img :src="item.img" alt="" />
            </div>
          </div>
        </div>
        <div class="pay-btn">
          <t-button @click="Payment">支付</t-button>
        </div>
      </div>
    </template>
  </t-dialog>
</template>

<script lang="ts" setup>
import request from '@/utils/request';
import { MessagePlugin } from 'tdesign-vue-next';
const props = defineProps({
  hasPayDialog: Boolean,
  price: String,
});
// 用户交易地址
const userAddress = useUserAddress();
// 用户token
const userToken = useUserToken();
// 用户所有信息
const userInfo = useTokenInfo();
const emit = defineEmits(['closePayDialog']);
const closeDialog = () => {
  emit('closePayDialog', false);
  // console.log(userToken.value);
};
// 交易轮询
let Interval: any = null;
// 默认的选择币
const defaBtn = ref({
  label: 'BUSD',
  value: 1,
});
// 收款地址--先写死，之后从接口获取
let MyAddress = '0x1601f342dBfbf76d27Fe35C09fFfEa7bfCCaE4b5';
const moring = computed((label: string) => {
  return function (label: string) {
    return defaBtn.value.label === label;
  };
});
// img
const Imgs = [
  {
    img: '/images/svg/user/usdt.svg',
    value: 'USDT',
    address: '0x55d398326f99059fF775485246999027B3197955',
  },
  {
    img: '/images/svg/user/busd.svg',
    value: 'BUSD',
    address: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',
  },
  {
    img: '/images/svg/user/usdc.svg',
    value: 'USDC',
    address: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',
  },
];
// 切换支付方式
const changeb = (label: string, index: number) => {
  defaBtn.value.label = label;
  defaBtn.value.value = index;
};
// 发起交易
const recharge = (hash: string, price: number) => {
  request
    .post(
      '/api/recharge',
      {
        hash: hash,
        amount: price,
        // 付款账号
        address: userAddress.value,
        // 收款账号
        address_to: MyAddress,
        config_id: userInfo.value.id,
        type: defaBtn.value.label,
      },
      {
        headers: {
          authorization: `Bearer ${userToken.value}`,
        },
      }
    )
    .then((res: any) => {
      if (res.code === 2 && 'token' in res.data) {
        userToken.value = res.data.token;
      }
    });
};
// 支付
const Payment = () => {
  let eth: any = window;
  // 转换后的收款地址
  let MyNewAddress = MyAddress.substring(2).padStart(64, '0');
  // 实际价格--props.price
  // 测试价格
  // let price = 0.01;
  // 转换后的价格
  let newPrice = (parseInt(props.price) * Math.pow(10, 18))
    .toString(16)
    .padStart(64, '0');
  // 小狐狸支付
  eth.ethereum
    .request({
      method: 'eth_sendTransaction',
      params: [
        {
          // 用户钱包地址
          from: userAddress.value,
          // 支付代币类型 BUSD
          to: Imgs[defaBtn.value.value].address,
          // gas价格
          // gasPrice: "0x12a05f200",
          // gas: "0x16e360",
          // 交易数据十六进制  交易0xa9059cbb  目标钱包地址(我们的钱包地址)  交易金额（十六转换）
          data: '0xa9059cbb' + MyNewAddress + newPrice,
        },
      ],
    })
    .then((hash) => {
      // 交易hash
      if (hash) {
        // 发送充值信息
        recharge(hash, parseInt(props.price));
        // 轮询交易状态
        Interval = setInterval(() => {
          request
            .post(
              '/api/recharge/check',
              {
                hash: hash,
              },
              {
                headers: {
                  authorization: `Bearer ${userToken.value}`,
                },
              }
            )
            .then((res: any) => {
              if (res.data.status == 1) {
                MessagePlugin.success('支付成功');
                // 关闭轮询
                clearInterval(Interval);
                // 关闭弹窗
                emit('closePayDialog', false);
              } else if (res.code === 2 && 'token' in res.data) {
                userToken.value = res.data.token;
              }
            });
        }, 2000);
      }
    })
    .catch((e) => {
      // 关闭轮询
      clearInterval(Interval);
      if (e.code == -32602) {
        MessagePlugin.closeAll();
        MessagePlugin.warning('未连接钱包');
      } else {
        MessagePlugin.closeAll();
        MessagePlugin.warning('交易关闭');
      }
    });
  //
};
onMounted(() => {
  // 是否可以向当前链发出 RPC 请求
  // console.log(ethereum.isConnected());
});
</script>

<style lang="less" scoped>
@import '@/style/flex.less';
@import '@/style/variables.less';
.pay-dialog-box {
  :deep(.t-dialog) {
    width: 420px;
    padding-bottom: 12px;
    .t-dialog__body {
      .pay-body-box {
        .pay-body-line {
          font-size: @font-size-l;
          .dj(space-between);
          padding: 12px 12px;
          font-weight: bold;
          :nth-child(1) {
            color: rgb(68, 68, 68);
          }
          :nth-child(2) {
            color: black;
          }
        }
        .Payment-Method {
          padding: 12px 12px;
          font-size: @font-size-base;
          font-weight: bold;
          color: black;
          .Pay-img-box {
            margin-top: 20px;
            .dja(space-between, center);
            .pay-img {
              width: 94px;
              height: 58px;
              border-radius: 4px;
              .dja();
              box-shadow: 0 0 10px #ddd;
              &:hover {
                box-shadow: 0 0 12px var(--td--main-btn-color-1);
                transition: all 0.2s;
                cursor: pointer;
              }
            }
            .active {
              box-shadow: 0 0 12px var(--td--main-btn-color-1);
            }
          }
        }
        .pay-btn {
          .dja(center,flex-end);
          width: 100%;
          height: 80px;
          .t-button {
            width: 94%;
            height: 54px;
            background: rgb(42, 45, 46);
            border: none;
            --ripple-color: rgb(80, 78, 79);
          }
        }
      }
    }
  }
}
</style>
