<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" validate-trigger="bind" err-show-type="undertext">
							<uni-forms-item name="name" required label="昵称">
								<uni-easyinput type="text" v-model="formData.platform_nickname" placeholder="请填写账号昵称">
								</uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="numberfans" required label="粉丝数">
								<uni-easyinput type="number" v-model="formData.fans_count" placeholder="请填写粉丝数量">
								</uni-easyinput>
							</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"
									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,
				loading: true,
				accountId: '',
				platform: {
					platform_id: '',
					platform_name: '',
					platform_icon: '',
				},
				isBind: true,
				imageData: [],
				formData: {
					platform_nickname: '',
					fans_count: '',
					home_page_url: '',
				},
				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",
					},
				},

			}
		},
		onReady() {},
		async onShow() {
			this.loading = true;
			uni.showLoading({
				title: '加载中'
			});
			await this.getinfo();
			if (!this.isBind) {
				await this.getaccount()
			};
			this.loading = false;
			uni.hideLoading();
		},
		onLoad() {},
		onLoad(options) {
			this.platform.platform_id = parseInt(options.platform_id)
			if (options.account_id) {
				this.accountId = parseInt(options.account_id)
				this.isBind = false
			}
		},
		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.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);
								}
							}
						}
					})
			},
			/**
			 * 手动提交
			 * @param {Object} form
			 */
			submitForm(form) {
				const urlReg =
					/(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%$#_]*)?/
				if (!urlReg.test(this.formData.home_page_url)) {
					uni.showToast({
						title: '主页链接格式不正确',
						icon: 'none'
					})
					return
				}
				let that = this
				uni.showModal({
					title: '提示',
					content: '请保证账号信息的准确性和真实性',
					success: function(res) {
						if (res.confirm) {
							that.$refs[form]
								.submit()
								.then(res => {
									console.log('表单的值：', res)
									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
													});
												}
											})

									}
								})
								.catch(errors => {
									console.error('验证失败：', errors)
									uni.showToast({
										title: '请填写所有信息',
										icon: 'none'
									})
								})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			exit() {
				uni.navigateBack()
			},
			ceshiChooseSuccess(tempFilePaths, e) { //选择图片返回
				console.log('ceshiChooseSuccess', tempFilePaths, e);
				if (e == 0) {
					this.store = 'talent_upload/' + this.guid() + '.png'
					// this.store = 'talent_upload/icon-warning.png'
				} else if (e == 1) {
					this.store = 'talent_upload/' + this.guid() + '.mp4'
				}
				/****************
				以下代码是自定义上传逻辑，仅供参考
				***************/
				this.imgUpload(tempFilePaths);
				/*******************************/
				console.log("imgdata" + this.imageData)
			},
			imgUpload(tempFilePaths) {
				let that = this
				console.log('imgUpload', tempFilePaths)
				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.statusCode); //打印响应状态码
						if (res.statusCode == '204') {
							that.imageData.push(config.EndPoint + '/' + fileName);
							console.log('上传图片成功', res)
							let obs_url = config.EndPoint + '/' + fileName; //用你自己的 bucket 名替换星号
							console.log(obs_url)
							that.formData.home_img = obs_url
							uni.showToast({
								title: '上传成功',
								icon: '成功'
							});
						} else {
							console.log('上传图片失败', res)
							uni.showToast({
								title: '上传失败',
								icon: '失败'
							});
						}
					},
					fail: function(e) {
						console.log(e);
						uni.showToast({
							title: '上传失败22222',
							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);
				});
			},
		},
	}
</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; */
	}
</style>
<style lang="scss" scoped>
	.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>
