<template>
	<view class="box3">
		<u-navbar :autoBack="true" title="投稿" bgColor="rgba(255,255,255,0)" :placeholder="true" titleStyle="font-weight:bold;color:#121212"></u-navbar>
		<view class="nav_fabu">
			<view class="nav_left" @click="releaseBtn(0)">
				<view class="left_icon"><uni-icons type="compose" size="20" color=" #ffffff"></uni-icons></view>
				<text>发文章</text>
			</view>
			<view class="nav_right" @click="releaseBtn(1)">
				<view class="left_icon" style="background-color: #4e7198"><uni-icons type="videocam" size="20" color=" #ffffff"></uni-icons></view>
				<text>发视频</text>
			</view>
			<view class="uptriangle" :class="{ uptriangle_active: releaseTab == 1, uptriangle: releaseTab == 0 }"></view>
		</view>
		<!-- 上传发布组件 -->
		<view style="width: 92%; margin: auto; margin-top: 30rpx">
			<u--input v-model.trim="titleVal" customStyle="background-color: #ffffff;height: 80rpx;" placeholder="请填写标题" border="surround" clearable></u--input>
		</view>
		<view class="" style="width: 92%; margin: auto; margin-top: 30rpx">
			<u-search
				searchIconSize="0"
				height="80rpx"
				:showAction="false"
				bgColor="#ffffff"
				:placeholder="searchVal ? searchVal : '关联文物'"
				v-model="val"
				shape="square"
				@change="searchBtn"
				:actionStyle="{ color: '#985741', fontSize: '30rpx', fontWeight: 'bold' }"
			></u-search>
		</view>
		<!-- 搜索的文物 -->
		<u-transition :show="searchList.length > 0">
			<scroll-view v-if="searchList.length > 0" class="search_box" scroll-y="true" @scrolltolower="LoadMore">
				<view>
					<view @click="searchItem(item)" class="item_tit" v-for="item in searchList" :key="item.id">
						{{ item.title }}
					</view>
				</view>
			</scroll-view>
		</u-transition>

		<view class="box">
			<!-- 上传照片 -->
			<view style="margin-left: 36rpx" v-if="releaseTab == 0">
				<view class="sc_box">
					<text class="sc_tp">请上传图片</text>
					<text class="sc_tp">{{ uploadNumber + '/' + 9 }}</text>
				</view>
				<u-upload
					width="200rpx"
					height="200rpx"
					:maxCount="9"
					imageMode="aspectFit"
					:deletable="true"
					:fileList="fileList1"
					@afterRead="afterRead"
					@delete="deletePic"
					name="1"
					multiple
				></u-upload>
			</view>
			<!-- 上传视频 -->
			<view style="margin-left: 26rpx" v-if="releaseTab == 1">
				<view class="sc_box">
					<text class="sc_tp">请上传视频</text>
				</view>
				<u-upload
					width="200rpx"
					height="200rpx"
					:fileList="fileList2"
					@afterRead="afterRead"
					@delete="deletePic"
					name="2"
					multiple
					:maxCount="10"
					accept="video"
				></u-upload>
			</view>

			<view class="banxin" style="background-color: #ffffff; margin-top: 20rpx">
				<!-- 				<u--textarea v-model.trim="textVal" placeholder="请输入内容"></u--textarea> -->
				<view class="" style="height: 400rpx">
					<sp-editor
						:toolbar-config="{
							excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
							iconSize: '18px'
						}"
						@input="inputOver"
						@upinImage="upinImage"
						@addLink="addLink"
						@exportHtml="exportHtml"
					></sp-editor>
				</view>
			</view>
			<!-- 分区 -->
			<u-popup :show="showTanCeng" mode="bottom" @close="close" bgColor="#efefef">
				<view class="show_box">
					<view class="" style="display: flex; justify-content: space-between">
						<text @click="showTanCeng = false">取消</text>
						<text @click="showTanCeng = false" class="box_ok">确认</text>
					</view>
					<view class="box_fenqu" @click="show = true">
						<text>选择投稿类型</text>
						<view style="display: flex">
							<text style="color: #999999; font-size: 28rpx">{{ typeName }}</text>
							<uni-icons color="#999999" type="forward" size="20"></uni-icons>
						</view>
					</view>
					<!-- 添加标签 -->
					<view class="box_tj">
						<text style="color: #999999; font-size: 28rpx">选择内容类型</text>
						<view class="tag_box">
							<view class="" v-for="(item, index) in radios" :key="index">
								<u-tag size="mini" :text="item.name" :plain="!item.checked" shape="circle" type="warning" :name="index" @click="radioClick"></u-tag>
							</view>
						</view>
					</view>

					<u-picker
						title="选择投稿类型"
						:show="show"
						@close="show = false"
						ref="uPicker"
						@cancel="show = false"
						keyName="name"
						:closeOnClickOverlay="true"
						:columns="columns"
						@confirm="confirm"
					></u-picker>
				</view>
			</u-popup>
			<view class="" style="background-color: #efefef; height: 20rpx; width: 100%"><!-- 分割背景 --></view>
			<view class="fq_box" @click="fenquBtn">
				<text>选择投稿类型</text>
				<view class="bq_box">
					<u-tag size="mini" shape="circle" text="文物" type="warning"></u-tag>
					<u-tag size="mini" shape="circle" text="非遗" type="success"></u-tag>
					<u-tag size="mini" shape="circle" text="民俗" type="error"></u-tag>
					<u-icon name="arrow-right" color="#666666" size="16"></u-icon>
				</view>
			</view>

			<!-- 评论 -->
			<view class="" style="background-color: #efefef; height: 20rpx; width: 100%"></view>

			<view class="queren" @click="isOk">确认发布</view>
		</view>
	</view>
