<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="platform.platform_icon" mode=""></image>
					<span>{{platform.platform_name}}账号绑定</span>
				</view>

				<view class="body">
					<view>
						<uni-forms :modelValue="formData" ref="form" :rules="bindRules" validate-trigger="bind"
							err-show-type="undertext">
							<uni-forms-item name="name" required label="昵称">
								<uni-easyinput type="text" v-model="formData.platform_nickname" style="width:300rpx"
									placeholder="请填写账号昵称">
								</uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="numberfans" required label="粉丝数">
								<view class="number-inupt">
									<uni-easyinput type="number" v-model="fansCount" placeholder="可保留小数点后一位"
										v-if="fansCountInfo === 1" style="width:300rpx" @input="onInput1">
									</uni-easyinput>
									<uni-easyinput type="digit" v-model="fansCount" placeholder="可保留小数点后一位" v-else
										style="width:300rpx" @input="onInput">
									</uni-easyinput>
									<picker @change="bindPickerChange" :value="index" :range="fansRange"
										style="z-index: 999;background-color: #fcdf41;padding: 0 10rpx;border-radius: 5rpx;"
										range-key="label">
										<view>{{ fansLabel }}</view>
									</picker>
								</view>
								<!-- <view style="font-size: 24rpx;padding-left: 10px;" @click="hasClicked = true" v-else>
									<p>点选数字单位</p>
								</view> -->
							</uni-forms-item>
							<uni-forms-item name="home_link" required label=" " label-width='10'>
								<uni-easyinput class="home-link" type="text" v-model="formData.home_page_url"
									style="width:650rpx" placeholder="请填写个人主页链接">
								</uni-easyinput>
							</uni-forms-item>
							<view style="margin-top: 40rpx;">
								<uni-forms-item name="home_img" required label="主页截图">
									<htz-image-upload :max="1" mediaType="image" name="file" :chooseNum="1"
										v-model="imageData" @chooseSuccess="ceshiChooseSuccess">
									</htz-image-upload>
								</uni-forms-item>
							</view>
						</uni-forms>
						<view class="heng-line"></view>
						<button class="btn1" @click="submitForm('form')">
							确认绑定</button>
					</view>
				</view>
			</view>
		</view>
	</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 {
				navH: getApp().globalData.navHeight,
				hasClicked: false,
				loading: true,
				accountId: '',
				platform: {
					platform_id: '',
					platform_name: '',
					platform_icon: '',
				},
				isBind: true,
				imageData: [],
				formData: {
					platform_nickname: '',
					fans_count: '',
					home_page_url: '',
					home_page_capture_url: ''
				},

				index: 0,
				fansLabel: "选择单位",
				fansCount: null,
				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) {
			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: {
			// 默认信息表，获取平台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
									}
								}
							}
						}
					})
			},
			/**
			 * 手动提交
			 * @param {Object} form
			 */
			submitForm(form) {
				const urlReg = this.urlRegList[this.platform.platform_id - 1]
				if (!urlReg.test(this.formData.home_page_url)) {
					uni.showToast({
						title: '主页链接格式不正确',
						icon: 'none'
					})
					return
				}
				if (this.fansCount == null || this.fansCount * this.fansCountInfo <= 0 || this.fansLabel == "选择单位") {
					uni.showToast({
						title: '请填写粉丝量数量',
						icon: 'none'
					})
					return
				}
				this.formData.fans_count = this.fansCount * this.fansCountInfo
				if (this.imageData.length === 0) {
					uni.showToast({
						title: '请上传主页截图',
						icon: 'none'
					})
					return
				}
				let that = this
				that.$refs.form.validate()
					// that.$refs[form]
					// 	.submit()
					.then(res => {
						console.log('表单的值：', res)

						uni.showModal({
							title: '提示',
							content: '请保证账号信息的准确性和真实性',
							success: function(res) {
								if (res.confirm) {
									that.formData.home_page_capture_url = that.imageData[0]
									if (that.isBind) {
										that.$https.post('/youngee/c/t/p/add-talent-account', {
												platform_id: that.platform.platform_id,
												platform_nickname: that.formData.platform_nickname,
												home_page_url: that.formData.home_page_url,
												fans_count: that.formData.fans_count,
												home_page_capture_url: that.formData
													.home_page_capture_url,
											})
											.then(res => {
												console.log(res)
												if (res.data.code == 0) {
													uni.navigateBack()
												} else {
													let msg = res.data.msg
													uni.showToast({
														title: msg,
														icon: 'none',
														duration: 2000
													});
												}
											})
									} else {
										that.$https.post('/youngee/c/t/p/update-talent-account', {
												account_id: that.accountId,
												platform_id: that.platform.platform_id,
												platform_nickname: that.formData.platform_nickname,
												home_page_url: that.formData.home_page_url,
												fans_count: that.formData.fans_count,
												home_page_capture_url: that.formData
													.home_page_capture_url,
											})
											.then(res => {
												console.log(res)
												if (res.data.code == 0) {
													uni.navigateBack()
												} else {
													let msg = res.data.msg
													uni.showToast({
														title: msg,
														icon: 'none',
														duration: 2000
													});
												}
											})
									}
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							},
						});
					})
					.catch(errors => {
						console.error('验证失败：', errors)
						uni.showToast({
							title: '请填写账号昵称',
							icon: 'none'
						})
					})
			},
			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>
	.uni-easyinput__content-input {
		font-size: 24rpx !important;
	}

	/deep/.uni-forms-item__inner {
		border-bottom: none !important;
		margin-bottom: 0 !important;
	}

	.uni-forms-item__label {
		font-size: 30rpx;
		display: flex;
		flex-shrink: 0;
		box-sizing: border-box;
		flex-direction: row;
		align-items: center;
		width: 65px;
		padding: 5px 0;
		/* height: 36px; */
	}

	/deep/ .uni-forms-item__content {
		display: flex !important;
		align-items: center !important;
		/* justify-content: space-between; */
	}
</style>
<style lang="scss" scoped>
	.number-inupt {
		display: flex !important;
		align-items: center !important;
	}

	.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;
	}

	.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;
	}

	.uni-input-placeholder {
		font-size: 24rpx !important;
	}

	/deep/.uni-date-x--border {
		border: 0px solid #dcdfe6 !important;
	}

	/deep/.is-input-border {
		border: 0px solid #c8c7cc !important;
	}
</style>
