<template>
	<view>
		<bgNavBar title="编辑视频信息"></bgNavBar>
		<view class="videobox x-c">
			<video v-if="fileList1.length>0" :src="fileList1[0].url" :poster="fileList1[0].thumbnailUrl"
				:autoplay='true' class="video">
				<cover-view class="closeempty" v-if="fileList1.length>0">
					<cover-image class="closeempty-img" src="/static/images/del.png" @click="deletePic($event,'myevent')"></cover-image>
				</cover-view></video>
			<view v-else>
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="1" accept="video">
					<view class="uploadbox" v-if="!loading">
						<uni-icons type="plusempty" size="30"></uni-icons>
						<text>上传视频</text>
					</view>
					<view class="uploadbox" v-else>
						<u-loading-icon></u-loading-icon>
						<text style="color: #999;">上传中...</text>
					</view>
				</u-upload>
			</view>
		</view>
		<view style="position: relative;">
			<view class="es-pl-24 es-pr-24 es-pt-24 es-pb-24">
				<view class="box es-br-24 es-mb-24">
					<view class="box-title x-bc" @click="showPop">
						<text class="name">分区或标签</text>
						<uni-icons type="right" size="16" color="#222"></uni-icons>
					</view>
					<view class="tags">
						<u-tag v-for="(tag,index) in chooseTagList" :key="index" :text="tag.label" closable
							color="#FF233C" bgColor="#ffe8dc" borderColor="#ffe8dc" :show="tag.checked"
							@close="closeTag(index)"></u-tag>
					</view>
				</view>
				<view class="box es-br-24 es-mb-24">
					<view class="box-title x-bc es-mb-24">
						<text class="name">标题</text>
					</view>
					<u--input placeholder="请输入标题" border="none" v-model.trim="form.title" clearable
						maxlength="50"></u--input>
				</view>
				<view class="box es-br-24">
					<view class="box-title x-bc es-mb-24">
						<text class="name">描述</text>
					</view>
					<u--textarea v-model.trim="form.description" border="none" autoHeight
						placeholder="介绍你的视频，让更多人了解你的作品" maxlength="300"></u--textarea>
				</view>
				<view class="footer-btn">
					<view @click="submit">发布</view>
				</view>
			</view>
		</view>
		<u-popup :show="show" mode="bottom" closeable :round="16" @close="close">
			<view class="tagpop">
				<view class="tagpop-title">选择标签</view>
				<view class="tagpop-box">
					<scroll-view scroll-y="true" style="height: 50vh;">
						<view v-for="(item,index) in tags" :key="index" class="tag-group">
							<view class="tag-label">{{ item.label }}</view>
							<view class="child-label-box">
								<u-tag class="child-label" v-for="(it,idx) in item.children" :key="idx" :text="it.label"
									:color="it.checked?'#FF233C':'#666'" :bgColor="it.checked?'#ffe8dc':'#fff'"
									:borderColor="it.checked?'#ffe8dc':'#eee'" @click="chooseTag(index,idx)"></u-tag>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</u-popup>
		<!-- <tagpop ref="tagpop"></tagpop> -->
	</view>
</template>

