<template>
	<view class="content">
		<view class="content-text">1.连接钱包</view>
		<button class="content-button" @click="modal.open()">Open Connect Modal</button>
		<button class="content-button" @click="modal.open({ view: 'Networks' })">Open Network Modal</button>
		<button class="content-button" @click="disconnect()">断开连接</button>
		<view class="content-text">2.获取钱包信息</view>
		<view class="content-text2">address:{{ address }}</view>
		<view class="content-text2">chainId:{{ chainId }}</view>
		<view class="content-text">3.签名</view>
		<button class="content-button" @click="sign()">sign message</button>
		<view class="content-text">4.查询 Match 余额</view>
		<view class="content-text2">MAT: {{balance && formatUnits(balance.value,18)}}</view>
		<view class="content-text2">TOX: {{usdtBalance && formatUnits(usdtBalance,18)}}</view>
		<view class="content-text">5.转账</view>
		<!-- <input v-model="inputValue" @input="fun" type="text" /> -->
		<button class="content-button" @click="transfer()">transfer</button>
		<view class="content-text">6.查询 授权合约额度</view>
		<view class="content-text2"> allowance: {{allowance && formatUnits(allowance,18)}}</view>


		<button class="content-button" @click="signLogin()">Login</button>
	</view>
</template>

<script>
	import {
		toRefs,
		toRaw,
		ref,
		defineModel,
		reactive
	} from 'vue';

	import {
		arbitrum,
		mainnet
	} from '@wagmi/core/chains'
	import {
		createWeb3Modal,
		useWeb3Modal,
		useWeb3ModalEvents,
		useWeb3ModalState,
		useWeb3ModalTheme
	} from '@web3modal/wagmi/vue'
	import {
		chains,
		projectId,
		wagmiConfig
	} from "../unit/config.js";

	import {
		useAccount,
		useBalance,
		useDisconnect,
		useReadContract,
		useSignMessage,
		useWriteContract
	} from "@wagmi/vue";
	import ERC20 from '../contract/abi/ERC20.json'
	import {
		ChainId,
		USDT_ADDRESS
	} from "@/contract/address";
	import {
		formatUnits,
		parseUnits
	} from "viem";
	// 3. Create modal
	createWeb3Modal({
		wagmiConfig,
		projectId,
		chains,
		themeMode: 'light'
	})

	export default {
		setup() {
			
			const {
				signMessageAsync
			} = useSignMessage()

			const {
				disconnect
			} = useDisconnect()
			// 4. Use modal composable 。
			// 注意在使用“useWeb3Mode”compositable之前，请调用“createWeb3Model”
			const modal = useWeb3Modal()
			const {
				address,
				chainId,
				isConnected
			} = useAccount()

			const {
				data: balance
			} = useBalance({
				address: address?.value
			})
			const balanceData = balance.value;

			if (balanceData) {
				console.log("Balance value:", formatUnits(balanceData.value, 18));

				console.log("Balance object:", balanceData);
				const balanceFormatted = balanceData?.formatted || 'undefined';
				const balanceSymbol = balanceData?.symbol || 'undefined';
				const balanceValue = formatUnits(balanceData.value, 18);

				console.log("Balance formatted:", balanceFormatted);
				console.log("Balance symbol:", balanceSymbol);
				console.log("Balance value:", balanceValue);
			} else {
				console.log("Balance data is not available.");
			}

			//签名
			async function sign() {
				const signature = await signMessageAsync({
					message: `Login request from ${address.value}`//'gm wagmi frens'
				})
				console.log(signature)
			}

			//测试签名登录
			async function signLogin() {
				if (!address) {
					await modal.open();
				}
				console.log("Connected address:", address);
				const userAddress = address.value;
				console.log("userAddress:", userAddress)
				const message = `Login request from ${userAddress}`;
				const signature = await signMessageAsync({
					message
				});

				// Send signature and account to backend
				// const response = await axios.post('http://192.168.0.113:30001/ms_dev/program/getLoginToken', {
				// 	address: address,
				// 	signature: signature,
				// 	message: message
				// });
				const params = {
					address: userAddress,
					signature: signature,
					message: message
				}
				uni.request({
					url: "http://127.0.0.1:30001/ms_dev/program/getLoginToken",
					data: params,
					method: "POST",
					header: {
						"Content-Type": "application/json",
					},
					success: function(res) {
						if (res.statusCode == 200) {
							let data = res.data;
							console.log("res:", data);
							const token = data.token;
							console.log(token)
						} else {
							console.error("Error:", res)
						}
					},
					fail: function(e) {
						console.error("Failed:", e)
					}
				})

			}

			// 获取 USDT 余额
			const {
				data: usdtBalance
			} = useReadContract({
				abi: ERC20,
				address: USDT_ADDRESS[ChainId.MATCH],
				functionName: 'balanceOf',
				args: [address],
			})
			// 获取 USDT授权某个合约额度 直接转账transfer不需要授权 调用合约扣除自己代币的需要先授权
			// 授权方法 approve 参数 合约地址 数量（一般MaxUint256）具体看 abi erc20
			// export const MaxUint256: bigint = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
			const {
				data: allowance
			} = useReadContract({
				abi: ERC20,
				address: USDT_ADDRESS[ChainId.MATCH],
				functionName: 'allowance',
				//自己地址 合约地址
				args: [address, address],
			})
			const {
				writeContractAsync
			} = useWriteContract()


			const state = reactive({
				inputValue: '',
			})
			// 输入处理函数
			let fun = (event) => {
				console.log(event);
				state.inputValue = event.target.value;
			}

			async function transfer() {
				
				//转给谁
				const to =
					"0xB91ee630d4BaF83bBfc32d99a6536344d63cCA87"; // "0xa5f99C0E7D0C7A35D27b6F8E9881F2c9E32A937D"
				//转多少 这里以 1 个 USDT 举例 因为区块链没有小数 USDT 的代币精度是 18 1个 USDT 在区块链上表示为 1*10**18
				const value = parseUnits("0.01", 18) //库封装了方法
				const res = await writeContractAsync({
					abi: ERC20,
					address: USDT_ADDRESS[ChainId.MATCH],
					functionName: 'transfer',
					args: [
						to,
						value
					],
				})
				console.log(res)
			}
			return {
				modal,
				address,
				chainId,
				
				balance,
				usdtBalance,
				allowance,
				
				formatUnits,
				disconnect,
				sign,
				transfer,
				signLogin
			}
		},
		data() {
			return {

			}
		},
		methods: {

		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: aqua;
	}

	.content-text {
		text-align: left;
		width: 400rpx;
		height: 60rpx;
		font-weight: bold;
		margin: 20rpx 0;
	}

	.content-text2 {
		text-align: left;
		width: 400rpx;
		height: 80rpx;
		line-height: 80rpx;
		/* border: 1rpx solid red; */
		/* word-wrap: break-word; */
		/* font-weight: bold; */
	}

	.content-input {}

	.content-button {
		/* width: 400rpx; */
		/* height: 60rpx; */
		margin: 10rpx 0;
	}
</style>