</template>

<script>
let that;
export default {
	data() {
		return {
			val: '',
			cr_id: '' /* 文物id */,
			searchVal: '',
			searchList: [] /* 搜索的数组 */,
			isLoading: false,
			page: 1,
			prevSearchVal: '',
			releaseTab: 0,
			radios: [
				{
					name: '文章',
					id: 1,
					checked: true
				},
				{
					name: '视频',
					id: 2,
					checked: false
				},
				{
					name: '音频',
					id: 3,
					checked: false
				},
				{
					name: '相册',
					id: 4,
					checked: false
				}
			],
			model_id: '' /* 投稿模型id */,
			typeId: 1 /* 投稿内容类型id */,
			main_body_column_id: '' /* 投稿栏目id */,
			typeName: '' /* 选中的类型 */,
			closeTag: true,
			showTanCeng: false,
			show: false,
			columns: [
				[
					{ name: '我与文物的故事', id: 73 },
					{ name: '价值挖掘', id: 72 }
				]
			],
			titleVal: '',
			textVal: '',

			// 上传的图片
			fileList1: [],
			// 上传的视频
			fileList2: []
		};
	},
	onLoad() {
		that = this;
	},
	computed: {
		uploadNumber() {
			return this.fileList1.length;
		}
	},
	methods: {
		// 搜索
		searchBtn() {
			if (this.val) {
				// 只有在搜索词变化时重置page为1
				if (this.prevSearchVal !== this.val) {
					this.prevSearchVal = this.val; // 更新prevSearchVal为当前搜索词
					this.page = 1; // 当搜索词变化时重置page
					this.searchList = []; // 清空已有搜索结果
				}
				this.$api.getContentList(
					{
						main_body_id: 1,
						model_id: 1,
						keywords: this.val,
						page: this.page,
						pageSize: '10'
					},
					function (res) {
						that.searchList = [...that.searchList, ...res.data];
					}
				);
			} else {
				this.searchList = [];
			}
		},
		// 搜索的每项
		searchItem(item) {
			// console.log(item, 666666666);
			this.searchVal = item.title;
			this.cr_id = item.id;
			this.val = '';
			this.searchList = [];
		},
		// 下滑加载
		LoadMore() {
			this.page++;
			this.searchBtn();
		},
		releaseBtn(i) {
			this.releaseTab = i;
		},
		fenquBtn() {
			// this.show = true;
			this.showTanCeng = true;
		},

		confirm(e) {
			console.log('confirm', e.value);
			this.model_id = e.value[0].model_id;
			this.main_body_column_id = e.value[0].id;
			this.typeName = e.value[0].name;
			this.show = false;
		},

		// 删除图片
		deletePic(event) {
			console.log(event, 'event');
			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);
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
			console.log(this.fileList1, 'uuuu');
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let userToken = '';
				let auth = this.$db.get('auth');
				userToken = auth.token;
				let a = uni.uploadFile({
					url: this.$config.baseUrl + 'api/common/upload?token=' + userToken, // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: {},
					success: (res) => {
						setTimeout(() => {
							console.log(res);
							resolve(JSON.parse(res.data).data.fullurl);
						}, 1000);
					}
				});
			});
		},
		radioClick(name) {
			this.radios.map((item, index) => {
				item.checked = index === name ? true : false;
			});
			this.typeId = this.radios[name].id;
		},
		// 投稿
		isOk() {
			let titleIsEmpty = this.titleVal === '';
			let textIsEmpty = this.textVal === '';

			// 先检查标题和内容是否为空
			if (titleIsEmpty) {
				that.$common.errorToShow('请填写投稿标题');
				return false; // 遇到错误时提前返回，避免后续条件的判断
			}

			if (textIsEmpty) {
				that.$common.errorToShow('请输入投稿内容');
				return false;
			}

			// 再检查模型ID、类型ID和栏目ID
			if (this.model_id === '' || this.main_body_column_id === '') {
				that.$common.errorToShow('请选择投稿类型');
				return false;
			}
			let image = '';
			let images = '';
			if (this.fileList1.length !== 0) {
				image = this.fileList1[0].url;
				images = this.fileList1.map((itme) => itme.url).join(',');
			}

			// 如果typeId是必须选择的，这里也要进行验证
			if (this.typeId === '') {
				that.$common.errorToShow('请选择内容类型');
				return false;
			} else {
				this.$api.contribute(
					{
						main_body_id: 1,
						model_id: 1,
						main_body_column_id: this.main_body_column_id,
						title: this.titleVal,
						type: this.typeId,
						content: this.textVal,
						cr_id: this.cr_id,
						image: image,
						images: images
					},
					function (res) {
						if (res.code == 1) {
							that.$common.successToShow('投稿成功');
							setTimeout(() => {
								uni.redirectTo({
									url: '/user_fenbao/myTouGao/myTouGao'
								});
							}, 1000);
						} else {
							that.$common.errorToShow('投稿失败请稍后再试');
							// console.log(that.fileList1, 6666);
						}
					}
				);
			}
		},
		close() {
			this.showTanCeng = false;
			// console.log('close');
		},
		// 富文本相关
		inputOver(e) {
			// 可以在此处获取到编辑器已编辑的内容
			console.log('==== inputOver :', e);
			this.textVal = e.html;
		},

		upinImage(tempFiles, editorCtx) {
			that.$common.errorToShow('请在上方上传图片');
			// uni.chooseImage({
			// 	count: 1,
			// 	sizeType: ['compressed'],
			// 	sourceType: ['album'],
			// 	success: (res) => {
			// 		console.log('chooseImage', res.tempFilePaths);
			// 		var imageFileSrc = res.tempFilePaths;
			// 		let userToken = '';
			// 		let auth = this.$db.get('auth');
			// 		userToken = auth.token;
			// 		uni.uploadFile({
			// 			url: this.$config.baseUrl + 'api/common/upload?token=' + userToken, // 仅为示例，非真实的接口地址
			// 			filePath: imageFileSrc[0],
			// 			name: 'file',
			// 			formData: {
			// 				Accept: 'application/json',
			// 				'Content-Type': 'multipart/form-data',
			// 				token: userToken
			// 			},
			// 			success: (uploadFileRes) => {
			// 				console.log(JSON.parse(uploadFileRes.data), 9999);
			// 				var dataimg = JSON.parse(uploadFileRes.data);
			// 				this.imageSrc = dataimg.data.fullurl;
			// 				this.imagepath = dataimg.data.url;
			// 			}
			// 		});
			// 	},
			// 	fail: (err) => {
			// 		console.log('chooseImage fail', err);
			// 	}
			// });
		},
		/**
		 * 导出 - toolbar需要开启export工具
		 * @param {string} e 导出的html内容
		 */
		exportHtml(e) {
			uni.navigateTo({
				url: '/pages/personInfo/personalInfo',
				success(res) {
					// 传至导出页面解析即可
					res.eventChannel.emit('e-transmit-html', {
						data: e
					});
				}
			});
		},
		/**
		 * 添加超链接
		 * @param {Object} e { text: '链接描述', href: '链接地址' }
		 */
		addLink(e) {
			console.log('==== addLink :', e);
		}
	}
};
</script>

