<template>
	<view class="page">

		<view class="nav-bar">
			<view class="left">
				<view class="uni-btn-icon" @click="goBack">&#xe601;</view>
				<view class="center">发表想法</view>
			</view>
			<view class="right">
				<!-- <view class="btn" @click="onManage">管理</view> -->
				<view class="btn" @click="onSubmit" v-if="id && id < 1">发布</view>
				<view class="btn" @click="onSubmit" v-else>更新</view>
			</view>
		</view>

		<view class="enterContentDetails">
			<!-- 上限五张图片或一个视频 -->
			<view class="img_list">
				<view class="image" v-for="(item, index) in img_list" :key="index">
					<image class="upimg" :src="item" mode="aspectFill"></image>
					<image class="del" src="@/static/icon/img-del.png" @click="delIt(index)"></image>
					<view class="loading" v-if="item.startsWith('http') === false">
						<view class="loading-icon"></view>
					</view>
				</view>
				<view v-if="video_path" class="image">
					<video :src="video_path" controls style="width:100%;height:100%"></video>
					<image class="del" src="@/static/icon/img-del.png" @click="delVideo"></image>
				</view>
				<view class="image" @click="upload('list')" v-if="img_list.length < 9">
					<image class="txt" src="../../static/icon/sy_icon_jiahao02.png"></image>
				</view>
			</view>
			<view class="content-title">
				<input class="edit" v-model="ainfo.title" maxlength="20" placeholder="标题(必填)" />
			</view>
			<view class="content-textarea">
				<textarea class="edit2" auto-height v-model="ainfo.content" :maxlength="1000"
					placeholder="添加描述"></textarea>
			</view>

			<view class="agree">
				<text class="xy">{{ ainfo.content.length }}/1000</text>
			</view>


		</view>

		<view class="worksBox scale-tap" @click="upload4">
			<view class="optionalWorks">
				<view class="title">
					上传详情页
					<text style="font-weight: normal;">(支持长图)</text>
				</view>
			</view>
			<view class="select-box">
				<image src="../../static/icon/upload-icon.png"></image>
			</view>
		</view>








	</view>
</template>

