<template>
	<view class="container">

		<!-- Tab切换 - 平均分配宽度 -->
		<view class="custom-tabs">
			<view class="tab-item" :class="{ active: currentTab === 0 }" @click="switchTab(0)">
				<text class="tab-text">京东月结码</text>
			</view>
			<view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">
				<text class="tab-text">顺丰月结码</text>
			</view>
		</view>

		<!-- 二维码邀请内容 -->
		<view  class="tab-content">
			<scroll-view scroll-y class="scroll-view">
				<!-- 店铺信息 -->
				<view class="store-info">
					<view class="store-name">月结卡号</view>
					<view class="store">
						<!-- <text class="store-name">{{shopInfo.shopName}}</text> -->
						<text class="store-address">12345444</text>
						<!-- <u-icon name="arrow-right"></u-icon> -->
					</view>
				</view>
			
				<!-- 二维码区域 -->
				<view class="qrcode-container">
			
					<view class="store-manager-content">
						<text class="store-manager title">请小哥扫此二维码</text>
					</view>
			
					<view class="store-manager-content">
						<text class="store-manager">警告：系统将记录所有操作，请勿违规使用</text>
					</view>
					<!-- 空出二维码位置 -->
					<view class="qrcode-placeholder">
						<!-- 这里在实际应用中会显示二维码图片 -->
						<!-- 使用说明 inviteType 1 是添加员工  0是邀请会员 -->
						<image :src="qrCodeUrl"></image>
			
					</view>
			
					<view class="expiry-info">
						<text class="text">此二维码300秒有效，点击</text>
					</view>
				</view>
			
				<!-- 使用说明 inviteType 1 是添加员工  0是邀请会员 -->
				<!-- <view class="instructions" v-if="inviteType == '1'">
					<text class="instructions-title">使用说明</text>
					<view class="instructions-list">
						<text class="instruction-item">1. 让员工使用微信扫描上方二维码</text>
						<text class="instruction-item">2. 员工确认门店信息并提交申请</text>
					</view>
				</view>
			
				<view class="instructions" v-if="inviteType == '0'">
					<text class="instructions-title">使用说明</text>
					<view class="instructions-list">
						<text class="instructions-content-title">1. 扫码申请加入门店会员</text>
						<text class="instruction-item">会员扫描二维码后，可自主提交申请成为门店会员，审核通过后即可享受会员权益。</text>
						<text class="instructions-content-title">2. 添加用户手机号直接添加门店会员</text>
						<text class="instruction-item">输入用户手机号，直接为其开通门店会员资格</text>
					</view>
				</view> -->
			
			</scroll-view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'

	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app' // 导入 UniApp 的生命周期

	// 当前选中的tab
	const currentTab = ref(0)
	const linkType = ref(0) //0门店  1外聘 2平台

	// 手机号
	const phoneNumber = ref('')
	const qrCodeUrl = ref('')
	const imgData = ref('')
	const searchUser = ref({
		id: undefined
	})

	const tenantId = ref('')
	const shopInfo = ref({})
	const title = ref({})
	const btnName = ref({})
	const inviteType = ref('1') // 1 是添加员工  0是邀请会员


	onLoad((option) => {
		tenantId.value = option.tenantId
		inviteType.value = option.inviteType
		
	})

	onShow(() => {
		// 1 是添加员工  0是邀请会员
		// if (inviteType.value == '0') {
		// 	getShopInfo()
		// 	// getShopShareQrcode()
		// }else{
		// 	getShopInfo()
		// }
	})

	// 切换Tab
	const switchTab = (index) => {
		currentTab.value = index
	}

	// 分享二维码
	const shareQrcode = () => {
		uni.showToast({
			title: '分享功能',
			icon: 'none'
		})
	}


	const handleSearch = () => {
		if (!ValidationUtils.validatePhone(phoneNumber.value)) {
			uni.showToast({
				title: "请填写正确手机号码",
				icon: 'none'
			})
			return
		}
		uni.showLoading({
			title: "正在查找，请稍等"
		})
		if (inviteType.value == '1') {
			getStaffByPhone()
		} else {
			getUserByPhone()
		}
	}

	const handleAdd = () => {
		if (!searchUser.value.id) {
			uni.showToast({
				title: "请查找添加人员信息",
				icon: 'none'
			})
			return
		}
		if (inviteType.value == '1') {
			addEmployee()
		} else {
			addShareShopUser()
		}
	}

	const addShareShopUser = async () => {
		//promoterStatus推广状态(0 封禁 1 正常 )
		try {
			const params = {
				applyUserId: searchUser.value.id,
				tenantId: tenantId.value,
				promoterStatus: 1
			}
			uni.showLoading()
			const res = await addStaffApi(params)
			if (res.code == 200) {
				uni.showToast({
					title: "添加成功",
					icon: "success"
				})
				// 清空输入框
				phoneNumber.value = ''
				searchUser.value.id = undefined
			}
			uni.hideLoading()
		} catch (error) {

		} finally {
			uni.hideLoading()
		}
	}


	// 添加员工
	const addEmployee = async () => {
		try {
			const params = {
				userId: searchUser.value.id,
				tenantId: tenantId.value,
				linkType: linkType.value
			}

			uni.showLoading()
			const res = await addStaffApi(params)
			if (res.code == 200) {
				uni.showToast({
					title: "添加成功",
					icon: "success"
				})
				// 清空输入框
				phoneNumber.value = ''
				searchUser.value.id = undefined
			}
			uni.hideLoading()

		} catch (error) {

		} finally {

			uni.hideLoading()
		}
	}

	const getShopInfo = () => {
		const params = {
			tenantId: tenantId.value,
			linkType: linkType.value
		}
		getShopUserInfoApi(params).then(res => {
			console.log("res======", res)
			if (res.code == 200) {
				shopInfo.value = res.data
				//门店员工直接返回二维码
				// 1 是添加员工  0是邀请会员
				// if (inviteType.value == '1') {
				qrCodeUrl.value = res.data.qrCodeUrl
				// }
			}
		})
	}

	// const getShopShareQrcode = () => {
	// 	//codeType 0:门店推广人 1门店用户
	// 	const params = {
	// 		userId: searchUser.value.id,
	// 		tenantId: shopInfo.value.tenantId,
	// 		codeType: inviteType.value,
	// 		linkType: linkType.value
	// 	}
	// 	getShopShareQrcodeApi(params).then(res => {
	// 		console.log('res====',res)
	// 		if (res.code == 200 && res.data.length > 0) {
	// 			//门店推广单独请求二维码
	// 			// 1 是添加员工  0是邀请会员
	// 			if (inviteType.value == '0') {
	// 				qrCodeUrl.value = res.data[0].qrCodeUrl
	// 			}
	// 		} else {
	// 			uni.showToast({
	// 				title: '暂无查到相关二维码',
	// 				icon: 'none'
	// 			})
	// 		}
	// 	})
	// }

	const getStaffByPhone = () => {
		uni.showLoading({
			title: '正在查找'
		})
		const params = {
			userPhone: phoneNumber.value
		}
		getStaffByPhoneApi(params).then(res => {
			uni.hideLoading()
			if (res.code == 200 && res.data.length > 0) {
				searchUser.value = res.data[0]
			} else {
				uni.showToast({
					title: "暂无此人",
					icon: 'error'
				})
			}
		}, err => {
			uni.hideLoading()
		})
	}

	const getUserByPhone = () => {
		const params = {
			userPhone: phoneNumber.value
		}
		queryUserByPhoneApi(params).then(res => {
			uni.hideLoading()
			if (res.code == 200 && res.data.length > 0) {
				searchUser.value = res.data[0]
			} else {
				uni.showToast({
					title: "暂无此人",
					icon: 'error'
				})
			}
		}, err => {
			uni.hideLoading()
		})
	}


	// 判断是否为网络图片
	const isNetworkImage = (text) => {
		// 检查是否以http或https开头
		const networkPattern = /^(https?:\/\/[^\s]+)/i
		if (networkPattern.test(text)) {
			return true
		}
	}
	// 保存Base64图片到相册
	const saveBase64ToAlbum1 = async () => {
		if (!qrCodeUrl.value) {
			uni.showToast({
				title: '暂无需要保存的图片',
				icon: 'none'
			})
			return
		}

		if (isNetworkImage(qrCodeUrl.value)) {
			saveImageToAlbum()
			return
		}
		console.log('=====my_document====')
		saveBaseImgFile(qrCodeUrl.value)
	}


	// 保存图片到相册
	const saveImageToAlbum = async () => {
		try {
			// 第一步：下载网络图片到本地
			const downloadResult = await downloadImage(qrCodeUrl.value)

			if (!downloadResult.tempFilePath) {
				throw new Error('图片下载失败')
			}

			// 第二步：保存到相册
			await saveImage(downloadResult.tempFilePath)

			uni.showToast({
				title: '图片保存成功',
				icon: 'success',
				duration: 2000
			})

		} catch (error) {
			console.error('保存失败:', error)

			// 处理权限问题
			if (error.errMsg && error.errMsg.includes('auth')) {
				// 权限被拒绝，提示用户手动开启
				uni.showModal({
					title: '需要相册权限',
					content: '保存图片需要访问您的相册权限，请在设置中开启权限后重试',
					confirmText: '去设置',
					success: (res) => {
						if (res.confirm) {
							// 跳转到应用设置页面
							uni.openSetting()
						}
					}
				})
			} else {
				uni.showModal({
					title: '保存失败',
					content: error.errMsg || '保存图片失败，请重试',
					showCancel: false
				})
			}
		} finally {
			// saving.value = false
		}
	}

	// 下载图片到本地临时文件
	const downloadImage = (url) => {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url,
				success: resolve,
				fail: reject
			})
		})
	}

	// 保存图片到相册
	const saveImage = (tempFilePath) => {
		return new Promise((resolve, reject) => {
			uni.saveImageToPhotosAlbum({
				filePath: tempFilePath,
				success: resolve,
				fail: reject
			})
		})
	}

	const saveBaseImgFile = (base64) => {
		const bitmap = new plus.nativeObj.Bitmap('base64')
		bitmap.loadBase64Data(base64, () => {
				const url = '_doc/' + new Date().getTime() + '.png'
				bitmap.save(
					url, {
						overwrite: true // 是否覆盖  
						// quality: 'quality'  // 图片清晰度  
					},
					(i) => {
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: () => {
								uni.showToast({
									title: '图片保存成功',
									duration: 2000
								})
								console.log('图片保存成功')
								bitmap.clear()
							}
						})
					},
					(e) => {
						uni.showToast({
							title: '图片保存失败',
							content: e.errMsg || '保存图片失败，请重试',
							duration: 2000
						})
						console.log('图片保存失败')
						bitmap.clear()
					}
				)
			},
			(e) => {
				console.log('图片保存失败')
				bitmap.clear()
			}
		)
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #F5F7FA;
	}

	.header {
		padding: 44rpx 0 30rpx 0;
		text-align: center;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;

		.header-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}

	// 自定义Tab布局 - 平均分配
	.custom-tabs {
		display: flex;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 30rpx 0;
		position: relative;

		&.active {
			.tab-text {
				color: #2979ff;
				font-weight: bold;
			}

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 4rpx;
				background-color: #2979ff;
				border-radius: 2rpx;
			}
		}

		.tab-text {
			font-size: 32rpx;
			color: #666;
		}
	}

	// 内容区域
	.tab-content {
		padding: 16rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		background-color: #F5F7FA;
		margin-bottom: 140rpx;

		.scroll-view {
			flex: 1;
			margin-bottom: 156rpx;
		}
	}

	// 店铺信息
	.store-info {
		min-height: 124rpx;
		background: #FFFFFF;
		border-radius: 32rpx;
		text-align: center;
		margin-bottom: 20rpx;
		padding: 32rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-sizing: border-box;

		.store-icon {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: rgba(0, 137, 255, 0.1);
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			flex-shrink: 0;

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.store {
			display: flex;

			.store-name {
				height: 44rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
				line-height: 44rpx;
				text-align: left;
			}

			.store-address {
				min-height: 44rpx;
				line-height: 44rpx;
				font-size: 28rpx;
				color: #1B64F0;
				text-align: left;
			}

		}

	}

	// 二维码区域
	.qrcode-container {
		background-color: #fff;
		border-radius: 32rpx;
		padding: 20rpx;
		margin-bottom: 32rpx;
		text-align: center;

		.store-manager-content {
			display: flex;
			justify-content: center;
			text-align: center;

			image {
				width: 48rpx;
				height: 48rpx;
				border-radius: 48rpx;
			}


			.store-manager {
				height: 44rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				line-height: 44rpx;

				&.title {
					height: 48rpx;
					font-weight: bold;
					font-size: 32rpx;
					color: #333333;
					line-height: 48rpx;

				}
			}
		}


		// 二维码占位区域
		.qrcode-placeholder {
			width: 400rpx;
			height: 400rpx;
			margin: 20rpx auto 30rpx;
			border-radius: 16rpx;
			background-color: #f5f5f5;
			display: flex;
			align-items: center;
			justify-content: center;

			/* 这里在实际应用中会显示二维码图片 */
			/* 暂时使用背景色占位 */
			image {
				width: 400rpx;
				height: 400rpx;
				border-radius: 16rpx;
			}
		}

		.expiry-info {
			margin: 20rpx;
			height: 84rpx;
			background: #F5F7FA;
			border-radius: 16rpx;

			font-weight: 400;
			font-size: 28rpx;
			color: #3D3D3D;
			line-height: 84rpx;
			text-align: center;
			.text{
				&::after{
					content: '刷新二维码';
					color: #1B64F0;
				}
			}
		}
	}


	// 使用说明
	.instructions {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 16rpx;
		margin-bottom: 16rpx;

		.instructions-title {
			display: inline-block;
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 16rpx;
			color: #333;
		}

		.instructions-content-title {
			display: inline-block;
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
			margin-top: 8rpx;
		}

		.instructions-list {
			display: flex;
			flex-direction: column;
		}

		.instruction-item {
			font-size: 26rpx;
			color: #666;
			line-height: 1.6;
		}
	}

	// 按钮组
	.button-group {
		width: 100%;
		height: 132rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		position: fixed;
		bottom: 0;
		padding: 0rpx 32rpx;
		background-color: #fff;

		.button {
			height: 88rpx;
			line-height: 88rpx;
			flex: 1;
			text-align: center;
			border-radius: 16rpx;
			font-size: 30rpx;
			font-weight: bold;

			&.share-button {
				color: #1B64F0;
				margin-right: 32rpx;
				background: rgba(0, 137, 255, 0.1);
			}

			&.save-button {
				background-color: #1B64F0;
				color: #fff;
			}

			.button-text {
				font-size: 30rpx;
			}
		}


	}

	// 手机号邀请表单
	.phone-form {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 16rpx;

		.phone-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 16rpx;
			display: block;
		}

		.phone-input-group {
			height: 88rpx;
			display: flex;
			border-radius: 16rpx;
			overflow: hidden;
			background-color: #F5F7FA;

			.country-code {
				width: 140rpx;
				padding: 24rpx;
				text-align: center;
				font-size: 28rpx;
				color: #333;
				display: flex;
				align-items: center;
				justify-content: center;
				border-right: 2rpx solid #e0e0e0;
			}

			.phone-input {
				height: 88rpx;
				line-height: 88rpx;
				flex: 1;
				padding: 24rpx;
				font-size: 28rpx;
			}
		}

	}


	.employee-item-main {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		background-color: #fff;
		border-radius: 32rpx;
		padding: 20rpx;

		.photo {
			background-color: #F5F7FA;
			width: 88rpx;
			height: 88rpx;
			border-radius: 80rpx;
		}

		.employee-main-info {
			height: 84rpx;
			margin-left: 20rpx;
			align-self: center;
			display: flex;
			flex-direction: column;
			justify-content: center;
			margin-bottom: 20rpx;
			flex: 1;

			.employee-name {
				height: 44rpx;
				line-height: 44rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #333333;
			}

			.employee-phone {
				height: 40rpx;
				line-height: 40rpx;
				font-size: 24rpx;
				color: #666666;
			}

		}

		.employee-actions {
			display: flex;
			align-items: center;
			height: 116rpx;
			background-color: #fff;
			border-radius: 32rpx;
			margin-top: 16rpx;


			.status-badge {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				margin-right: 16rpx;

				.enabled {
					// background-color: #e6f7ff;
					margin-left: 16rpx;
					color: #1B64F0;
				}

				.disabled {
					// background-color: #f5f5f5;
					margin-left: 16rpx;
					color: #333333;
				}
			}

			.btn-view-order {
				height: 40rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #1B64F0;
				line-height: 40rpx;
				text-align: left;
				margin-right: 16rpx;
			}

			.dismiss-btn {
				width: 88rpx;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				background: #F52929;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #FFFFFF;
			}
		}

	}


	.submit-button {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #1B64F0;
		color: #fff;
		text-align: center;
		border-radius: 16rpx;

		.submit-text {
			font-size: 32rpx;
			font-weight: bold;
		}
	}
</style>