<template>
	<view class="box">
		<view class="box-list">
			<view class="uni-flex uni-row" style="border-bottom: 1rpx solid #E7E7E7; padding-bottom: 6px;">
				<view class="uni-flex-item">
					<u-tabs :current="currentTab" inactiveStyle="{color: rgba(142, 142, 147, 1)}"
						:list="[{name:'轉換'},{name:'投資'},{name:'收益'},{name:'推荐收益'}]" @click="switchTab"></u-tabs>
				</view>
				<view class="coinItem" @click="show=true">
					<u--text suffixIcon="arrow-down" customStyle="color:#4F5AD7;"
						iconStyle="font-size: 16px; padding-left:8px;" :text="coins[coinIndex]"></u--text>
				</view>
			</view>
			<view class="box-main">
				<scroll-view scroll-y :style="{ height: scrollHeight + 'px' }" @scrolltolower="loadMore">
					<view v-for="item in list" class="list_item" :key="item.id">
						<view class="list_title" v-if="currentTab != 2 && currentTab != 3">
							<image :src="imgs[coins[coinIndex]]" mode="heightFix"></image>
							<text>{{coins[coinIndex]}}</text>
						</view>
						<view v-if="currentTab == 0" class="list_txt">時間：<text>{{ timeOptin(item.insertTime - 0) }}</text></view>
						<view v-if="currentTab == 0" class="list_txt">數量：<text :class="`text_${coins[coinIndex]}`"> {{ item.transferType == 'out' ? '-' : '+'}} {{ item.amount.replace('-',"") || 0 }} {{coins[coinIndex]}}</text></view>
						<view v-if="currentTab == 0 && item.transferType == 'out'" class="list_txt">GAS費：{{ item.gasFees }} BNB</view>
						<view v-if="currentTab == 0" class="list_txt">
							狀態：
							<text v-if="item.txId">已完成</text>
							<text v-else>AI交割中</text>
						</view>
						
						<view v-if="currentTab == 1" class="list_txt">時間：<text>{{ timeOptin(item.settletime * 1000) }}</text></view>
						<view v-if="currentTab == 1" class="list_txt">數量：<text :class="`text_${coins[coinIndex]}`"> - {{ item.money || 0 }} {{coins[coinIndex]}}</text></view>
						<!-- 收益 -->
						<recordVue v-if="currentTab == 2" :item="item"/>
						<!-- 推荐人奖励 -->
						<view v-if="currentTab == 3" class="list_txt list_txt_tui">
							<view>地址：</view>
							<view class="color-black" @click="copyAddress(item.address)">{{ addressOption(item.address) }}</view>
						</view>
						<view v-if="currentTab == 3" class="list_txt list_txt_tui">
							<view>购买量化产品：</view>
							<view :class="`text_${coins[coinIndex]}`">+{{ item.amount + " " + coins[coinIndex]}}</view>
						</view>
						<view v-if="currentTab == 3" class="list_txt list_txt_tui">
							<view>时间：</view>
							<view class="color-black">{{ timeOptin(item.createtime * 1000) }}</view>
						</view>
					</view>
					<view v-if="!loading && (list.length === 0 || search.page >= totalPages)" class="nodata">
						{{list.length === 0 ? '暫無數據' : '暫無更多數據'}}
					</view>
				</scroll-view>
			</view>
			<u-popup :show="show" mode="bottom" @close="show = false" round="10" :closeable="false">
				<view style=" width: 100%; padding: 32px 0;">
					<view class="uni-flex uni-row" style="justify-content: space-around;">
						<view @click="changeCoin(i)" class="coinTag" :class="{'checked':coinIndex === i}"
							v-for="(coin , i) in coins" :key="coin">{{coin}}
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import recordVue from "@/components/record.vue";
	import {
		_getrechargelogs, //獲取充值記錄
		_getinvestlogs, //獲取投資記錄
		_getexerciselogs ,//獲取收益記錄
		_quantifyrewardlogs //获取推荐收益记录
	} from "@/request/api.js"
	export default {
		components:{
			recordVue
		},
		data() {
			return {
				imgs: {
					USDT: '/static/usdt.png',
				    BNB: '/static/bnb.png',
				    ETH: '/static/eth.png',
				    BTC: '/static/btc.png'
				},
				show: false,
				list: [],
				currentTab: 0,
				loading: false,
				coinIndex: 0,
				coins: ['USDT', 'BNB', 'ETH', 'BTC'],
				scrollHeight: 0,
				totalPages: 1,
				search: {
					cointype: "USDT",
					listrow: 5,
					page: 1
				}
			}
		},
		onLoad() {
			this.calculateScrollHeight();
			this.resetAndLoadData();
		},
		methods: {
			async gasSearch(hash){
				let gasFee = await new Promise((resolve, reject) => {
				    uni.request({
				        url: "https://nfta.ikiry.com/searchGasused?hash=" + hash,
				        success(res) {
				            resolve(res.data.gasFeeEther); 
				        },
				        fail(err) {
				            console.log(err);
				            reject(err); 
				        }
				    });
				});
				return gasFee
			},
			copyAddress(address){
				uni.setClipboardData({
					data: address,
					success: () => {
						uni.showToast({
							title: '複製成功',
							icon: 'success'
						})
					}
				})
			},
			addressOption(addr){
				if(addr){
					let start = addr.substring(0, 6);
					let end = addr.substring(addr.length - 6);
					let middle = "…";
					let finalString = start + middle + end;
					return finalString
				}
			},
			timeOptin(timestamp){
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份從0開始，所以要加1
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			async loadData() {
				if (this.loading) return;
				this.loading = true;
				let api;
				switch (this.currentTab) {
					case 0:
						api = _getrechargelogs;
						break;
					case 1:
						api = _getinvestlogs;
						break;
					case 2:
						api = _getexerciselogs;
						break;
					case 3:
						api = _quantifyrewardlogs;
						break;
					default:
						api = _getrechargelogs;
				}
				try {
					if (this.search.page === 1) {
						uni.showLoading({
							mask: true,
							title: '數據加載中...'
						});
					}
					const res = await api(this.search);
					if (res.code === 1) {
						if (this.search.page === 1) {
							this.list = res.data.data || [];
						} else {
							this.list = this.list.concat(res.data.data || []);
						}
						this.totalPages = (res.data.total / 5) || 1;
						
						await Promise.all(this.list.map(async (item) => {
							if(item.transferType == 'out') {
								item.gasFees = await this.gasSearch(item.txId);
							} else {
								item.gasFees = "";
							}
						}));
					} else {
						uni.showToast({
							title: res.msg || '加載失敗',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('Data loading error:', error);
					uni.showToast({
						title: '網絡異常，請稍後重試',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					uni.hideLoading();
				}
			},
			// 加載更多
			loadMore() {
				if (this.loading) return;
				if (this.search.page >= this.totalPages) return;
				this.search.page++;
				this.loadData();
			},

			// 重置並加載數據
			resetAndLoadData() {
				this.search.page = 1;
				this.list = [];
				this.loadData();
			},
			// 計算滾動區域高度
			calculateScrollHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.scrollHeight = systemInfo.windowHeight - 100; // 減去其他元素高度
			},
			// 切換標籤頁
			switchTab(item) {
				if (this.currentTab === item.index) return;
				this.currentTab = item.index;
				this.resetAndLoadData();
			},
			// 切換幣種
			changeCoin(index) {
				this.show = false;
				if (this.coinIndex === index) return;
				this.coinIndex = index;
				this.search.cointype = this.coins[index];
				this.resetAndLoadData();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.nodata {
		height: 64px;
		line-height: 64px;
		text-align: center;
		color: #A4A4A4;
	}

	.text_USDT{
		color:#1ABA84 !important; 
	}
	.text_BNB{
	    color: #EEB80B !important;
	}
	.text_ETH{
	    color: #5E81F3 !important;
	}
	.text_BTC{
	    color: #F5921A !important;
	}

	.box {
		background-color: #000033;
		height: 100vh;
		padding: 32rpx 32rpx 0;
		box-sizing: border-box;
		width: 100%;

		.box-list {
			height: 100%;
			width: 100%;
			box-sizing: border-box;
			border-radius: 18px 18px 0 0;
			background-color: #fff;

			.title {
				border-bottom: 1px silver solid;
				padding: 12px 18px;
			}

			.box-main {
				height: calc(100vh - 70px);
				overflow-y: scroll;
				overflow-x: hidden;
				padding: 0 12px;
				.list_item{
					width: 100%;
					padding: 40rpx 0;
					border-bottom: 1px solid #E7E7E7;
					.list_title{
						display: flex;
						align-items: center;
						margin-bottom: 15rpx;
						image{
							height: 100rpx;
						}
						text{
							font-weight: 700;
							margin-left: 40rpx;
							font-size: 35rpx;
						}
					}
					.list_txt{
						color: #A4A4A4;
						margin-top: 15rpx;
						text{
							color: #000;
						}
					}
					.list_txt_tui{
						display: flex;
						justify-content: space-between;
						.color-black{
							color: #000;
						}
					}
				}
			}
		}

		.coinItem {
			flex-basis: 52px;
			height: 44px;
			line-height: 52px;
			text-align: end;
			padding-right: 24px;
			color: #4F5AD7;
		}

		.coinTag {
			padding: 4px 12px;
			border-radius: 2px;
			border: 1rpx solid #4F5AD7;
			transform: skewX(-10deg);
			font-size: 28rpx;
			color: #4F5AD7;

		}

		.checked {
			background-color: #4F5AD7;
			color: #fff;
		}
	}
</style>