<script>
	import permission from '@/common/permission.js';
	export default {
		components: {},
		data() {
			return {
				skey: '',
				pop_sel: false,
				cid: 0,
				catename: '',
				img2: '',
				ainfo: {
					id: 0,
					title: '',
					content: '',
					name: '',
					telphone: '',
					address: '',
					contact: '',
					num: '',
				},
				img_list: [],
				video_path: '',
				is_agree: 0,
				selectedWork: {},
				content_images: [],
			}
		},

		onLoad(params) {
			if (getApp().globalData.skey != "") {
				this.skey = getApp().globalData.skey;
			} else {
				this.skey = params.skey || ''; //1234567xef
			}
			if (params.id) {

				this.id = params.id;
			} else {
				this.id = -1;

			}
			let that = this;
			// this.getCate();
			that.getInfo();
			// this.getData();

			// 添加事件监听
			uni.$on('selectItem', this.handleSelect);


		},
		onUnload() {
			uni.$off('selectItem', this.handleSelect);
		},
		onShow() {
			let that = this;
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			handleSelect(item) {
				this.selectedWork = item;
			},
			delIt(ind) {
				let arr = [];
				if (this.img_list.length > 0) {
					for (let i = 0; i < this.img_list.length; i++) {
						if (i !== ind) {
							arr.push(this.img_list[i]);
						}
					}
					this.img_list = arr;
				}
			},
			getInfo() {
				var that = this;
				uni.request({
					url: this.$apiHost + '/Article/getinfo',
					data: {
						uuid: getApp().globalData.uuid,
						id: this.id
					},
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						this.ainfo = res.data.article;
						this.img_list = [];
						this.selectedWork = res.data.work_info;
						if (res.data.article.images.length > 1) {
							let arr = res.data.article.images.split("|");
							if (arr.length > 0) {
								for (let i = 0; i < arr.length; i++) {
									if (arr[i].length > 10) {
										this.img_list.push(arr[i]);
									}
								}
							}
						}
					}
				});
			},
			checkField(str, tips) {
				if (str.length < 2) {
					uni.showToast({
						title: tips,
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			onSubmit() {
				if (this.checkField(this.ainfo.title, "请输入名称") == false) return;
				if (this.checkField(this.ainfo.content, "请输入具体内容") == false) return;
				if (this.is_submit > 0) return;
				let img_str = '';
				if (this.img_list.length > 0) {
					for (let i = 0; i < this.img_list.length; i++) {
						img_str += this.img_list[i] + "|";
					}
				}
				if (this.img_list.length < 1 && !this.selectedWork.id) {
					uni.showToast({
						title: '请上传 图片 或 选择一个作品',
						icon: 'none'
					});
					return;
				} else {
					if (!this.selectedWork.id) {
						if (!img_str || img_str.trim().length < 2) {
							uni.showToast({
								title: '请确保至少上传一张有效图片作为封面',
								icon: 'none'
							});
							return;
						}
						if (this.img_list.length > 5) {
							uni.showToast({
								title: '最多只能上传 5 张图片',
								icon: 'none'
							});
							return;
						}
					}
				}
				let that = this;
				let contentImagesStr = '';
				if (this.content_images.length > 0) {
					for (let i = 0; i < this.content_images.length; i++) {
						contentImagesStr += this.content_images[i] + "|";
					}
				}
				this.is_submit = 1;
				console.log({
					uuid: getApp().globalData.uuid,
					id: this.ainfo.id,
					title: this.ainfo.title,
					content: this.ainfo.content,
					images: img_str,
					content_images: contentImagesStr,
					video_url: this.video_path,
				}, 9999999999);

				uni.request({
					url: this.$apiHost + '/crowdfund/seji/save',
					data: {
						uuid: getApp().globalData.uuid,
						id: this.ainfo.id,
						title: this.ainfo.title,
						content: this.ainfo.content,
						images: img_str,
						content_images: contentImagesStr,
						video_url: this.video_path,
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'sign': getApp().globalData.headerSign
					},
					dataType: 'json',
					success: (res) => {
						uni.showToast({
							title: res.data.str,
							icon: 'none'
						});
						if (res.data.success == "yes") {
							setTimeout(function() {
								uni.$emit('switchToMyPage', {
									type: 'article'
								});
								uni.switchTab({
									url: '/pages/my/my'
								})
							}, 500);
							that.ainfo.title = '';
							that.ainfo.content = '';
							that.ainfo.num = '';
							that.img_list = [];
						}
						this.is_submit = 0;
					},
					fail: (err) => {
						this.is_submit = 0;
					},
					complete: (com) => {}
				})
			},
			async upload(type) {
				// 权限弹窗校验
				if (plus.os.name.toLowerCase() === 'android') {
					let hasPermission = false;
					try {
						hasPermission = await permission.request('photoLibrary', {
							title: '相册/视频权限说明',
							describe: '便于您上传图片或视频，请您确认授权，否则无法使用该功能'
						});
						if (!hasPermission) {
							uni.showToast({
								title: '未获得相册权限',
								icon: 'none'
							});
							return;
						}
					} catch (e) {
						uni.showToast({
							title: '权限检查失败',
							icon: 'none'
						});
						return;
					}
				} else {

				}
				if (this.img_list.length >= 9 && !this.video_path) {
					uni.showToast({
						title: '最多只能上传9张图片',
						icon: 'none'
					});
					return;
				}
				uni.showActionSheet({
					itemList: ['拍照', '从相册选择'],
					success: (res) => {
						const sourceType = res.tapIndex === 0 ? 'camera' : 'album';
						this.upload_ext(sourceType);
					}
				});
				// uni.chooseMedia({
				// 	count: 9 - this.img_list.length,
				// 	mediaType: ['image', 'video'],
				// 	sourceType: ['album', 'camera'],
				// 	maxDuration: 60,
				// 	success: (res) => {
				// 		console.log(res, 'res');

				// 	}
				// });
			},
			upload_ext(sourceType) {
				console.log("----upload");
				var _self = this;
				uni.chooseMedia({
					count: 9 - this.img_list.length,
					mediaType: ['image'], //, 'video'
					sourceType: [sourceType],
					maxDuration: 60,
					success: function(res) {
						console.log('res:', res)
						if (res.tempFiles && res.tempFiles.length > 0) {
							// 根据文件类型判断
							let videoFiles = res.tempFiles.filter(file => file.fileType === 'video');
							let imageFiles = res.tempFiles.filter(file => file.fileType === 'image');

							if (videoFiles.length > 0) {
								// 如果多选视频，只处理第一个并提示
								if (videoFiles.length > 1) {
									uni.showToast({
										title: '只能上传一个视频，已自动选取第一个',
										icon: 'none'
									});
								}
								// 如果已存在视频，替换并提示
								if (_self.video_path) {
									uni.showToast({
										title: '已替换为新上传的视频',
										icon: 'none'
									});
								}
								_self.upload2('list', videoFiles[0].tempFilePath, 'video',
									'/Xweb/upload_video?skey=');
								console.log(videoFiles, 'videoFiles');
							}

							console.log(imageFiles, 'imageFiles');
							if (imageFiles.length > 0) {
								// 多图全部上传
								imageFiles.forEach(img => {
									_self.upload2('list', img.tempFilePath, 'image',
										'/Xweb/upload_img?skey=');
								});
							}
						}
						// for (let index = 0; index < res.tempFilePaths.length; index++) {
						// 	let filepath = "";
						// 	// #ifdef H5
						// 	filepath = res.tempFiles[index].path;
						// 	// #endif

						// 	// #ifdef APP-PLUS
						// 	filepath = res.tempFilePaths[index];
						// 	// #endif

						// 	_self.imglocal = filepath; //res.tempFilePaths[0]
						// 	const uploadTask = uni.uploadFile({
						// 		url: _self.$apiHost + '/Xweb/upload_img?skey=' + _self
						// 			.skey, // post请求地址
						// 		filePath: filepath,
						// 		name: 'file', // 待确认
						// 		success: function(uploadFileRes) {
						// 			let resdata = JSON.parse(uploadFileRes.data)
						// 			console.log('Success1:', uploadFileRes);
						// 			if (resdata.success == 'no') {
						// 				uni.showToast({
						// 					title: resdata.str,
						// 					icon: 'none'
						// 				});
						// 				return;
						// 			}
						// 			if (resdata.code == 0) {
						// 				console.log('Success2:', resdata.data.path);

						// 				_self.content_images.push(resdata.data.path)
						// 				console.log('_self.content_images:', _self.content_images);
						// 				.0
						// 			}
						// 		},
						// 		fail: function(uploadFileFail) {
						// 			console.log('Error:', uploadFileFail.data);
						// 		},
						// 		complete: () => {
						// 			console.log('Complete:');
						// 		}
						// 	});
						// }
					},
					fail: function(e) {
						console.log(e);
					}
				});


			},
			delVideo() {
				this.video_path = '';
			},
			upload2(type, filepath, fileType, url) {
				console.log(filepath, 'filepath');
				console.log(fileType, 'fileType');

				// 上传前先显示临时图
				if (fileType === 'image') {
					this.img_list.push(filepath);
				} else if (fileType === 'video') {
					this.video_path = filepath;
				}

				let uploadUrl = this.$apiHost + url + this.skey;
				console.log({
					url: uploadUrl,
					filePath: filepath,
					name: 'file',
				}, 99999);
				let that = this;

				uni.uploadFile({
					url: uploadUrl,
					filePath: filepath,
					name: 'file',
					success: (uploadFileRes) => {
						console.log(uploadFileRes, 'uploadFileRes');

						let resdata = JSON.parse(uploadFileRes.data);
						if (resdata.success == 'no') {
							uni.showToast({
								title: resdata.str,
								icon: 'none'
							});
							// 上传失败时移除临时图
							if (fileType === 'image') {
								that.img_list.pop();
							} else if (fileType === 'video') {
								that.video_path = '';
							}
							return;
						}
						if (resdata.code == 0) {
							if (fileType === 'image') {
								// 替换临时图为服务端路径
								const index = that.img_list.indexOf(filepath);
								if (index !== -1) {
									// 使用 Vue.set 确保响应式更新
									that.$set(that.img_list, index, resdata.data.path);
								}
								// this.img_list.push(resdata.data.path);
								console.log("img_list-1", that.img_list);
							} else if (fileType === 'video') {
								that.video_path = resdata.data.path;
							}
						}
					},
					fail: () => {
						// 上传失败时移除临时图
						if (fileType === 'image') {
							that.img_list.pop();
						} else if (fileType === 'video') {
							that.video_path = '';
						}
					}
				});
			},



			upload4(type) {
				if (this.content_images.length >= 5) {
					uni.showToast({
						title: '最多只能上传5张图片',
						icon: 'none'
					});
					return
				}
				uni.showActionSheet({
					itemList: ['拍照', '从相册选择'],
					success: (res) => {
						const sourceType = res.tapIndex === 0 ? 'camera' : 'album';
						if (plus.os.name.toLowerCase() === 'android') {
							this.checkRights1(sourceType);
						} else {
							this.upload5('list', sourceType);

						}
					}
				});
			},
			async checkRights1(sourceType) {
				try {
					let hasPermission = false;

					if (sourceType === 'camera') {
						hasPermission = await permission.request(permission.PermissionType.CAMERA, {
							title: '“萌创星球”想访问你的相机',
							describe: '萌创星球想访问您的摄像头，便于拍摄获取图片来与其他用户进行交流'
						});

						if (!hasPermission) {
							uni.showToast({
								title: '未获得相机权限',
								icon: 'none'
							});
							return;
						}
					} else {
						hasPermission = await permission.request(permission.PermissionType.PHOTO_LIBRARY, {
							title: '“萌创星球”想访问你的照片图库',
							describe: '萌创星球想访问您本地照片图库，便于获取图片来与其他用户进行交流'
						});

						if (!hasPermission) {
							uni.showToast({
								title: '未获得相册权限',
								icon: 'none'
							});
							return;
						}
					}

					// 权限获取成功后，继续执行上传
					this.upload5('list', sourceType);
				} catch (error) {
					console.error('权限检查失败：', error);
					uni.showToast({
						title: '权限检查失败',
						icon: 'none'
					});
				}
			},
			upload5(type, sourceType) {
				console.log("----upload");
				var _self = this;
				uni.chooseImage({
					count: 5,
					sizeType: ['compressed'],
					sourceType: [sourceType],
					success: function(res) {
						console.log('res:', res)
						for (let index = 0; index < res.tempFilePaths.length; index++) {
							let filepath = "";
							// #ifdef H5
							filepath = res.tempFiles[index].path;
							// #endif

							// #ifdef APP-PLUS
							filepath = res.tempFilePaths[index];
							// #endif

							_self.imglocal = filepath; //res.tempFilePaths[0]
							const uploadTask = uni.uploadFile({
								url: _self.$apiHost + '/Xweb/upload_img?skey=' + _self
									.skey, // post请求地址
								filePath: filepath,
								name: 'file', // 待确认
								success: function(uploadFileRes) {
									let resdata = JSON.parse(uploadFileRes.data)
									console.log('Success1:', uploadFileRes);
									if (resdata.success == 'no') {
										uni.showToast({
											title: resdata.str,
											icon: 'none'
										});
										return;
									}
									if (resdata.code == 0) {
										console.log('Success2:', resdata.data.path);

										_self.content_images.push(resdata.data.path)
										console.log('_self.content_images:', _self.content_images);
										.0
									}
								},
								fail: function(uploadFileFail) {
									console.log('Error:', uploadFileFail.data);
								},
								complete: () => {
									console.log('Complete:');
								}
							});
						}
					},

					error: function(e) {

						console.log(e);

					}

				});


			},
		}
	}
</script>

<style scoped lang="scss">
	page {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		display: flex;
		background-color: #f2f6f2;
		min-height: 100vh;
	}

	.status_bar {
		height: 44rpx;
		width: 100%;
	}

	.page {
		background-color: #f2f6f2;
		display: flex;
		flex-direction: column;
		width: 750rpx;
		min-height: 100vh;
	}

	.nav-bar {
		width: calc(100ve - 73rpx);
		height: calc(96rpx + var(--status-bar-height));
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0;
		padding-right: 40rpx;
		padding-left: 33rpx;
		padding-top: var(--status-bar-height);
		box-sizing: border-box;

		.left {
			display: flex;
			align-items: center;
			font-family: PingFang SC-Bold;
			font-weight: 400;
			font-size: 32rpx;
			color: #1f1f1f;

			.uni-btn-icon {
				font-size: 45rpx;
				font-weight: bold;
				color: #1f1f1f;
				transition: color 0.2s;
				margin-right: 20rpx;

				&:active {
					color: #2b85e4;
				}
			}
		}

		.right {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			font-family: "PingFang SC-Bold";
			font-weight: 400;

			.btn {
				border-radius: 26rpx;
				background: #1f1f1f;
				padding: 6rpx 32rpx;
				color: #acf934;
				font-size: 28rpx;
			}
		}
	}

	.enterContentDetails {
		width: calc(100% - 40rpx);
		min-height: 726rpx;
		background: #ffffff;
		border-radius: 20rpx;
		margin: 0 20rpx;
		padding: 0rpx 24rpx 24rpx 24rpx;
		box-sizing: border-box;

		.edit {
			height: 92rpx;
			border-bottom: 2rpx solid #f2f6f2;
		}

		.edit2 {
			min-height: 350rpx;
			width: 100%;
		}

		.content-textarea {
			padding-top: 24rpx;
		}

		::v-deep.input-placeholder,
		::v-deep.textarea-placeholder {
			font-family: PingFang SC;
			font-weight: 400;
			font-size: 32rpx;
			color: #999999;
		}

		.agree {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		.img_list {
			width: 100%;
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			row-gap: 20rpx;
			flex-wrap: wrap;
			margin-top: 15rpx;

			.image {
				display: flex;
				width: 208rpx;
				height: 208rpx;
				position: relative;
				box-sizing: border-box;
				justify-content: center;
				align-items: center;
				background: #f2f6f2;
				border-radius: 16rpx;

				.txt {
					font-size: 120rpx;
					color: #999;
					width: 40rpx;
					height: 40rpx;
				}

				.upimg {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}

				.del {
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					right: 0rpx;
					top: 0rpx;
				}

				.loading {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
					background: rgba(0, 0, 0, 0.5);
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 8rpx;

					.loading-icon {
						width: 40rpx;
						height: 40rpx;
						border: 4rpx solid #fff;
						border-top-color: transparent;
						border-radius: 50%;
						animation: spin 1s linear infinite;
					}
				}
			}
		}
	}

	.worksBox {
		border-radius: 20rpx;
		overflow: hidden;
		margin: 0 24rpx;
		background: #fff;
		margin-top: 20rpx;
		padding-left: 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.optionalWorks {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 24rpx;
			height: 88rpx;
			padding-left: 0;

			.title {
				font-family: "PingFang SC-Bold";
				font-weight: bold;
				font-size: 28rpx;

				text {
					color: #bbb;
					font-size: 24rpx;
					padding-left: 10rpx;
				}
			}
		}

		.select-box {
			width: 64rpx;
			height: 64rpx;

			image {
				width: 64rpx;
				height: 64rpx;
			}
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>