<template>
	<view style="position: relative;">
		<!-- 胶囊 -->
		<mvBar :mysNavConfig="mysNavConfig"></mvBar>
		<view :style="{marginTop:navH}"></view>
		<view class="home">
			<view class="card" v-if="!loading">
				<view class="head">
					<image
						src="https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/lQLPDhrXwll1_NcjI7AD0T3viYtxQwGOvh1SwG0A_35_35.png"
						mode="aspectFill">
					</image>
					<span>快手账号绑定</span>
				</view>

				<view class="body">

					<view>
						<!-- 绑定成功展示信息  v-if -->
						<view>
							<!-- 左侧图片和文字 -->
							<view class="task-info-left" style="display: flex;">
								<!-- 图片 -->
								<image class="head-img" :src="head_uri"></image>
								<view class="task-info-txt">
									<p style="margin-bottom: 15rpx;">{{nick_name}}</p>
									<p style="color: #81838f;">剩余100天</p>

								</view>
							</view>
							<view class="sale_txt">
								<p>粉丝数:<span>{{fansCount}}</span></p>
								<p>近30日橱窗销量:<span style="padding-left: 30rpx;">{{saleNum_30}}</span></p>
							</view>
						</view>


						<!-- 分割线 -->
						<view class="heng-line"></view>

						<!-- 点击弹窗 toggle(触发)-->
						<button class="btn1" @click="getqrcode('center')">
							{{ isBindKuaishou ? '刷新授权' : '添加快手账号' }}
						</button>
					</view>
				</view>
			</view>
		</view>
		<!-- 普通弹窗  公众号-->
		<uni-popup ref="popup4" class="share" background-color="#fff" @change="change" :maskClick="true">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<view class="sharepage">
					<view class="projecttext1">
						<span>快手账号登录</span>
					</view>
					<view class="sharetxt">
						<text style="color:#9a9a9a ;">
							截屏或下载二维码，使用快手APP\n
							打开[首页-搜索-扫一扫]后扫码进行
						</text>
					</view>
					<!-- 授权码展示 -->
					<view class="sharemap">
						<!-- 根据 countdownTime 的值为 image 元素应用不同的类名 -->
						<image :class="{'expired-image': countdownTime <= 0, 'active-image': countdownTime > 0}"
							:src="qrcodeURL" mode=""></image>

						<!-- 条件渲染：当 countdownTime 小于等于 0 时显示蒙版 -->
						<image v-if="countdownTime <= 0"
							src="https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/qrOOD.png"
							style="width: 150rpx;height: 150rpx;position: absolute;top: 240rpx;left: 200rpx;"></image>

					</view>

					<view style="margin: 30rpx 0;">
						<button class="butmin1" size="mini" @tap="freshqrcode" :disabled="countdownTime > 0">
							{{ countdownTime > 0 ? `刷新二维码(${countdownTime}秒后到期)` : '刷新二维码 (已过期)' }}
						</button>
					</view>
					<view class="importentInfo1">
						<view class="sharetxt1" style="font-size: 22rpx;">
							<text style="white-space: pre-line; text-align: left;line-height: 1;">
								登录成功后： \n
								·同步账号基础信息及查看账号运营数据\n
								·获得免费领样权限\n
								·获得承接快手悬赏任务权限\n
								·为达人橱窗快速选品\n
								·为直播带货快速选品\n
								·样叽专属高佣商品，同一商品，更高佣金\n
								·变现种草任务参与资质\n
							</text>
						</view>
					</view>

					<view style="margin: 30rpx 0;">
						<button class="butmin" size="mini" @tap="saveImage">下载二维码至手机</button>
					</view>
				</view>

			</view>
		</uni-popup>
	</view>
</template>