<style>
.box3 {
	width: 100%;
	padding-bottom: 50rpx;
	background-image: url('https://huli-app.wenlvti.net/app_static/WenWuGuanJia/image/xbg_2.png');
	background-size: 100% 100%;
	background-attachment: fixed;
	background-repeat: repeat-y;
	height: auto;
}
.uptriangle {
	position: absolute;
	top: 120rpx;
	left: 170rpx;
	width: 0px;
	height: 0px;
	border: 30rpx solid transparent;
	border-top-color: #ca5642;
}
.uptriangle_active {
	position: absolute;
	top: 120rpx;
	left: 510rpx;
	width: 0px;
	height: 0px;
	border: 30rpx solid transparent;
	border-top-color: #ca5642;
}
.banxin {
	margin: 0 32rpx 0 32rpx;
}
.u-upload__button.data-v-69e2a36e {
	background-color: #efefef !important;
}
.u-upload__deletable.data-v-69e2a36e {
	width: 35rpx !important;
	height: 35rpx !important;
}

.u-transition {
	margin-right: 12rpx;
}
.tag_box {
	display: flex;
	margin-top: 20rpx;
}

.nav_fabu {
	position: relative;
	display: flex;
	justify-content: space-evenly;
	background-color: #ca5642;
}
.nav_left {
	display: flex;
	justify-content: start;
	align-items: center;
	width: 282rpx;
	height: 123rpx;
	font-size: 32rpx;
	background: #f4f4f9;
	border: 6px solid #ca5642;
	border-radius: 20rpx;
}
.left_icon {
	width: 50rpx;
	height: 50rpx;
	text-align: center;
	line-height: 50rpx;
	border-radius: 50%;
	margin-left: 50rpx;
	background-color: #ca5642;
}
.nav_right {
	display: flex;
	justify-content: start;
	align-items: center;
	width: 282rpx;
	height: 123rpx;
	font-size: 32rpx;
	background: #f4f4f9;
	border: 6px solid #ca5642;
	border-radius: 20rpx;
}
.right_icon {
	width: 50rpx;
	height: 50rpx;
	margin-left: 50rpx;
	border-radius: 50%;
	background-color: #4e7198;
}

