<!-- 
	打赏面板组件
-->
<template>
	<view>
		<uni-popup ref="giftPanel" type="bottom" @change="onChange">
			<view class="hl88-lr-gp">
				<view class="hl88-lr-gp-header">
					<text class="hl88-lr-gp-title">{{ langTexts.selectGift }}</text>
					<text class="hl88-lr-gp-close" @tap="close">✕</text>
				</view>
				
				<scroll-view scroll-x="true" class="hl88-lr-gp-list">
					<!-- 加载状态 -->
					<view v-if="giftLoading && giftList.length === 0" class="hl88-lr-gp-loading">
						<text class="hl88-lr-gp-loadTx">{{ langTexts.loading }}</text>
					</view>
					<!-- 礼物列表 -->
					<view 
						v-else-if="giftList.length > 0"
						class="hl88-lr-gp-item" 
						v-for="(item, index) in giftList" 
						:key="item.id || index"
						:class="{ 'hl88-lr-gp-itemSel': selectedIndex === index }"
						@tap="selectGift(index)"
					>
					<image :src="getGiftImage(item.image)" class="hl88-lr-gp-itemImg" mode="aspectFit"></image>
					<text class="hl88-lr-gp-itemNm">{{ item.name }}</text>
					<view class="hl88-lr-gp-itemPr">
						<image src="/static/imgs/icon/ic_diamond.png" class="hl88-lr-gp-itemPrIc" mode="aspectFit"></image>
						<text class="hl88-lr-gp-itemPrTx">{{ item.price }}</text>
					</view>
					</view>
					<!-- 空状态 -->
					<view v-else class="hl88-lr-gp-empty">
						<text class="hl88-lr-gp-emptyTx">{{ langTexts.noGifts }}</text>
					</view>
				</scroll-view>
				
				<view class="hl88-lr-gp-footer">
					<view class="hl88-lr-gp-balance">
						<text class="hl88-lr-gp-balLb">{{ langTexts.balance }}</text>
						<text class="hl88-lr-gp-balVal">{{ balance }}</text>
					</view>
					<view class="hl88-lr-gp-actions">
						<view class="hl88-lr-gp-cntSel">
							<text class="hl88-lr-gp-cntBtn" @tap="decreaseCount">-</text>
							<text class="hl88-lr-gp-cntVal">{{ count }}</text>
							<text class="hl88-lr-gp-cntBtn" @tap="increaseCount">+</text>
						</view>
						<view class="hl88-lr-gp-sendBtn" @tap="sendGift">
							<text class="hl88-lr-gp-sendTx">{{ langTexts.send }} ({{ totalPrice }})</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		
		<!-- 钻石余额不足弹框 -->
		<live-room-insufficient-balance-modal
			:show="showInsufficientBalanceModal"
			:title="langTexts.insufficientBalance"
			:subtitle="langTexts.rechargeToContinue"
			:buttonText="langTexts.goToRecharge"
			@close="closeInsufficientBalanceModal"
			@confirm="goToRecharge"
		/>
	</view>
</template>

<script>
import liveRoomInsufficientBalanceModal from '@/components/live-room/insufficient-balance-modal.vue';
import { get, post } from '@/core/http/http-client'
import appSettings from '@/core/config/app-settings'

