<template>
	<view class="container">
		<web-view style="visibility: hidden; height: 1px; width: 100%;"  :webview-styles="webviewStyles" src="/static/web3/transfer-web.html" @message="handleWebViewMessage"
			:fullscreen="false" :update-title="false"></web-view>
		<view style="margin-bottom: 30rpx;">
			<u-notice-bar bgColor="#fff" color="black" :text="text1"></u-notice-bar>
		</view>
		<!-- 餘額 -->
		<view class="cards">
			<template v-if="balabces">
				<cardVue @nowCoinType="getNowCoin" @recharge="showUpgradeModal1" @changeMoney="toChangeTransfer" @blanceInfos="toBlanceDetail" :balabces="balabces"
					:incomes="allsettlefee"/>
			</template>			
		</view>
		<!-- 投資機會 -->
		<view class="invest">
			<view class="uni-flex uni-row"
				style="border-bottom: 1rpx solid #E7E7E7;font-size: 28rpx; padding-bottom: 8px;">
				<view class="uni-flex-item">
					<u-tabs :current="currentTab" inactiveStyle="{color: rgba(142, 142, 147, 1)}"
						:list="[{name:'投資機會'},{name:'我的投資'}]" @click="switchTab"></u-tabs>
				</view>
				<view class="uni-flex-item" style="text-align: end; font-size: 24rpx; line-height: 44px;" @click="more">
					查看全部</view>
			</view>
			<view style="height: calc(100vh - 360px); overflow-y: scroll;">
				<view v-if="list.length === 0" class="nodata">暫無數據</view>
				<view v-for="item in list" :key="item.id">
					<item :detail="item" />
				</view>
			</view>

		</view>
		<u-popup :show="modalintMoney" mode="bottom" @close="modalintMoney = false" round="10" :closeable="false">
			<view class="uni-flex uni-column" style="text-align: center; padding: 24px;">
				<view class="uni-flex-item">
					<canvas canvas-id="qrcodes"
						:style="{width: `${qrcodeSize}px`, height: `${qrcodeSize}px`, margin:'0px auto'}" />
				</view>
				<view class="uni-flex-item" style="font-size: 12px; padding: 12px; color: #333;">掃一掃進行充值</view>
				<!-- <view class="uni-flex-item" style="font-size: 16px; padding: 12px;text-align: start;">請選擇需要充值的貨幣</view>
				<view class="uni-flex uni-row" style="justify-content: space-around;">
					<view @click="checkCoin = coin" class="coinTag" :class="{'checked':checkCoin === coin}"
						v-for="coin in coinType" :key="coin">{{coin}}</view>
					<view @click="checkCoin = 'USDT'" class="coinTag" :class="{'checked':checkCoin === 'USDT'}">USDT
					</view>
				</view> -->
				<view class="uni-flex-item"
					style="background-color: #E7E7E7;padding: 12px 0; margin-top: 12px; border-radius: 8px;"
					@tap="copyAdress(userLoacalAddress)">
					錢包地址：<text style="flex: 1;">️{{userMoneyAdressOptions1(userLoacalAddress)}}</text>
					<image src="/static/copy.png" style="width: 28rpx;height: 28rpx;  margin-left: 18px;"></image>
				</view>
			</view>
		</u-popup>
		<!-- 密碼彈窗 -->
		<view class="modal-transfer" v-if="modalName">
			<view class="modal-content-transfer">
				<view class="modal-header-transfer">
					<u-tabs :current="moneyTab" inactiveStyle="{color: rgba(142, 142, 147, 1)}"
						:list="[{name:'劃轉到量化交易'},{name:'劃轉到錢包'}]" @click="switchMoneytab"></u-tabs>
				</view>
				<view class="modal-body-transfer">
					<view class="modal-item-transfer zf_mod_item-transfer">
						<text class="modal-label-transfer">郵箱:</text>
						<view class="">{{userInfos.email}}</view>
					</view>
					<view class="modal-item-transfer zf_mod_item-transfer">
						<text class="modal-label-transfer">轉換金額:</text>
						<u--input color="#fff" style="width: 70%;" v-model="transferIcon" 
							border="none"></u--input>
					</view>
					<view class="modal-item-transfer zf_mod_item-transfer">
						<text class="modal-label-transfer">轉換類型:</text>
						<picker mode="selector" :range="biTypes" @change="onPickerChange" style="width: 70%;">
							<view>{{selectedOption ? selectedOption : '請選擇'}}</view>
						</picker>
					</view>
					<view class="modal-item-transfer zf_mod_item-transfer">
						<text class="modal-label-transfer">支付密碼:</text>
						<u--input color="#fff" style="width: 70%;" :value="zhifuMima" :password="showPassword"
							border="none" @input="handleInput"></u--input>
						<img :src="!showPassword ? showpwdImg : hidepwdImg" @tap="showPassword = !showPassword"
							style="width: 50rpx;height: 50rpx;"></img>
					</view>
					<view class="modal-item-transfer zf_mod_item-transfer">
						<text class="modal-label-transfer">郵箱驗證碼:</text>
						<u--input color="#fff" style="width: 70%;" v-model="emailCode" border="none"></u--input>
						<view class="sendcode" @click="tosendemail">{{emaiTip}}</view>
					</view>
					<view class="modal-item-transfer zf_mod_item-transfer">
						<text class="modal-label-transfer">谷歌驗證碼:</text>
						<u--input color="#fff" style="width: 70%;" v-model="googleCode" border="none"></u--input>
						<view class="sendcode-transfer" @click="googleemail">{{googleTip}}</view>
					</view>
				</view>
				<view class="modal-footer-transfer">
					<button class="modal-button-transfer cancel" @tap="modalName = false">取消</button>
					<button class="modal-button-transfer confirm" @tap="modalBtn">確定</button>
				</view>
			</view>
		</view>
	    <view class="guide" v-if="guide">
            <view class="huadong">左右滑動,切換查看賬戶</view>
            <view @click="noTis" class="but">確 定</view>
        </view>
    </view>
