<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="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 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>
				<view class="image" @click="upload('list')" v-if="img_list.length < 9">
					<!-- <text class="txt">+</text> -->
					<image class="txt" src="../../static/icon/sy_icon_jiahao02.png"></image>
				</view>
			</view>

		</view>

		<view class="worksBox">
			<view class="optionalWorks" @click="onManage">
				<view class="title">
					可选作品
					<text v-if="id < 1">(图片或作品必选一个发布)</text> 
				</view>
				<view class="selectLeft">
					<text class="prompt" v-if="id > 1">已选择一个作品</text>
					<image class="rightArrow" src="../../static/me/wd_icon_jiantou2.png"></image>
				</view>
			</view>
			<view class="activeItem" v-if="selectedWork.images">
				<view class="img-box">
					<image :src="selectedWork.images"></image>
				</view>
				<view class="info">
					<view class="title">{{ selectedWork.title }}</view>
				</view>
				<view class="select-box" @click="deleteWorkInfo()">
					<image src="../../static/icon/close.png"></image>
				</view>
			</view>
		</view>



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



		<view class="user-list" v-if="false">
			<view class="content">
				<input class="edit" v-model="ainfo.title" maxlength="20" placeholder="填写标题会有更多赞哦~" />
			</view>
			<view class="content">
				<textarea class="edit2" v-model="ainfo.content" :maxlength="1000"
					placeholder="美好的一天，写点什么吧..."></textarea>
			</view>
			<view class="agree">
				<text>还可以输入<text class="xy">{{ 1000 - ainfo.content.length }}</text>字</text>
			</view>

			<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/del.svg" @click="delIt(index)"></image>
				</view>
				<view class="image" @click="upload('list')" v-if="img_list.length < 9">
					<text class="txt">+</text>
				</view>
			</view>
			<view style="display:flex;flex-direction: column;height:200rpx;"></view>
		</view>



	</view>
</template>