export default {
	name: 'LiveRoomGiftPanel',
	components: {
		liveRoomInsufficientBalanceModal
	},
	data() {
		return {
			selectedIndex: 0,
			count: 1,
			balance: 0,
			giftList: [],
			giftLoading: false,
			current_page: 1,
			last_page: 1,
			cdnUrl: '',
			// 是否显示余额不足弹框
			showInsufficientBalanceModal: false,
			// 待发送的礼物信息（余额不足时保存）
			pendingGiftInfo: null,
			// 语言文本变量
			langTexts: {
				selectGift: '',
				loading: '',
				noGifts: '',
				balance: '',
				send: '',
				pleaseSelectGift: '',
				missingLiveId: '',
				insufficientBalance: '',
				rechargeToContinue: '',
				goToRecharge: '',
				sendFailed: '',
				success: '',
				defaultGiftName: ''
				}
		}
	},
	computed: {
		totalPrice() {
			const selectedGift = this.giftList[this.selectedIndex]
			return selectedGift ? selectedGift.price * this.count : 0
		}
	},
	mounted() {
		this.cdnUrl = (getApp().globalData && getApp().globalData.config && getApp().globalData.config.cdnurl)
			|| appSettings.cdnurl
			|| ''
		this.initLanguageStrings()
		this.loadBalance()
		this.loadGiftList()
	},
	methods: {
		// 初始化语言文本
		initLanguageStrings() {
			const locale = uni.getLocale() || 'zh-cn';
			const savedLanguage = uni.getStorageSync('language');
			const currentLang = savedLanguage || locale;
			
			// 语言文本映射
			const languageMap = {
				'zh-cn': {
					selectGift: '选择礼物',
					loading: '加载中...',
					noGifts: '暂无礼物',
					balance: '钻石：',
					send: '送出',
					pleaseSelectGift: '请选择礼物',
					missingLiveId: '缺少直播间ID',
					insufficientBalance: '余额不足',
					sendFailed: '打赏失败',
					success: '成功',
					defaultGiftName: '礼物'
				},
				'zh-Hant': {
					selectGift: '選擇禮物',
					loading: '加載中...',
					noGifts: '暫無禮物',
					balance: '鑽石：',
					send: '送出',
					pleaseSelectGift: '請選擇禮物',
					missingLiveId: '缺少直播間ID',
					insufficientBalance: '餘額不足',
					rechargeToContinue: '儲值後才可繼續購買',
					goToRecharge: '去儲值',
					sendFailed: '打賞失敗',
					success: '成功',
					defaultGiftName: '禮物'
				},
				'en': {
					selectGift: 'Select Gift',
					loading: 'Loading...',
					noGifts: 'No gifts available',
					balance: 'Diamond: ',
					send: 'Send',
					pleaseSelectGift: 'Please select a gift',
					missingLiveId: 'Missing live room ID',
					insufficientBalance: 'Insufficient balance',
					rechargeToContinue: 'Recharge to continue purchasing',
					goToRecharge: 'Recharge',
					sendFailed: 'Send failed',
					success: 'Success',
					defaultGiftName: 'Gift'
				},
				'en-SG': {
					selectGift: 'Select Gift',
					loading: 'Loading...',
					noGifts: 'No gifts available',
					balance: 'Diamond: ',
					send: 'Send',
					pleaseSelectGift: 'Please select a gift',
					missingLiveId: 'Missing live room ID',
					insufficientBalance: 'Insufficient balance',
					rechargeToContinue: 'Recharge to continue purchasing',
					goToRecharge: 'Recharge',
					sendFailed: 'Send failed',
					success: 'Success',
					defaultGiftName: 'Gift'
				},
				'en-MY': {
					selectGift: 'Select Gift',
					loading: 'Loading...',
					noGifts: 'No gifts available',
					balance: 'Diamond: ',
					send: 'Send',
					pleaseSelectGift: 'Please select a gift',
					missingLiveId: 'Missing live room ID',
					insufficientBalance: 'Insufficient balance',
					rechargeToContinue: 'Recharge to continue purchasing',
					goToRecharge: 'Recharge',
					sendFailed: 'Send failed',
					success: 'Success',
					defaultGiftName: 'Gift'
				},
				'ja': {
					selectGift: 'ギフトを選択',
					loading: '読み込み中...',
					noGifts: 'ギフトがありません',
					balance: '残高：',
					send: '送る',
					pleaseSelectGift: 'ギフトを選択してください',
					missingLiveId: 'ライブルームIDが不足しています',
					insufficientBalance: '残高不足',
					rechargeToContinue: 'チャージ後に購入を続けることができます',
					goToRecharge: 'チャージへ',
					sendFailed: '送信失敗',
					success: '成功',
					defaultGiftName: 'ギフト'
				}
			};
			
			// 根据当前语言设置文本，如果不存在则使用简体中文
			const texts = languageMap[currentLang] || languageMap['zh-cn'];
			this.langTexts = {
				selectGift: texts.selectGift,
				loading: texts.loading,
				noGifts: texts.noGifts,
				balance: texts.balance,
				send: texts.send,
				pleaseSelectGift: texts.pleaseSelectGift,
				missingLiveId: texts.missingLiveId,
				insufficientBalance: texts.insufficientBalance,
				rechargeToContinue: texts.rechargeToContinue,
				goToRecharge: texts.goToRecharge,
				sendFailed: texts.sendFailed,
				success: texts.success,
				defaultGiftName: texts.defaultGiftName
			};
		},
		open() {
			// 打开时若列表为空则重新拉取，避免 mounted 时请求失败后一直空白
			if (!this.giftList.length) {
				this.loadGiftList()
			}
			this.loadBalance()
			this.$refs.giftPanel.open()
		},
		close() {
			this.$refs.giftPanel.close()
		},
		onChange(e) {
			this.$emit('change', e)
		},
		selectGift(index) {
			this.selectedIndex = index
			this.count = 1
		},
		increaseCount() {
			this.count++
		},
		decreaseCount() {
			if (this.count > 1) {
				this.count--
			}
		},
		sendSimulationGift(){
			const selectedGift = this.giftList[this.selectedIndex]
			if (!selectedGift) return
			
			// 模拟发送礼物（用于测试）
			this.$emit('gift-sent', {
				gift: selectedGift,
				count: this.count,
				totalPrice: this.totalPrice
			})
		},
		async sendGift() {
			const selectedGift = this.giftList[this.selectedIndex]
			if (!selectedGift) {
				uni.showToast({
					title: this.langTexts.pleaseSelectGift,
					icon: 'none'
				})
				return
			}
			
			if (!this.liveId) {
				uni.showToast({
					title: this.langTexts.missingLiveId,
					icon: 'none'
				})
				return
			}
			
			// 检查余额
			if (this.totalPrice > this.balance) {
				// 余额不足，保存礼物信息，然后显示余额不足弹框
				this.pendingGiftInfo = {
					liveId: this.liveId,
					giftId: selectedGift.id,
					giftName: selectedGift.name,
					giftImage: selectedGift.image,
					count: this.count,
					totalPrice: this.totalPrice,
					timestamp: Date.now()
				};
				
				// 显示余额不足弹框
				this.showInsufficientBalanceModal = true;
				return;
			}
			
			// 发送打赏请求
			try {
				const { data } = await post('/wanlshop/pay/sendgift', {
					id: Number(this.liveId),
					gift_id: Number(selectedGift.id),
					number: Number(this.count) || 1
				})

				this.$emit('gift-sent', {
					gift: selectedGift,
					count: this.count,
					totalPrice: this.totalPrice
				})

				if (typeof data === 'string' || typeof data === 'number') {
					this.balance = Number(data) || 0
				} else if (data && typeof data === 'object' && data.balance !== undefined) {
					this.balance = Number(data.balance) || 0
				} else {
					this.balance = Math.max(0, this.balance - this.totalPrice)
				}

				this.close()
				uni.showToast({
					title: this.langTexts.success,
					icon: 'success'
				})
			} catch (error) {
				console.error('Send gift error:', error)
				uni.showToast({
					title: (error && error.message) ? error.message : this.langTexts.sendFailed,
					icon: 'none'
				})
			}
		},
		async loadBalance() {
			try {
				const { data } = await get('/user/getdiamondnum')
				if (typeof data === 'string' || typeof data === 'number') {
					this.balance = Number(data) || 0
					return
				}
				if (data != null && typeof data === 'object') {
					if (data.diamond != null) {
						this.balance = Number(data.diamond) || 0
						return
					}
					if (data.data != null && typeof data.data === 'object' && data.data.diamond != null) {
						this.balance = Number(data.data.diamond) || 0
						return
					}
				}
				this.balance = Number(data) || 0
			} catch (error) {
				console.error('Load balance error:', error)
				this.balance = 0
			}
		},
		// 加载礼物列表
		async loadGiftList() {
			if (this.giftLoading) return
			this.giftLoading = true
			try {
				const { data, raw } = await get('/wanlshop/livegift/list', {
					page: this.current_page
				})
				console.log('[gift-panel] livegift/list raw=', raw && raw.res, 'data=', data)

				// http-client 已解包 code===1 的 data；兼容数组 / 分页对象 / 仍带 envelope
				let payload = data
				if (payload && typeof payload === 'object' && payload.code !== undefined) {
					payload = payload.data
				}
				if ((!payload || (typeof payload === 'object' && !Array.isArray(payload) && !payload.data)) && raw && raw.res) {
					const env = raw.res
					payload = (env && env.code !== undefined) ? env.data : env
				}

				const list = Array.isArray(payload)
					? payload
					: (payload && Array.isArray(payload.data) ? payload.data
						: (payload && Array.isArray(payload.list) ? payload.list : []))

				const currentPage =
					(payload && payload.current_page) ? payload.current_page :
					this.current_page
				const lastPage =
					(payload && payload.last_page) ? payload.last_page :
					currentPage

				this.current_page = Number(currentPage) || 1
				this.last_page = Number(lastPage) || 1

				if (list.length > 0) {
					this.giftList = list.map(item => ({
						id: item.id,
						name: item.title || item.name || item.gift_name || this.langTexts.defaultGiftName,
						image: item.image || item.gift_image || item.icon || '',
						price: Number(item.price || item.gift_price || 0),
						type: item.type || item.gift_type || 'default',
						svga: item.show_image || item.svga || item.animation || ''
					}))
					if (this.selectedIndex >= this.giftList.length) {
						this.selectedIndex = 0
					}
				} else {
					this.giftList = []
					console.warn('[gift-panel] livegift/list 返回空列表')
				}
			} catch (error) {
				console.error('Load gift list error:', error)
				this.giftList = []
			} finally {
				this.giftLoading = false
			}
		},
		// 获取礼物图片完整URL
		getGiftImage(imageUrl) {
			if (!imageUrl) return ''
			if (/^(http|https):\/\/.+/.test(imageUrl)) {
				return imageUrl
			}
			const base = this.cdnUrl || appSettings.cdnurl || ''
			return base ? (base + imageUrl) : imageUrl
		},
		// 关闭余额不足弹框
		closeInsufficientBalanceModal() {
			this.showInsufficientBalanceModal = false;
			this.pendingGiftInfo = null;
		},
		// 跳转到充值页面
		goToRecharge() {
			// 关闭余额不足弹框
			this.closeInsufficientBalanceModal();
			
			// 关闭礼物面板
			this.close();
			
			// 保存礼物信息到本地存储
			if (this.pendingGiftInfo) {
				uni.setStorageSync('pending_gift', this.pendingGiftInfo);
			}
			
			// 跳转到充值页面，传递直播间ID
			uni.navigateTo({
				url: '/pages/user/money/diamond-top-up?from=gift&liveId=' + this.liveId
			});
		}
	},
	props: {
		liveId: {
			type: Number,
			default: 0
		}
	}
}
</script>

