<template>
	<!-- 悬浮按钮 -->
	<view v-if="pageCount == 1 || need" class="fixed-box" :style="{ height: fixBtnShow ? '330rpx' : '120rpx' }">
		<!-- AI智能助手 -->
		<view class="btn-item" v-if="fixBtnShow && enableAIChat" @click="openAIChat"
			:style="{backgroundImage:'url('+(aiAgentimg?aiAgentimg:'')+')',backgroundSize:'100% 100%'}">
			<text class="ai-icon" v-if="!aiAgentimg">🤖</text>
			<view v-if="unreadCount > 0" class="unread-badge">
				<text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
			</view>
		</view>

		<!-- 客服按钮 -->
		<button class="btn-item" v-if="fixBtnShow" hoverClass="none" @click="openKefuSelectPopup"
			:style="{ backgroundImage: 'url(' + (kefuimg ? kefuimg : '') + ')', backgroundSize: '100% 100%' }">
			<text class="icox icox-kefu" v-if="!kefuimg"></text>
		</button>

		<!-- 电话按钮 -->
		<view class="btn-item" v-if="fixBtnShow" @click="call()"
			:style="{ backgroundImage: 'url(' + (phoneimg ? phoneimg : '') + ')', backgroundSize: '100% 100%' }">
			<text class="iconfont icon-dianhua" v-if="!phoneimg"></text>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex' // 去掉mapMutations，直接用$store.commit
	import { createCustomerService } from '@/common/js/customer-service.js';

	export default {
		name: 'hover-nav',
		props: {
			need: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				pageCount: 0,
				fixBtnShow: true,
				tel: '',
				kefuimg: '',
				phoneimg: '',
				customerService: null,
				buttonConfig: null,
				kefuList: [
					{ id: 'weixin-official', name: '微信官方客服', isOfficial: true, type: 'weapp' },
					{ id: 'custom-kefu', name: '自定义在线客服', isOfficial: false, type: 'custom' },
					{ id: 'qyweixin-kefu', name: '企业微信客服', isOfficial: false, type: 'qyweixin' }
				],
				selectedKefu: null
			};
		},
		created() {
			this.kefuimg = this.$util.getDefaultImage().kefu
			this.phoneimg = this.$util.getDefaultImage().phone
			this.pageCount = getCurrentPages().length;
			this.selectedKefu = this.kefuList[0];
			this.customerService = createCustomerService(this);
			this.buttonConfig = this.customerService.getButtonConfig();

			uni.getStorage({
				key: 'shopInfo',
				success: (e) => { this.tel = e.data.mobile }
			})
		},
		computed: {
			...mapGetters([
				'globalAIKefuConfig',
				'aiUnreadCount'
			]),
			aiAgentimg() {
				return this.globalAIKefuConfig?.icon || this.$util.getDefaultImage().aiAgent || ''
			},
			unreadCount() {
				return this.aiUnreadCount
			},
			enableAIChat() {
				return this.globalAIKefuConfig?.enable || true
			}
		},
		methods: {
			// 拨打电话
			call() {
				uni.makePhoneCall({ phoneNumber: this.tel + '' })
			},

			// 打开客服选择弹窗
			openKefuSelectPopup() {
				const kefuNames = this.kefuList.map(item => item.name);
				wx.showActionSheet({
					itemList: kefuNames,
					success: (res) => {
						this.selectedKefu = this.kefuList[res.tapIndex];
						this.reinitCustomerService(this.selectedKefu);
						this.handleSelectedKefu();
					}
				});
			},

			// 重新初始化客服实例
			reinitCustomerService(kefu) {
				this.customerService = createCustomerService(this, kefu);
				this.buttonConfig = this.customerService.getButtonConfig();
			},

			// 执行选中的客服逻辑
			handleSelectedKefu() {
				const kefu = this.selectedKefu;
				if (!kefu) return;

				if (kefu.isOfficial) {
					wx.openCustomerServiceConversation({ sessionFrom: 'weapp', showMessageCard: true });
				} else if (kefu.id === 'custom-kefu') {
					this.customerService.handleCustomerClick();
				} else if (kefu.id === 'qyweixin-kefu') {
					this.customerService.handleQyWeixinKefuClick();
				}
			},

			// 打开AI聊天（修复setAiUnreadCount的核心）
			openAIChat() {
				if (this.enableAIChat) {
					// 直接用$store.commit调用Vuex mutation，绕过映射问题
					this.$store.commit('setAiUnreadCount', 0);
				}
				this.$util.redirectTo('/pages_tool/ai-chat/index')
			}
		}
	};
</script>

<style lang="scss">
	.fixed-box {
		position: fixed;
		right: 0rpx;
		bottom: 200rpx;
		z-index: 10;
		border-radius: 120rpx;
		padding: 20rpx 0;
		display: flex;
		justify-content: center;
		flex-direction: column;
		width: 100rpx;
		box-sizing: border-box;
		overflow: hidden;

		.btn-item {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 14rpx 0;
			background: #fff;
			border-radius: 50rpx;
			width: 80rpx;
			height: 80rpx;
			padding: 0;
			position: relative;

			text {
				font-size: 36rpx;
				font-weight: bold;
			}

			.unread-badge {
				position: absolute;
				top: -5rpx;
				right: -5rpx;
				background-color: #ff4544;
				color: white;
				border-radius: 20rpx;
				min-width: 30rpx;
				height: 30rpx;
				font-size: 20rpx;
				line-height: 30rpx;
				text-align: center;
				padding: 0 8rpx;
				box-shadow: 0 2rpx 10rpx rgba(255, 69, 68, 0.3);
			}

			.ai-icon {
				font-size: 40rpx;
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>