</template>

<script>
	import uQRCode from '@/common/uqrcode.js'
	import item from '@/components/smarttrading/item.vue';
	import {
		_invest
	} from "@/request/aiInvestApi.js"
	import {
		_userInfos,
		_balances,
		_myIncome,
		_getstatics,
		_getcharge,
		_emailSend,
		_walletinfo,
		_pushorder,
		_moneyRedeem
	} from "@/request/api.js"
	import cardVue from '@/components/smarttrading/coinCard/card.vue';
	import {
		publicjiemi
	} from "@/common/jiemi.js";
	import MD5 from "blueimp-md5";
	export default {
		components: {
			item,
			cardVue
		},
		data() {
			return {
				moneyTab: 0,
				nowGasFee:"",
                guide:false,
				biTypes:['USDT',"BNB","ETH","BTC"],
				selectedOption:"",
				transferIcon:"",
				userInfos:{},
				userLoacalAddress:"",
				otherContractAddress: "",
				zhifuMima: "",
				emailCode: "",
				googleCode: "",
				emaiTip: "發送",
				googleTip: "發送",
				showPassword: true,
				showpwdImg: "static/icon/eye_on.png",
				hidepwdImg: "static/icon/eye_off.png",
				modalName: false,
				txhash: "",
				txTime:"",
				webviewInstance: null,
				webviewStyles: {
					progress: false,
					width: "0px",
					height: "0px"
				},
				userMoneyAdress: '0xa13b07154de9fe1e73bc09f84d14a789295b03de',
				qrcodeSize: 200,
				modalintMoney: false,
				currentTab: 0,
				text1: '1、投資有風險，交易需謹慎 2、每天下午四點前購買的產品，結算時間為:T+0。每天下午四點後購買的產品，結算時間為:T+1',
				invests: [], //投資列表
				incomes: [], //收益列表
				list: [],
				checkCoin: 'USDT',
				coinType: ['BNB', 'ETH', 'BTC'],
				coinIndex: 0,
				balabces: null,
				allsettlefee: {},
				investSearch: {
					page_size: 3,
					page_index: 1,
					totalPage: 0,
					invest_coin: 'BNB',
					option_type: 'CALL'
				},
			};
		},
		onReady() {
            
			// #ifdef APP
			// 獲取當前頁面
			const currentWebview = this.$scope.$getAppWebview();
			// 獲取web-view組件對象
			this.webviewInstance = currentWebview.children()[0];
			this.txhash = "";
			this.txTime = "";
			// #endif
		},
		onShow() {
			this.getUserInfos();
             this.guide = typeof uni.getStorageSync('guide') !== 'boolean'
		},
		mounted() {
			uni.showLoading({
				mask: true
			})
			this.getNowCoin(0);
			Promise.all([
				this.loadData(this.coinType[0]),
				this.loadData(this.coinType[1]),
				this.loadData(this.coinType[2]),
			]).then((res) => {
				res.map(arr => {
					if (arr.status === 200) {
						this.invests = this.invests.concat(arr.data.list)
					}
				})
				this.list = this.invests.sort((a, b) => b.purchaseEndTime - a.purchaseEndTime)
                this.list.sort((a, b) => b.apr - a.apr)
			}).finally(err => {
				uni.hideLoading()
			})
		},
		methods: {
			getNowCoin(e){
				_getstatics({ cointype: this.coinType[e] }).then(res => {
					console.log(res,'收益')
					res.code === 1 && (this.allsettlefee = res.data)
				})
			},
			onPickerChange(event){
				const index = event.detail.value; // 獲取選擇的索引
				this.selectedOption = this.biTypes[index]; 
			},
			handleInput(event) {
				this.zhifuMima = event;
			},
			async modalBtn() {
				console.log(this.moneyTab,'狀態');
				if (!this.zhifuMima || !this.emailCode || !this.googleCode || !this.selectedOption || !this.transferIcon) return uni.showToast({
					title: '請填寫完整資訊',
					icon: 'none'
				})
				const params = {
					code: this.emailCode,
					googlecode: this.googleCode,
					paykey: MD5(this.zhifuMima + (Math.floor(Date.now() / 1000))),
					timestamp: Math.floor(Date.now() / 1000),
				}
				let res = await _walletinfo(params);
				if (res.code === 1) {
					uni.showLoading({
						title:"轉換中..."
					})
					this.modalName = false;
					if(this.moneyTab == 0){
						let userSiyao = await publicjiemi(2, this.zhifuMima, this.userInfos.wallet.address);
						this.toTransfer(userSiyao);
					}else{
						this.toRedeem();
					}
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			async toRedeem(){
				const params = {
					cointype: this.selectedOption,
					amount: this.transferIcon
				};
				let res = await _moneyRedeem(params);
				console.log(res,'提現詳細');
				uni.hideLoading();
				if(res.code === 1){
					uni.showToast({
						title: "轉換申請成功！",
						icon: 'none'
					})
					this.getUserInfos();
					this.emailCode = "";
					this.googleCode = "";
					this.zhifuMima = "";
					this.emaiTip = "發送";
					this.googleTip = "發送";
					this.selectedOption = "";
					this.transferIcon = "";
				}else{
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			toTransfer(privateKey) {
				switch (this.selectedOption){
					case 'USDT':
						this.otherContractAddress = "0x55d398326f99059ff775485246999027b3197955";
						break;
					case 'ETH':
						this.otherContractAddress = "0x2170ed0880ac9a755fd29b2688956bd959f933f8";
						break;
					case 'BTCB':
						this.otherContractAddress = "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c";	
						break;
				}
				const params = {
					type:this.selectedOption,
					fromAdress: this.userInfos.wallet.address,
					toAdress: this.userMoneyAdress ,
					coin:this.transferIcon,
					privateKey,
					otherContractAddress:this.otherContractAddress
				};
				if (this.selectedOption == "BNB") {
					if (this.webviewInstance) {
						this.webviewInstance.evalJS(`
							bnbTransfer(${JSON.stringify(params)});
						`);
					}
				} else {
					if (this.webviewInstance) {
						this.webviewInstance.evalJS(`
							otherTransfer(${JSON.stringify(params)});
						`);
					}
				}
			},
			async tosendemail() {
				if (this.emaiTip == "發送") {
					let num = 60;
					let emaiTimer = setInterval(() => {
						this.emaiTip = num + 's';
						num--;
						if (num < 0) {
							this.emaiTip = "發送";
							clearInterval(emaiTimer)
						}
					}, 1000)
					let res = await _emailSend({
						email: this.userInfos.email,
						event: "check"
					});
					if (res.code === 1) {
						console.log('發送成功')
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				} else {
					return
				}
			},
			googleemail() {
				let num = 60;
				let googleTimer = setInterval(() => {
					this.googleTip = num + 's';
					num--;
					if (num < 0) {
						this.googleTip = "發送";
						clearInterval(googleTimer)
					}
				}, 1000)
			},
			// 接收WebView消息
			handleWebViewMessage(event) {
				let obj = event.detail.data;
				console.log('收到WebView消息:', obj);
				if (obj.length > 0) {
					if(obj[0].type != "gasFee"){
						uni.hideLoading();
						if (obj[0].status == "success") {
							this.txhash = obj[0].hash;
							this.txTime = obj[0].time;
							uni.showToast({
								title: "轉換成功！",
								icon: 'success'
							})
							this.pushOrderInfos();
						}
						if (obj[0].status == "error") {
							uni.showToast({
								title: "轉賬失敗！",
								icon: 'error'
							})
						}
						this.emailCode = "";
						this.googleCode = "";
						this.zhifuMima = "";
						this.emaiTip = "發送";
						this.googleTip = "發送";
						this.selectedOption = "";
						this.transferIcon = "";
					}
					if(obj[0].type == "gasFee"){
						this.nowGasFee = `${obj[0].nowGwei} Gwei(${obj[0].gasInBNB} BNB)`;
					}
				}
			},
			async pushOrderInfos() {
				const params = {
					address: "0xa13b07154de9fe1e73bc09f84d14a789295b03de", 
					addressTag: "", 
					amount: this.transferIcon, 
					coin: this.selectedOption, 
					completeTime: this.txTime, 
					confirmTimes: "15/15", 
					id: this.txTime, 
					insertTime: this.txTime, 
					network: "BSC", 
					status: 1, 
					transferType: 0, 
					txId: this.txhash, 
					unlockConfirm: 0, 
					walletType: 0,
					fromAddress: this.userInfos.wallet.address
				};
				const res = await _pushorder(params);
				console.log(res, '推送信息')
				if(res.code === 1){
					this.getUserInfos();
				}
			},
			toChangeTransfer() {
				// if (this.webviewInstance) {
				// 	this.webviewInstance.evalJS(`
				// 		searchGasFee();
				// 	`);
				// }
				this.modalName = true;
			},
			toBlanceDetail(){
				uni.navigateTo({
					url: '/pages/smarttrading/blanceDetail'
				})
			},
			async showUpgradeModal1() {
				this.modalintMoney = true;
				uni.showLoading({
					title: '二維碼生成中',
					mask: true
				})
				let qrcodeUrl = this.userLoacalAddress
				await uQRCode.make({
					canvasId: 'qrcodes',
					text: qrcodeUrl,
					size: this.qrcodeSize,
					margin: 10,
					success: res => {
						this.erweimapath = res
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},
			copyAdress(address) {
				uni.setClipboardData({
					data: address,
					success: () => {
						uni.showToast({
							title: '複製成功',
							icon: 'success'
						})
					}
				})
			},
			async getUserInfos() {
				let res = await _userInfos();
				if (res.code === 1) {
					this.userInfos = res.data.userinfo;
					this.userLoacalAddress = this.userInfos.wallet.address;
					uni.setStorageSync('infos', JSON.stringify(this.userInfos))
					const Money = await _getcharge()
					console.log(Money, 7777)
					// this.userMoneyAdress = this.userInfos.wallet.address;
					// const Money = await _balances(this.userInfos.wallet.address)
					this.balabces = {
						'BNB': '0.00',
						'ETH': '0.00',
						'BTC': '0.00',
						'USDT': '0.00'
					}
					Money.data.map(item => {
						this.balabces[item.coin] = item.amount
					})

					uni.setStorageSync('balabces', JSON.stringify(this.balabces))

				}
			},
			userMoneyAdressOptions1(data) {
				let start = data.substring(0, 14);
				let end = data.substring(data.length - 4);
				let middle = "…";
				let finalString = start + middle + end;
				return finalString
			},
			async switchTab(item) {
				this.list = []
				this.currentTab = item.index
				if (this.incomes.length === 0) {
					await this.loadIncome()
				}
                this.list = this.invests
                if(item.index == 1){
                  let arr = this.incomes.map(item => {
					  const info ={...item.info,money:item.money,}
                      return info
                  })   
                  this.list = arr.sort((a, b) => b.createTimes - a.createTimes)
                }
			},
			switchMoneytab(item){
				this.moneyTab = item.index
			},
			async loadIncome() { // 獲取我的收益列表數據
				uni.showLoading({
					mask: true
				})
				const res = await _myIncome()
				if (res.code === 1) {
					this.incomes = [...res.data.data]
                    
				}
				uni.hideLoading()

			},
			// 獲取投資列表數據
			loadData(type) {
				return new Promise(async (resolve) => {
					let search = {
						...this.investSearch
					}
					search.invest_coin = type
					delete search.totalPage
					let params = ''
					Object.keys(search).map(item => {
						params += `${item}=${search[item]}&`
					})

					params = params.slice(0, -1)
					const res = await _invest(params)
					resolve(res)
				})
			},
			more() {
				const url = this.currentTab === 0 ? 'recommend' : 'incomes'
				uni.navigateTo({
					url: `/pages/smarttrading/${url}?type=1`
				})
			},
			tobuy() {
				uni.navigateTo({
					url: '/pages/smarttrading/buy'
				})
			},
            noTis(){
                uni.setStorageSync('guide',false)
                this.guide = false
            },

		}
	}
</script>

<style lang="scss">
	.container {
		position: relative;
		min-height: 100vh;
		.nodata {
			height: 64px;
			line-height: 64px;
			text-align: center;
			color: #A4A4A4;
		}

		border-top: 1px solid dimgrey;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		padding: 18px 18px 0px;
		box-sizing: border-box;
		background: linear-gradient(to bottom, #000033, #51599b);

		.mybal {
			font-size: 24rpx;
			color: #A4A4A4;
			margin-bottom: 10rpx;
		}

		.cards {
			position: relative;
			margin-bottom: 24px;
			min-height: 196px;
		}

		.invest {
			margin-top: 30rpx;
			background-color: #fff;
			padding: 0px 24rpx 24rpx;
			border-radius: 30rpx;
		}
	}

	.modal1 {
		width: 80vw;
		height: 50vh;
		position: fixed;
		top: 62.7%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.9);
		z-index: 999;

		.modal1-content {
			width: 100%;
			height: 100%;
			position: relative;
			padding: 20rpx;
			box-sizing: border-box;

			.modal1-header {
				height: 10%;
				width: 100%;
				text-align: right;
				color: #fff;
				font-size: 50rpx;
			}

			.modal1-txt {
				height: 75%;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.modal1-footer {
				width: 100%;
				display: flex;
				align-items: center;
				height: 15%;
				color: #fff;
				font-size: 15px;
			}
		}
	}

	.coinTag {
		padding: 4px 12px;
		border-radius: 24px;
		border: 1rpx solid #4F5AD7;
		font-size: 28rpx;
		color: #4F5AD7;

		&.checked {
			background-color: #4F5AD7;
			color: #fff;
		}
	}
	.modal-transfer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		align-items: flex-end;
		z-index: 999;
	}
	
	.modal-content-transfer {
		background-color: #b6b5c8;
		border-radius: 20px 20px 0 0;
		padding: 10px 20px 20px;
		box-sizing: border-box;
		width: 100%;
		animation: slideUp 0.3s ease-out;
		box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.1);
	}
	
	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}
	
		to {
			transform: translateY(0);
		}
	}
	
	.modal-header-transfer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}
	
	.modal-body-transfer {
		margin-bottom: 20px;
	}
	
	.modal-item-transfer {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		padding-bottom: 10px;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.zf_mod_item-transfer {
		display: flex;
		align-items: center;
	}
	
	.modal-label-transfer {
		color: #666;
		font-size: 14px;
		margin-right: 20rpx;
	}
	
	.modal-footer-transfer {
		display: flex;
		justify-content: space-between;
	}
	
	.modal-button-transfer {
		width: 48%;
		height: 44px;
		border-radius: 22px;
		font-size: 16px;
		font-weight: bold;
		border: none;
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.modal-button-transfer.cancel {
		background-color: #f0f0f0;
		color: #333;
	}
	
	.modal-button-transfer.cancel:hover {
		background-color: #e0e0e0;
	}
	
	.modal-button-transfer.confirm {
		background-color: #4CAF50;
		color: white;
	}
	
	.modal-button-transfer.confirm:hover {
		background-color: #45a049;
	}
 .guide{
     background-color: rgba(0, 0, 0, .2);
     position: fixed;
     left:0;
     top:0;
     width: 100%;
     height: 100vh;
     z-index: 999;
     .huadong{
          background-color: rgba(0, 0, 0, .4);
          position: absolute;
          top:64px;
          left: 18px;
          width: calc(100% - 36px);
          height: 192px;
          line-height: 192px;
          border-radius: 8px;
          color: #fff;
          text-align: center;
     }
     .but{
         position: absolute;
         bottom:80px;
         left: calc(50% - 50px);
         width: 100px;
         line-height: 42px;
         text-align: center;
          background-color: rgba(0, 0, 0, .8);
          color: #fff;
          border-radius: 24px;
         height:42px;
     }
 }   
</style>