<template>
	<view style="position: relative;">
		<!-- 胶囊 -->
		<mvBar :mysNavConfig="mysNavConfig"></mvBar>
		<view :style="{marginTop:navH}"></view>
		<view @click="toRecord()" style="margin-bottom:20rpx">
			<view style="display: flex;justify-content: center;">
				<image style="height: 60rpx;width: 60rpx;" src="../../static/img/icon-clock.png"></image>
			</view>
			<view style="display: flex;justify-content: center;">
				<p style="font-size: 30rpx;">查看修改/反馈记录</p>
			</view>
		</view>

		<view v-if="!loading && !onlyShow">
			<view style="display: flex;justify-content: center;">
				<radio-group @change="chan">
					<label v-for="item in radioGroup" :key="item">
						<view style="display: inline;margin: 0 20rpx">
							<radio :value="item" :checked="item==activeRadio" color="#fdd544" />{{item}}
						</view>
					</label>
				</radio-group>
			</view>

			<view style="margin: 30rpx;display: flex;justify-content: center;" v-if="activeRadio == '图文'">
				<htz-image-upload :max="18" mediaType="image" name="file" :chooseNum="9" v-model="imageData"
					@chooseSuccess="ceshiChooseSuccess1">
				</htz-image-upload>
			</view>

			<view style="margin: 30rpx;display: flex;justify-content: center;" v-if="activeRadio == '视频'">
				<htz-image-upload :max="1" mediaType="video" name="file" :chooseNum="1" v-model="videoData"
					@chooseSuccess="ceshiChooseSuccess2">
				</htz-image-upload>
			</view>

			<view style="padding: 20rpx 30rpx 0;">
				<uni-easyinput type="text" :inputBorder="false" v-model="title" placeholder="在此填写让人眼前一亮的标题吧"
					:placeholderStyle="placeholderStyle">
				</uni-easyinput>
			</view>
			<!-- 多行输入框 -->
			<view style="padding: 40rpx 30rpx 150rpx;font-size: 30rpx;">
				<textarea v-model="text" maxlength="2000" auto-height="true" placeholder="添加正文" />
			</view>
			<view class="signup">
				<button type="default" class="but1" :loading="loading" :class="{'on':item.title == '1',}"
					@click="submit()">
					提交初稿</button>
			</view>
		</view>

		<view v-if="!loading && onlyShow">
			<view v-if="activeRadio == '图文'">
				<view class="image-list">
					<!-- 图文 -->
					<view class="image-item" v-for="photo in imageData">
						<image :src="photo" mode="aspectFill" style="width: 100%;height: 100%;"
							@click="handlePreviewImage1(photo)"></image>
					</view>
				</view>
			</view>
			<!-- 视频 -->
			<view style="display: flex;align-items: center;justify-content: center;" v-if="activeRadio == '视频'">
				<video :src="videoData[0]"></video>
			</view>
			<view>
				<p style="font-size: 30rpx;padding: 20rpx 30rpx 0 ;">{{title}}</p>
				<view style="padding: 40rpx 30rpx 150rpx;font-size: 30rpx;">
					<text style="font-size: 30rpx;"> {{text}}</text>
				</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 {
				onlyShow: false,
				loading: true,
				placeholderStyle: "font-size: 30rpx;",
				navH: getApp().globalData.navHeight,
				taskId: "",
				title: "",
				text: "",
				sketchStatus: "",
				activeRadio: '图文', //存的是选中的value值
				radioGroup: ['图文', '视频'],
				videoData: [],
				imageData: [],
				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",
					},
				},
			}
		},

		onLoad(options) {
			let data = options.textObj.replace(/""/g, "");
			data = JSON.parse(decodeURIComponent(data))
			this.taskId = data.taskId
			this.sketchStatus = data.sketchStatus
			this.getSketch()
		},
		methods: {
			chan(e) {
				this.activeRadio = e.detail.value;
				console.log(this.activeRadio);
			},
			handlePreviewImage1(item) {
				console.log("image src: ", item)
				let that = this
				wx.previewImage({
					current: item, // 当前显示图片的http链接
					urls: that.imageData // 需要预览的图片http链接列表
				})
			},
			async getSketch() {
				this.loading = true
				uni.showLoading({
					title: '加载中'
				});
				await this.$https.get('/youngee/c/t/g/get-unsubmit-task-sketch' +
						"?" +
						"task_id" +
						"=" +
						this.taskId)
					.then(res => {
						console.log(res)
						if (res.data.data != null) {
							this.onlyShow = true
							this.title = res.data.data.title
							this.text = res.data.data.content
							if (res.data.data.type == 1) { // 图文
								this.activeRadio = '图文'
								for (var j = 0; j < res.data.data.Photo.length; j++) {
									this.imageData.push(res.data.data.Photo[j].photo_url)
								}
							} else if (res.data.data.type == 2) { //视频
								this.activeRadio = '视频'
								for (var j = 0; j < res.data.data.Photo.length; j++) {
									this.videoData.push(res.data.data.Photo[j].photo_url)
								}
							}
						}
					})
				uni.hideLoading();
				this.loading = false
			},
			toRecord() {
				var data = {
					taskId: this.taskId,
				};
				data = JSON.stringify(data)
				uni.navigateTo({
					url: '/page_workspace/task/record/sketchrecord?textObj=' + encodeURIComponent(data)
				});
			},

			submit() {
				// 检验标题和内容是否为空
				let type = 0
				let photourl = []
				if (this.activeRadio == '图文') { // 图文
					type = 1
					photourl = this.imageData
				} else {
					type = 2
					photourl = this.videoData
				}
				// if (photourl.length == 0) {
				// 	uni.showToast({
				// 		title: "请上传初稿图片或视频",
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				if (type === 1) {
					if (this.title == '') {
						uni.showToast({
							title: "请填写初稿标题",
							icon: 'none'
						})
						return
					}
					if (this.text == '') {
						uni.showToast({
							title: "请填写初稿内容",
							icon: 'none'
						})
						return
					}
				}
				console.log("photourl:", photourl)
				let that = this
				uni.showModal({
					title: '提示',
					content: '提交后无法修改并进行审核，确认提交？',
					success: async function(res) {
						if (res.confirm) {
							await that.$https.post('/youngee/c/t/p/add-task-sketch', {
									task_id: that.taskId,
									title: that.title,
									content: that.text,
									type: type,
									photo_url: photourl.toString()
								})
								.then(res => {
									console.log(res)
								})
							await that.$https.get('/youngee/c/t/g/submit-task-sketch' +
									"?" +
									"task_id" +
									"=" +
									that.taskId)
								.then(res => {
									console.log(res)
								})

							uni.navigateBack()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			},
			ceshiChooseSuccess1(tempFilePaths, e) { //选择图文返回
				console.log('ceshiChooseSuccess', tempFilePaths, e);
				/****************
				以下代码是自定义上传逻辑，仅供参考
				***************/
				this.imgUpload1(tempFilePaths, e);
				/*******************************/
				console.log("imgdata" + this.imageData)
			},
			imgUpload1(tempFilePaths, e) {
				let that = this
				console.log('imgUpload', tempFilePaths)
				let config = {
					AccessKeyId: 'IVW21DTGIIUBBAGXKK0Y', //AK
					SecretKey: 'Y01nEQNcLOATMw7uJwrk3yOdQZ2fqLhSnXcOKVDE', //SK
					EndPoint: 'https://horastar.obs.cn-east-3.myhuaweicloud.com', //上传文件的路径
				};

				for (let i = 0; i < tempFilePaths.length; ++i) {
					if (e == 0) {
						this.store = 'talent_upload/' + this.guid() + '.png'
					} else if (e == 1) {
						this.store = 'talent_upload/' + this.guid() + '.mp4'
					}
					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[i],
						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: '上传失败',
								icon: '失败'
							});
						}
					})
				}

			},
			ceshiChooseSuccess2(tempFilePaths, e) { //选择视频返回
				console.log('ceshiChooseSuccess', tempFilePaths, e);
				if (e == 0) {
					this.store = 'talent_upload/' + this.guid() + '.png'
				} else if (e == 1) {
					this.store = 'talent_upload/' + this.guid() + '.mp4'
				}
				/****************
				以下代码是自定义上传逻辑，仅供参考
				***************/
				this.imgUpload2(tempFilePaths);
				/*******************************/
				console.log("videoData" + this.videoData)
			},
			imgUpload2(tempFilePaths) {
				let that = this
				console.log('videoUpload', tempFilePaths)
				let config = {
					AccessKeyId: 'IVW21DTGIIUBBAGXKK0Y', //AK
					SecretKey: 'Y01nEQNcLOATMw7uJwrk3yOdQZ2fqLhSnXcOKVDE', //SK
					EndPoint: 'https://horastar.obs.cn-east-3.myhuaweicloud.com', //上传文件的路径
				};
				let fileName = this.store; //指定上传到OBS桶中的对象名
				// let fileName = "talent_upload/icon-arrow-right.png"
				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.videoData.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: '上传失败',
							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>
	/deep/ .uni-easyinput__content-input {
		font-size: 30rpx !important;
		padding: 0 !important;
	}
</style>

<style lang="scss" scoped>
	.signup {
		box-shadow: 0rpx 5rpx 40rpx #ccc;
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		display: flex;
		height: 90rpx;
		padding-top: 2%;
		background-color: #FFFFFF;
		z-index: 99;
	}

	.image-list {
		margin: 0 22.5rpx;
		display: flex;
		flex-wrap: wrap;
		// justify-content: space-between;
	}

	.image-item {
		width: 220rpx;
		height: 220rpx;
		margin: 10rpx 7.5rpx;
	}

	.but1 {
		width: 60%;
		background-color: #f2d22d;
		border-radius: 20rpx;
		font-size: 36rpx;
		line-height: 200%;
		letter-spacing: 10rpx;
		font-weight: 500;
		height: 80%;

		&.on {
			background-color: #C0C0C0;

		}

	}
</style>