<template>
	<div class="g-rh-rh-serverpopup">
		<u-popup v-model="showModal" mode="center" :mask-close-able="true" :closeable="true" @close="showModal = false" border-radius="30">
			<view style="padding: 0 64px 32px">
				<view style="text-align: center; font-size: 16px; color: #333; font-weight: 500; margin-bottom: 32px; padding-top: 32px">添加微信</view>
				<view>
					<image 
						:src="serviceInfo.qrCode || 'https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/1shoudanWeb/nopicture.png'" 
						alt="" 
						style="width: 184px; height: 184px"
						@longpress="handleLongPress"
						@show="onImageLoad"
						ref="qrImage"
					/>
				</view>
				<view class="g_c_sub g_flex_row_center flex_center g_fs_14 g_mt_24" @click="kefuPhone"> 
					<i class="iconfont icon-phone g_mr_4"> </i>电话联系 
				</view>
			</view>
		</u-popup>
	</div>
</template>

<script>
// 检查是否在APP环境
const isAppEnvironment = () => {
	// #ifdef APP-PLUS
	return true;
	// #endif
	return false;
};

// 检查API是否可用
const isApiAvailable = (apiName) => {
	try {
		return typeof uni[apiName] === 'function';
	} catch (e) {
		return false;
	}
};

export default {
	props: {
		show: {
			default: false,
		},
	},
	data() {
		return {
			serviceInfo: {},
			showModal: false,
			imagePath: '' // 存储图片路径
		};
	},
	watch: {
		show(val) {
			console.log("showshowshow", val);
			this.showModal = val;
		},
		showModal(val) {
			console.log("valvalvalvalvalval", val);
			this.$emit("updateShow", val);
		},
	},
	created() {
		let serviceInfo = uni.getStorageSync("bc-server");
		if (serviceInfo.qrCode && !serviceInfo.qrCode.includes("https")) {
			serviceInfo.qrCode = serviceInfo.qrCode.replace("http", "https");
		}
		let tel = serviceInfo.workPhone.trim();
		let num1 = tel.slice(0, 3);
		let num2 = tel.slice(3, 7);
		let num3 = tel.slice(7, 11);
		serviceInfo.tel = num1 + "-" + num2 + "-" + num3;
		this.serviceInfo = serviceInfo;
	},

	methods: {
		// 图片加载完成事件
		onImageLoad() {
			// 获取图片信息
			if (!isAppEnvironment()) return;
			
			if (!isApiAvailable('getImageInfo')) {
				console.warn('getImageInfo API not available');
				return;
			}
			
			uni.getImageInfo({
				src: this.serviceInfo.qrCode,
				success: (res) => {
					this.imagePath = res.path;
				},
				fail: (err) => {
					console.error('getImageInfo failed:', err);
				}
			});
		},
		
		// 处理长按事件
		handleLongPress() {
			console.log("长按事件触发");
			// 在APP环境下显示操作菜单
			if (!isAppEnvironment()) return;
			this.showActionSheet();
		},
		
		// 显示操作菜单
		showActionSheet() {
			if (!isAppEnvironment()) return;
			
			if (!isApiAvailable('showActionSheet')) {
				console.warn('showActionSheet API not available');
				return;
			}
			
			uni.showActionSheet({
				title: '请选择操作',
				itemList: ['保存图片'],
				success: (res) => {
					if (res.tapIndex === 0) {
						// 保存图片到相册
						this.saveImageToPhotosAlbum();
					}
				},
				fail: (err) => {
					console.log('用户取消操作');
				}
			});
		},
		
		// 保存图片到相册
		saveImageToPhotosAlbum() {
			if (!isAppEnvironment()) return;
			
			// 检查必要API是否可用
			if (!isApiAvailable('saveImageToPhotosAlbum')) {
				uni.showToast({
					title: '当前环境不支持保存图片',
					icon: 'none'
				});
				return;
			}
			
			// 直接尝试保存图片，无需权限检查（让系统自动处理权限）
			this.doSaveImage();
		},
		
		// 实际保存图片的方法
		doSaveImage() {
			if (!isAppEnvironment()) return;
			
			// 检查必要的API是否存在
			if (!isApiAvailable('downloadFile') || !isApiAvailable('saveImageToPhotosAlbum')) {
				uni.showToast({
					title: '当前环境不支持保存图片',
					icon: 'none'
				});
				return;
			}
			
			uni.showLoading({
				title: '保存中...'
			});
			
			// 如果还没有图片路径，则先下载图片
			if (!this.imagePath) {
				uni.downloadFile({
					url: this.serviceInfo.qrCode,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.hideLoading();
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: (err) => {
									uni.hideLoading();
									console.error('保存失败:', err);
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									});
								}
							});
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('下载失败:', err);
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				});
			} else {
				// 直接保存已有路径的图片
				uni.saveImageToPhotosAlbum({
					filePath: this.imagePath,
					success: () => {
						uni.hideLoading();
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('保存失败:', err);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			}
		},
		
		kefuPhone() {
			let tel = this.serviceInfo.workPhone.trim();
			if(tel){
				tel = tel.replace(/-/g, "");
			}
			uni.makePhoneCall({
				phoneNumber: tel,
			});
		},
	},
};
</script>

<style></style>