<script>
import permission from '@/common/permission.js';
export default {
	components: {},
	data() {
		return {
			skey: '',
			uinfo: {},
			is_first: 0,
			pid: 0,
			sel: 0,
			pop_sel: false,
			cate: '',
			cid: 0,
			catename: '',
			img2: '',
			cateNames: [],
			cate_list: [],
			CateIndex: 0,
			nameList1: [],
			nameList2: [],
			content: '',
			cate: '',
			ainfo: {
				id: 0,
				title: '',
				content: '',
				name: '',
				telphone: '',
				address: '',
				contact: '',
				num: '',
			},
			TypeArray: ['请选择', '线下服务', '电话咨询', '远程服务', '视频咨询', '其他服务'],
			TypeIndex: 0,
			TypeArray2: ['请选择', '次', '天', '小时', '分钟', '周', '月', '年', '单', '份'],
			TypeIndex2: 0,
			img_list: [],
			img_list2: [],
			img_list1: [],
			visible: false,
			maskCloseAble: true,
			str: '',
			defaultValue: '',
			listData: [],
			cateTag: [],
			money: '',
			item_gz: -1,
			item_time: [],
			item_dx: [],
			is_top: false,
			is_agree: 0,
			selectedWork: {}
		}
	},

	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) {
			console.log(item, '收到修改的数据');

			this.selectedWork = item;
		},
		onManage() {
			// 处理管理按钮点击
			// uni.redirectTo({
			// 	url: '/pages/make/manageArticle'
			// })
			uni.navigateTo({
				url: '/pages/make/relatedWorks'
			})
		},
		onPublish() {
			this.onSubmit();
		},
		copyKd(item_data) {
			if (item_data != "") {
				uni.setClipboardData({
					data: item_data, // e是需要设置的内容
					success: function () {
						uni.showToast({
							title: '网址已复制',
							icon: 'none'
						})
					}
				})
			}
		},
		agreeChk() {
			if (this.is_agree == 0) {
				this.is_agree = 1;
			} else {
				this.is_agree = 0;
			}
		},
		showPicker() {
			this.pop_sel = true;
		},
		open() {
			this.visible = true
		},
		confirm(val) {
			console.log(val)
			this.defaultValue = val.code
			this.ainfo.city = val.desc
			this.visible = false
		},
		cancel() {
			this.visible = false
		},
		delIt(ind) {
			let arr = [];
			if (this.img_list.length > 0) {
				for (let i = 0; i < this.img_list.length; i++) {
					if (i == ind) { } else {
						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) => {
					console.log("====", res.data);
					this.ainfo = res.data.article;
					that.img_list1 = [];
					that.img_list = [];
					that.img_list2 = [];
					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) {
									that.img_list.push(arr[i]);
								}
							}
						}
					}

				}
			});


		},
		checkField(str, tips) {
			if (str.length < 2) {
				uni.showToast({
					title: tips,
					icon: 'none'
				});
				return false;
			}
			return true;
		},
		onSubmit() {
			console.log("skey", this.skey);

			// 校验标题
			if (this.checkField(this.ainfo.title, "请输入名称") == false) {
				return;
			}

			// 校验内容
			if (this.checkField(this.ainfo.content, "请输入具体内容") == false) {
				return;
			}

			// 校验是否正在提交
			if (this.is_submit > 0) {
				return;
			}

			// 校验图片数量和作品选择
			if (this.img_list.length < 1 && !this.selectedWork.id) {
				uni.showToast({
					title: '请上传 图片 或 选择一个作品',
					icon: 'none'
				});
				return;
			}else{
						// 校验图片字符串有效性（可选，因为已经检查了图片数量）
			if (!img_str || img_str.trim().length < 2) {
				uni.showToast({
					title: '请确保至少上传一张有效图片作为封面',
					icon: 'none'
				});
				return;
			}
			// 校验图片数量不超过 5 张
			if (this.img_list.length > 5) {
				uni.showToast({
					title: '最多只能上传 5 张图片',
					icon: 'none'
				});
				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] + "|";
				}
			}

		
			let that = this;
			this.is_submit = 1;
			uni.request({
				url: this.$apiHost + '/Article/add',
				data: {
					uuid: getApp().globalData.uuid,
					id: this.ainfo.id,
					title: this.ainfo.title,
					content: this.ainfo.content,
					img_list: img_str,
					work_id: this.selectedWork.id

				},
				//data: formdata,   // 这里传入你的参数(json格式)
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'sign': getApp().globalData.headerSign
				},
				dataType: 'json',
				success: (res) => {
					console.log("---", res.data);
					uni.showToast({
						title: res.data.str,
						icon: 'none'
					});
					if (res.data.success == "yes") {
						// if (that.ainfo.id > 0) {
						console.log(1);

						setTimeout(function () {
							uni.$emit('switchToMyPage', { type: 'article' });
							uni.switchTab({ url: '/pages/my/my' })
						}, 500);
						// } else {
						console.log(2);

						that.ainfo.title = '';
						that.ainfo.content = '';
						that.ainfo.num = '';
						that.img_list = [];
						// }
					} else { }
					this.is_submit = 0;

				},
				fail: (err) => {
					console.log('登录失败：', err);
					this.is_submit = 0;
				},
				complete: (com) => { }
			})
		},
		select(e) {
			console.log('选择文件：', e)
		},
		upload(type) {
			if (this.img_list.length >= 5) {
				uni.showToast({
					title: '最多只能上传5张图片',
					icon: 'none'
				});
				return
			}
			uni.showActionSheet({
				itemList: ['拍照', '从相册选择'],
				success: (res) => {
					const sourceType = res.tapIndex === 0 ? 'camera' : 'album';
					this.checkRights(sourceType);
				}
			});
		},
		async checkRights(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.upload2(type, sourceType);
			} catch (error) {
				console.error('权限检查失败：', error);
				uni.showToast({
					title: '权限检查失败',
					icon: 'none'
				});
			}
		},
		upload2(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);
									if (type == 'avatar') {
										_self.img2 = resdata.data.path;
									} else if (type == 'list') {
										_self.img_list.push(resdata.data.path)
										console.log('_self.img_list:', _self.img_list);
									} else if (type == 'list2') {
										_self.img_list2.push(resdata.data.path)
									} else if (type == 'list1') {
										_self.img_list1.push(resdata.data.path)
									}
								}
							},
							fail: function (uploadFileFail) {
								console.log('Error:', uploadFileFail.data);
							},
							complete: () => {
								console.log('Complete:');
							}
						});
					}
				},

				error: function (e) {

					console.log(e);

				}

			});


		},
		deleteWorkInfo() {
			this.selectedWork = {}

		}
	}
}
</script>

<style scoped lang="scss">
@import 'fabuArticle.scss';
</style>