<style scoped>
.hl88-lr-gp {
	background-color: rgba(255, 255, 255, 0.95);
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	/* #ifndef APP-NVUE */
	padding-bottom: env(safe-area-inset-bottom);
	/* #endif */
	/* #ifdef APP-NVUE */
	padding-bottom: 20rpx;
	/* #endif */
}

.hl88-lr-gp-header {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom-width: 1rpx;
	border-bottom-style: solid;
	border-bottom-color: #eeeeee;
}

.hl88-lr-gp-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.hl88-lr-gp-close {
	font-size: 40rpx;
	color: #999999;
	width: 60rpx;
	height: 60rpx;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	align-items: center;
	justify-content: center;
}

.hl88-lr-gp-list {
	/* #ifndef APP-NVUE */
	white-space: nowrap;
	/* #endif */
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	/* #ifdef APP-NVUE */
	flex-direction: row;
	/* #endif */
}

.hl88-lr-gp-item {
	/* #ifndef APP-NVUE */
	display: inline-block;
	/* #endif */
	width: 160rpx;
	margin-left: 15rpx;
	margin-right: 15rpx;
	/* #ifndef APP-NVUE */
	text-align: center;
	/* #endif */
	/* #ifdef APP-NVUE */
	align-items: center;
	justify-content: center;
	flex-direction: column;
	/* #endif */
	padding: 20rpx;
	border-radius: 15rpx;
	border-width: 2rpx;
	border-style: solid;
	border-color: transparent;
	/* #ifndef APP-NVUE */
	transition: all 0.3s;
	/* #endif */
}