<script>
	import mvBar from "@/components/mys_navBar/mysNavBar";
	import htzImageUpload from '@/components/htz-image-upload/htz-image-upload.vue';
	import getPolicyEncode from '@/components/obs/getPolicy.js';
	import getSignature from '@/components/obs/GetSignature.js';
	export default {
		components: {
			mvBar,
			htzImageUpload,
		},
		data() {
			return {
				countdownTime: 100, // 初始倒计时时间（秒）
				intervalId: null, // 计时器 ID
				qrcodeURL: 'https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/lQLPDhrXwll1_NcjI7AD0T3viYtxQwGOvh1SwG0A_35_35.png', // 用来保存二维码URL的变量
				// qrcodeURL: '',
				head_uri: 'https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/lQLPDhrXwll1_NcjI7AD0T3viYtxQwGOvh1SwG0A_35_35.png',
				nick_name: "",
				navH: getApp().globalData.navHeight,
				hasClicked: false,
				loading: true,
				accountId: '',
				platform: {
					platform_id: '',
					platform_name: '',
					platform_icon: '',
				},
				isBind: true,
				isBindKuaishou: true,
				imageData: [],
				formData: {
					platform_nickname: '',
					fans_count: '',
					home_page_url: '',
					home_page_capture_url: ''
				},
				// 二维码地址
				imageUrl: '',
				index: 0,
				fansLabel: "选择单位",
				fansCount: null,
				saleNum_30: 0,
				fansCountInfo: 1,
				fansRange: [{
						value: 1,
						label: '个'
					},
					{
						value: 10000,
						label: '万'
					},
					{
						value: 100000000,
						label: '亿'
					}
				],

				mysNavConfig: {
					/* 开启单页显示首页图标 */
					isHome: true,
					/* 固定导航  */
					navFixed: true,
					/* 标题 （屏幕中心居中 两边图标中心居中使用slot center1） */
					navTitle: {
						text: "社媒账号绑定",
						color: "",
						fontSize: "32rpx", // px upx rpx
						fontWeight: "normal", // 100 - 700
					},
					btnType: "type2",
					onLeftClick: '',
					/* type2 按钮 */
					type2Config: {
						// 左图标
						leftPath: "/static/img/png2.png",
						// 右图标
						rightPath: "/static/img/png4.png",
						// 圆角
						radius: "40rpx",
					},
				}, // 密码登录校验规则
				bindRules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入昵称'
						}]
					},
					home_img: {
						rules: [{
							required: true,
							errorMessage: '请上传主页截图',
						}]
					}
				},
				urlRegList: [
					/(.*)http(s?)\:\/\/((www\.)?)(xiaohongshu\.com)(.*)/,
					/(.*)http(s?)\:\/\/((www\.)?)((v\.)?)(douyin\.com)(.*)/,
					/(.*)http(s?)\:\/\/((www\.)?)((m\.)?)(weibo\.(com|cn))(.*)/,
					/(.*)http(s?)\:\/\/((www\.)?)((v|kpfshanghai)\.m\.chenzhongtech\.com)(.*)/,
					/(.*)http(s?)\:\/\/((www\.)?)(b23\.tv)(.*)/,
					/(.*)http(s?)\:\/\/((www\.)?)((m\.)?)(dianping\.(com|cn))(.*)/,
					/(.*)http(s?)\:\/\/((www\.)?)(zhihu\.com)(.*)/,
				]
			}
		},
		onReady() {},
		async onShow() {},
		async onLoad(options) {
			await this.checkaccount()
			this.platform.platform_id = parseInt(options.platform_id)
			if (options.account_id) {
				this.accountId = parseInt(options.account_id)
				this.isBind = false
			}
			this.loading = true;
			uni.showLoading({
				title: '加载中'
			});
			await this.getinfo();
			if (!this.isBind) {
				await this.getaccount()
			};
			this.loading = false;
			uni.hideLoading();
		},
		methods: {
			checkaccount() {
				this.$https.get('/youngee/c/t/g/check-account').then(res => {
					// todo:得到用户数据并赋值 ，头像、粉丝，
					console.log("Backend response res:", res);

					// 如果后端响应了您想要的结果，则关闭 uni-popup，并停止向后端发送请求
					//如果/kuangshouauth执行完毕（存在含tid的数据）
					if (res.data.code != -1) {
						this.nick_name = res.data.data.nick_name
						this.head_uri = res.data.data.head_uri
						this.fansCount = res.data.data.fan
						//继续往数据中填充30天销量字段
						this.$https.get('/youngee/c/t/g/query-sales-for30-days').then(res => {
							console.log("30days+++++++", res)
							this.saleNum_30 = res.data.data
						})
						this.isBindKuaishou = true
						//从数据库中取到accesstoken和


					} else {
						//没查到数据，没有绑定
						this.isBindKuaishou = false
					}
				}).catch(err => {
					console.error("Error:", err);
				});
			},
			// 获得二维码
			async getqrcode(type) {
				this.type4 = type;
				this.$refs.popup4.open(type);
				this.loading = true;
				uni.showLoading({
					title: '加载中',
				})

				// 从后端中请求二维码图片展示出来
				//达人id在后端通过session获取
				await this.$https.get('/youngee/c/t/g/display-qrcode').then(res => {
					this.qrcodeURL = res.data.data;
				})
				this.startCountdown();
				this.loading = false;
				uni.hideLoading();

			},
			// 倒计时结束才能点击
			async freshqrcode() {
				this.qrcodeURL =
					'https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/lQLPDhrXwll1_NcjI7AD0T3viYtxQwGOvh1SwG0A_35_35.png'
				if (this.intervalId != null) {
					clearInterval(this.intervalId);
					this.countdownTime = 100;
				}
				//重新设置倒计时时间
				this.countdownTime = 100; // 重置为 10 秒
				this.loading = true;
				uni.showLoading({
					title: '加载中',
				})
				await this.$https.get('/youngee/c/t/g/display-qrcode').then(res => {
					this.qrcodeURL = res.data.data;
					console.log("refresh--url:", this.qrcodeURL);
				})
				// 启动倒计时计时器
				this.startCountdown();
				this.loading = false;
				uni.hideLoading();
			},
			startCountdown() {
				// 每秒减少剩余时间
				this.intervalId = setInterval(() => {
					if (this.countdownTime > 0) {
						this.countdownTime--;
						this.$https.get('/youngee/c/t/g/check-account').then(res => {
							// todo:得到用户数据并赋值
							console.log("Backend response res:", res);
							// 如果后端响应了您想要的结果，则关闭 uni-popup，并停止向后端发送请求
							if (res.data.code != -1 && this.intervalId != null) {
								clearInterval(this.intervalId);
								this.countdownTime = 100;
								this.closepop() // 关闭 uni-popup
							}
						}).catch(err => {
							console.error("Error:", err);
						});
					}
				}, 1000); // 每秒执行一次
			},
			// startCountdown() {
			// 	// 每秒减少剩余时间
			// 	this.intervalId = setInterval(() => {
			// 		if (this.countdownTime > 0) {
			// 			this.countdownTime--;
			// 		}
			// 	}, 1000); // 每秒执行一次
			// },

			//unipop出现/消失自动触发
			async change(e) {
				if (this.loading) {
					this.loading = false;
					uni.hideLoading();
				}
				if (this.intervalId != null) {
					clearInterval(this.intervalId);
					this.countdownTime = 100;
				}
				await this.checkaccount()
				this.qrcodeURL =
					'https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/lQLPDhrXwll1_NcjI7AD0T3viYtxQwGOvh1SwG0A_35_35.png'
			},
			// 保存图片
			async saveImage() {
				// showToast('保存成功')
				wx.downloadFile({
					url: 'https://horastar.obs.cn-east-3.myhuaweicloud.com/talent/lQLPDhrXwll1_NcjI7AD0T3viYtxQwGOvh1SwG0A_35_35u',
					success: function(res) {
						wx.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(data) {
								wx.showToast({
									title: "保存成功",
									icon: "success",
									duration: 2000
								})
							},
							fail: function(err) {
								console.log(err);
							},
							complete(res) {
								console.log(res);
							}
						})
					}
				})
			},
			closepop() {
				this.$refs.popup4.close()
			},

			// 默认信息表，获取平台logo
			getinfo() {
				return this.$https.get('/youngee/c/g/get-info-tables')
					.then(res => {
						let list = res.data.data.ThirdPlatform
						for (var i = 0; i < list.length; ++i) {
							if (list[i].id == this.platform.platform_id) {
								this.platform.platform_icon = list[i].platform_icon
								this.platform.platform_name = list[i].platform_name
							}
						}
					})
			},
			getaccount() {
				return this.$https.get('/youngee/c/t/g/get-talent-account')
					.then(res => {
						console.log(res)
						if (res.data.code !== -3) {
							this.account = res.data.data
							this.imageData = []
							for (var i = 0; i < this.account.length; i++) {
								if (this.platform.platform_id == this.account[i].platform_id) {
									this.hasClicked = true
									this.formData.platform_nickname = this.account[i].platform_nickname
									this.formData.fans_count = this.account[i].fans_count
									this.formData.home_page_url = this.account[i].home_page_url
									this.imageData.push(this.account[i].home_page_capture_url);

									if (this.formData.fans_count >= 100000000) {
										this.index = 2
										this.fansCountInfo = this.fansRange[this.index].value;
										this.fansLabel = this.fansRange[this.index].label;
										this.fansCount = (this.formData.fans_count / 100000000).toFixed(1)
									} else if (this.formData.fans_count >= 10000) {
										this.index = 1
										this.fansCountInfo = this.fansRange[this.index].value;
										this.fansLabel = this.fansRange[this.index].label;
										this.fansCount = (this.formData.fans_count / 10000).toFixed(1)
									} else {
										this.index = 0
										this.fansCountInfo = this.fansRange[this.index].value;
										this.fansLabel = this.fansRange[this.index].label;
										this.fansCount = this.formData.fans_count
									}
								}
							}
						}
					})
			},

			exit() {
				uni.navigateBack()
			},
			// 粉丝量量级选择
			bindPickerChange: function(e) {
				if (this.index !== e.detail.value) {
					this.fansCount = null
				}
				this.index = e.detail.value;
				this.fansLabel = this.fansRange[this.index].label
				this.fansCountInfo = this.fansRange[this.index].value
			},
			ceshiChooseSuccess(tempFilePaths, e) { //选择图片返回
				console.log('ceshiChooseSuccess', tempFilePaths, e);
				if (e == 0) {
					this.store = 'talent_upload/' + this.guid() + '.png'
					// this.store = 'talent_upload/icon-whole-pipline.png'
					// this.store = 'youngee/talent_upload/icon-edit.2png'
				} else if (e == 1) {
					this.store = 'talent_upload/' + this.guid() + '.mp4'
				}
				/****************
				以下代码是自定义上传逻辑，仅供参考
				***************/
				this.imgUpload(tempFilePaths);
				/*******************************/
			},
			imgUpload(tempFilePaths) {
				let that = this
				let config = {
					AccessKeyId: 'IVW21DTGIIUBBAGXKK0Y', //AK
					SecretKey: 'Y01nEQNcLOATMw7uJwrk3yOdQZ2fqLhSnXcOKVDE', //SK
					EndPoint: 'https://horastar.obs.cn-east-3.myhuaweicloud.com', //上传文件的路径
				};
				let fileName = this.store; //指定上传到OBS桶中的对象名
				let OBSPolicy = { //设定policy内容
					"expiration": "2089-12-31T12:00:00.000Z",
					"conditions": [{
							"bucket": "horastar"
						}, //Bucket name
						// {"bucket": "goin"}, 
						{
							'key': fileName
						}
					]
				}

				let policyEncoded = getPolicyEncode(OBSPolicy); //计算policy编码值
				let signature = getSignature(policyEncoded, config.SecretKey); //计算signature 
				uni.uploadFile({
					//url: config.EndPoint,
					url: config.EndPoint,
					filePath: tempFilePaths[0],
					name: 'file',

					formData: {
						'AccessKeyID': config.AccessKeyId,
						'policy': policyEncoded,
						'signature': signature,
						'key': fileName,
					},

					success: function(res) {
						console.log("res", res); //打印响应状态码
						if (res.statusCode == 204) {
							// that.imageData.push(config.EndPoint + '/' + fileName);
							let obs_url = config.EndPoint + '/' + fileName; //用你自己的 bucket 名替换星号							
							that.imageData.push(obs_url)
							that.formData.home_page_capture_url = obs_url
							uni.showToast({
								title: '上传成功',
								icon: '成功'
							});
						} else {
							uni.showToast({
								title: '上传失败',
								icon: '失败'
							});
						}
					},
					fail: function(e) {
						console.log(e);
						uni.showToast({
							title: '上传失败',
							icon: '失败'
						});
					}
				})
			},
			guid() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);

					return v.toString(16);
				});
			},
			onInput(e) {
				console.log(e)
				e = (e.match(/^\d*(\.?\d{0,1})/g)[0]) || null
				// //重新赋值给input
				if (e < 0 || e > 9999.9) {
					uni.showToast({
						title: '请输入[1,9999.9]区间内的数',
						icon: 'none'
					})
					console.log('请输入[1,9999.9]区间内的数')
				}
				this.$nextTick(() => {
					this.fansCount = (e > 0 && e <= 9999.9) ? e : null
				})
			},
			onInput1(e) {
				// 验证是否是纯数字
				const isNumber = /^\d*$/.test(e)
				// 过滤非数字
				e = e.replace(/\D/g, '')
				if (!isNumber || e < 0 || e > 9999) {
					uni.showToast({
						title: '请输入[0,9999]区间的整数',
						icon: 'none'
					})
					console.log('请输入[0,9999]区间的整数')
				}
				this.$nextTick(() => {
					this.fansCount = (e >= 0 && e <= 9999 && e.match(/^\d*/g)[0]) ? e : null
				})
			}
		},
	}