.sc_box {
	display: flex;
	align-items: center;
	margin: 40rpx 55rpx 40rpx 10rpx;
	border-bottom: 1px #dedede solid;
	height: 60rpx;
}
.sc_tp {
	font-size: 30rpx;
	color: #000000;
}
.fq_box {
	display: flex;
	justify-content: space-between;
	margin: 0 32rpx 0 50rpx;
	height: 105rpx;
	align-items: center;
}
.box {
	/* background-color: #ffffff; */
	/* 	padding-top: 20rpx;
	padding-bottom: 30rpx; */
}
.bq_box {
	display: flex;
	align-items: center;
}
.pl_box {
	display: flex;
	justify-content: space-between;
	margin: 0 32rpx 0 32rpx;
	height: 105rpx;
	align-items: center;
}
.show_box {
	width: 100%;
	height: 500rpx;
	padding: 20rpx;
}
.queren {
	height: 80rpx;
	background-color: #ca5642;
	border-radius: 35rpx;
	font-size: 30rpx;
	color: #ffffff;
	text-align: center;
	line-height: 80rpx;
	margin: 0 32rpx 0 32rpx;
}
.box_ok {
	line-height: 50rpx;
	text-align: center;
	color: #ffffff;
	width: 93rpx;
	height: 52rpx;
	background: #ca5642;
	border-radius: 26rpx;
}
.box_fenqu {
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-radius: 20rpx;
	margin-top: 20rpx;
	height: 105rpx;
	background-color: #ffffff;
	font-size: 30rpx;
	padding: 20rpx;
}
.box_tj {
	height: 300rpx;
	border-radius: 20rpx;
	background-color: #ffffff;
	margin-top: 20rpx;
	padding: 20rpx;
}
.search_box {
	width: 90%;
	position: absolute;
	height: 200px;
	z-index: 39;
	left: 32rpx;
	padding: 40rpx;
	background-color: #f7dfc0;
}
.item_tit {
	line-height: 50rpx;
	font-size: 30rpx;
}
</style>