.hl88-lr-gp-itemSel {
	border-color: #f72b36;
	background: rgba(247, 43, 54, 0.1);
}

.hl88-lr-gp-itemImg {
	width: 100rpx;
	height: 100rpx;
	margin-bottom: 10rpx;
	/* #ifdef APP-NVUE */
	margin-top: 0;
	margin-left: 0;
	margin-right: 0;
	/* #endif */
}

.hl88-lr-gp-itemNm {
	/* #ifndef APP-NVUE */
	display: block;
	/* #endif */
	font-size: 24rpx;
	color: #333333;
	margin-bottom: 5rpx;
}

.hl88-lr-gp-itemPr {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	align-items: center;
	justify-content: center;
	font-size: 22rpx;
	color: #f72b36;
	font-weight: bold;
}

.hl88-lr-gp-itemPrIc {
	width: 24rpx;
	height: 24rpx;
	margin-right: 4rpx;
}

.hl88-lr-gp-itemPrTx {
	font-size: 22rpx;
	color: #f72b36;
	font-weight: bold;
}

.hl88-lr-gp-footer {
	padding: 20rpx 30rpx;
	border-top-width: 1rpx;
	border-top-style: solid;
	border-top-color: #eeeeee;
}

.hl88-lr-gp-balance {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.hl88-lr-gp-balLb {
	font-size: 28rpx;
	color: #666;
}

.hl88-lr-gp-balVal {
	font-size: 32rpx;
	color: #f72b36;
	font-weight: bold;
}

.hl88-lr-gp-actions {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}

.hl88-lr-gp-cntSel {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	align-items: center;
	border-width: 1rpx;
	border-style: solid;
	border-color: #dddddd;
	border-radius: 10rpx;
	/* #ifndef APP-NVUE */
	overflow: hidden;
	/* #endif */
}

.hl88-lr-gp-cntBtn {
	width: 60rpx;
	height: 60rpx;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #333333;
	background-color: #f5f5f5;
}

.hl88-lr-gp-cntVal {
	min-width: 80rpx;
	/* #ifndef APP-NVUE */
	text-align: center;
	/* #endif */
	font-size: 28rpx;
	color: #333333;
	padding-left: 20rpx;
	padding-right: 20rpx;
}

.hl88-lr-gp-sendBtn {
	/* #ifndef APP-NVUE */
	background: linear-gradient(135deg, #f72b36 0%, #ff6b6b 100%);
	/* #endif */
	/* #ifdef APP-NVUE */
	background-color: #f72b36;
	/* #endif */
	border-radius: 50rpx;
	padding: 20rpx 40rpx;
	margin-left: 20rpx;
}

.hl88-lr-gp-sendTx {
	color: #fff;
	font-size: 28rpx;
	font-weight: bold;
}

.hl88-lr-gp-loading {
	padding: 40rpx;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	align-items: center;
	justify-content: center;
}

.hl88-lr-gp-loadTx {
	font-size: 28rpx;
	color: #999999;
}

.hl88-lr-gp-empty {
	padding: 40rpx;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	align-items: center;
	justify-content: center;
}

.hl88-lr-gp-emptyTx {
	font-size: 28rpx;
	color: #999999;
}
</style>