</script>

<style>
	/deep/ .share .uni-popup .uni-popup__wrapper {
		width: 70% !important;
		border-radius: 15rpx !important;
	}
</style>
<style lang="scss" scoped>
	.importentInfo1 {
		margin-left: 59rpx;
		background-color: #efefef;
		border-radius: 8px;
		height: 370rpx;
		width: 400rpx;
	}


	// 主体样式
	.card {
		padding: 24rpx;
		margin-top: 30rpx;
		border: 1rpx solid #F0D232;
		background-color: #ffffff;
		margin: 0 10rpx;
	}

	.head {
		padding-top: 5%;
		padding: 0 0 0 1%;
		height: 80rpx;
		margin-top: 2%;
	}

	.head span {
		color: #333333;
		font-size: 80%;
		font-weight: 550;
		text-indent: 2em;

	}

	.head image {
		vertical-align: middle;
		width: 50rpx;
		height: 50rpx;
		display: inline-block;
		padding-right: 14rpx;
	}

	.task-info-txt {
		margin-top: 10rpx;
		margin-left: 20rpx;
	}

	.head-img {
		width: 120rpx;
		height: 120rpx;
		border-radius: 100rpx;
	}

	.sale_txt {
		margin-top: 30rpx;
	}

	.sale_txt p {
		margin-bottom: 17rpx;
		color: #81838f;
	}

	.sale_txt span {
		padding-left: 160rpx;
	}


	.home-link {
		/deep/.uni-easyinput__content-input {
			background-color: #EBEBEB;
			border-radius: 15rpx;
		}
	}


	.heng-line {
		margin-top: 60rpx;
		margin-bottom: 50rpx;
		border-bottom: 1rpx solid #DCDCDC;
	}

	.signupbtn p {
		font-size: 30rpx;
	}

	.exit-btn {
		width: 200rpx;
		text-align: center;
		padding: 10rpx 30rpx;
		background-color: #C0C0C0;
		border: 0;
		border-radius: 10rpx;
		color: #FFFFFF;
		font-size: 30rpx;
		line-height: 180%;
	}

	.btn1 {
		margin: 30rpx;
		font-size: 35rpx;
		color: #000;
		background-color: #F0D232;
		border: none;
		border-radius: 0;
	}


	//弹窗
	.share {
		text-align: center;
		line-height: 10rpx;
		margin-top: 10rpx;
	}

	.sharepage {
		// width: 90%;
		margin: 0 auto;
		// position: relative;
	}

	/deep/ .share.uni-popup .uni-popup__wrapper {
		width: 70%;

		border-radius: 15rpx;
	}

	.projecttext1 {
		// padding-top: 5%;
		padding: 0 0 0 1%;
		margin: 5% 0;
		text-align: center;
	}

	.projecttext1 image {
		vertical-align: middle;
		width: 80rpx;
		height: 80rpx;
		display: inline-block;
		padding-right: 14rpx;
	}

	.sharemap {
		margin: 0 auto;
		text-align: center;
		// margin-top: 15%;
		// margin-bottom: 15%;
	}

	.expired-image {
		width: 300rpx;
		height: 300rpx;
		background-color: #000;
		opacity: 0.2;
		/* 例如，设置透明度为 0.5 */
	}

	/* 定义活跃图片的样式 */
	.active-image {
		width: 300rpx;
		height: 300rpx;
		/* 如果有特定样式，可以在这里定义 */
	}


	.sharemap image {
		width: 300rpx;
		height: 300rpx;

	}

	.sharetxt {
		height: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.sharetxt1 {
		padding: 10rpx;
		height: 345rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.sharetxt text {
		font-size: 24rpx;
		text-align: left;
		line-height: 20rpx
	}

	.butmin {
		// height: 48rpx;
		width: 380rpx;
		height: 65rpx;
		background-color: #FCCF41;
		line-height: 60rpx;
		font-weight: bold;
	}

	.butmin1 {
		// height: 48rpx;
		width: 400rpx;
		background-color: #ffffff;
		border: #000000 10rpx;
		line-height: 48rpx;
		color: #FCCF41;
		font-weight: bold;
		font-size: 20rpx;
	}
</style>