<script>
	// import tagpop from "./components/tagpop.nvue"
	import bgNavBar from "./components/bgNavBar.vue"
	import {
		navBack
	} from "../../utils/common";
	import {
		uploadOSSTalent,
		talentVideo,
		getTag
	} from "@/api/expert.js"
	export default {
		components: {
			bgNavBar,
			// tagpop
		},
		data() {
			return {
				current: 1,
				interval: 3000,
				duration: 1000,
				autoplay: true,
				advImgs: [{}],
				form: {
					duration: null,
					url: '',
					thumbnailUrl: '',
					title: '',
					description: ''
				},
				value: '',
				value1: '',
				videoUrl: '',
				thumbnail: '',
				fileList1: [],
				tags: [],
				chooseTagList: [],
				show: false,
				loading: false
			}
		},
		onLoad() {
			// #ifdef APP-PLUS
			const subNVue = uni.getSubNVueById('tagpop');
			subNVue.hide('slide-out-bottom');
			// #endif
			uni.$on("chooseTag",data=>{
				this.tags = data
				this.chooseTagList = this.findCheckedItems(this.tags)
			})
			this.uploadVideo()
			// #ifndef APP-PLUS
			this.getTags()
			// #endif
		},
		onUnload() {
			uni.$off("chooseTag")
		},
		methods: {
			showPop() {
				// #ifndef APP-PLUS
				this.show = true
				// #endif
				// #ifdef APP-PLUS
				const subNVue = uni.getSubNVueById('tagpop');
				subNVue.show('slide-in-bottom', 250);
				// #endif
			},
			close() {
				this.show = false
				this.chooseTagList = this.findCheckedItems(this.tags)
			},
			findCheckedItems(tags) {
				let checkedItems = [];
				// 遍历tags数组
				tags.forEach(tag => {
					// 如果当前标签的children存在且有checked为true的item
					if (tag.children) {
						tag.children.forEach(child => {
							if (child.checked) {
								checkedItems.push(child); // 将符合条件的item加入数组
							}
						});
					}
				});

				return checkedItems;
			},
			closeTag(index) {
				this.chooseTagList[index].checked = false
			},
			chooseTag(index, idx) {
				this.tags[index].children[idx].checked = !this.tags[index].children[idx].checked
			},
			uploadVideo() {
				let self = this
				// #ifdef APP-PLUS
				if (!plus.runtime.isAgreePrivacy()) {
					uni.showToast({
						title: "请同意隐私政策",
						icon: "none"
					});
					return;
				}
				// #endif
				uni.chooseVideo({
					sourceType: ['album'],
					success: async (res) => {
						const result = await this.uploadFilePromise(res.tempFilePath)
						this.fileList1 = [{
							url: result.url,
							thumbnailUrl: result.thumbnailUrl,
							duration: result.videoInfo.duration
						}]
					}
				});
			},
			getTags() {
				getTag().then(res => {
					if (res.code == 200) {
						this.tags = res.data || []
						this.tags = this.addCheckedProperty(this.tags)
					}
				})
			},
			addCheckedProperty(tags) {
				return tags.map(tag => {
					// 为当前对象添加checked属性
					const updatedTag = {
						...tag,
						checked: false
					};
					// 如果有子对象，递归处理
					if (updatedTag.children) {
						updatedTag.children = this.addCheckedProperty(updatedTag.children);
					}
					return updatedTag;
				});
			},
			submit() {
				if (this.fileList1.length == 0) {
					uni.showToast({
						title: "请上传视频",
						icon: "none"
					})
					return
				}
				let arry = this.chooseTagList.filter(item=>item.checked)
				let tags = []
				if(arry&&arry.length>0) {
					tags = arry.map(it=>it.value)
				}
				if (!this.form.title.trim()) {
					uni.showToast({
						title: "请输入标题",
						icon: "none"
					})
					return
				}
				if (!this.form.description.trim()) {
					uni.showToast({
						title: "请输入描述",
						icon: "none"
					})
					return
				}
				const form = {
					title: this.form.title,
					description: this.form.description,
					url: this.fileList1[0].url,
					thumbnail: this.fileList1[0].thumbnailUrl,
					duration: this.fileList1[0].duration,
					tags: tags.join(',')
				}
				uni.showLoading({
					title: '发布中',
				})
				talentVideo(form).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						uni.showToast({
							title: '发布成功，待管理员审核',
							icon: 'none'
						})
						uni.$emit("resetData")
						setTimeout(() => {
							this.$navBack()
						}, 1500)
					}
				}).catch(() => {
					uni.hideLoading()
				})
			},
			deletePic(event, type) {
				uni.hideToast()
				if (type == 'myevent') {
					this.fileList1.splice(0, 1)
				} else {
					this[`fileList${event.name}`].splice(event.index, 1)
				}
			},
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					if (result.code != 200) {
						uni.showToast({
							title: '上传视频失败',
							icon: 'error'
						})
						return
					}
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url,
						thumbnailUrl: result.thumbnailUrl,
						duration: result.videoInfo.duration
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: '上传中',
					})
					this.loading = true
					let a = uni.uploadFile({
						url: uni.getStorageSync('requestPath') +
							'/app/talent/uploadOSSTalent', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						success: (res) => {
							resolve(JSON.parse(res.data))
						},
						fail: (err) => {
							uni.showToast({
								title: '上传视频失败',
								icon: 'error'
							})
						},
						complete: () => {
							uni.hideLoading()
							this.loading = false
						}
					});
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}

	.tagpop {
		background-color: #fff;
		overflow: hidden;
		border-radius: 16rpx 16rpx 0 0;
		padding: 24rpx;

		&-title {
			text-align: center;
		}

		.tag-group {
			// background-color: #ffffff;
			// border: 1px solid #ddd;
			// margin-bottom: 10px;
			// padding: 10px;
			// border-radius: 5px;
		}

		.tag-label {
			font-size: 16px;
			font-weight: bold;
			margin-bottom: 5px;
			// background-color: #f7f7f7;
		}

		.child-label-box {
			@include u-flex(row, center, flex-start);
			flex-wrap: wrap;
		}

		.child-label {
			margin: 0 16rpx 16rpx 0;
		}
	}
	.video {
		width: 694rpx;
		height: 390rpx;
		border-radius: 20rpx;
		overflow: hidden;
	}
	.videobox {
		width: 694rpx;
		height: 390rpx;
		margin: 32rpx auto 16rpx auto;
		border-radius: 20rpx;
		overflow: hidden;
		position: relative;
		background-color: #fff;

		.closeempty {
			position: absolute;
			z-index: 99;
			right: 0;
			top: 0;
			background-color: #fff;
			border-radius: 0 20rpx 0 20rpx;
			padding: 10rpx;
			.closeempty-img {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.uploadbox {
		width: 200rpx;
		height: 200rpx;
		@include u-flex(column, center, center);
		text {
			margin-top: 16rpx;
		}
	}

	.box {
		padding: 24rpx;
		background-color: #fff;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 34rpx;
		color: #222222;
	}

	.tags {
		@include u-flex(row, center, flex-start);
		flex-wrap: wrap;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #555;
	}

	.footer-btn {
		@include u-flex(row, center, center);
		font-family: PingFang SC, PingFang SC;
		margin-top: 60rpx;

		view {
			width: 602rpx;
			height: 88rpx;
			background: #FF233C;
			border-radius: 26rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 32rpx;
			color: #FFFFFF;
			@include u-flex(row, center, center);
		}
	}
</style>