<template>
	<view class="detail-page-container">
		<view class="topic-list-box" v-if="topicList.length > 0">
			<view class="topic-box-common" v-for="(item,index) in topicList" @click="handleDeleteTopic(index)">
				# {{item.name}}
			</view>
		</view>
		<view class="publish-box">
			<textarea class="textarea" v-model="form.content" placeholder="分享有趣事~" placeholder-class="placeholder-class"
				@focus="handleFocus" />
			<image-upload v-model="form.attachments" ref="uploadRef" :limit="9" :showEmjo="showEmjo" :showIcons="true"
				@componentsType="handleSetComponentsType" @handleTopic="handleOpenTopicSelection"
				@handleEmjo="handleAddEmjo"></image-upload>
		</view>
		<view class="permission-box">
			<view class="item">
				<view class="text">允许评论</view>
				<switch color="#00E165" @change="(val)=>handleChange(val,'isEnableComment')"
					:checked="form.isEnableComment==1" />
			</view>
			<view class="item">
				<view class="text">开启评论精选</view>
				<switch color="#00E165" @change="(val)=>handleChange(val,'isEnableFeaturedComment')"
					:checked="form.isEnableFeaturedComment==1" />
			</view>
			<view class="item">
				<view class="text">开启PK</view>
				<switch color="#00E165" @change="(val)=>handleChange(val,'isEnableVote')"
					:checked="form.isEnableVote==1" />
			</view>
		</view>

		<!-- pk数据编辑 -->
		<view class="pk-edit-box" v-if="form.isEnableVote==1">
			<view class="textarea-box">
				<textarea class="textarea" v-model="form.voteTitle" maxlength="50" placeholder="请输入PK标题~（0/50）"
					placeholder-class="placeholder-class" />
			</view>
			<view class="pk-type-box">
				<radio-group v-model="form.voteOptionType" @change="radioChange">
					<label class="radio" style="margin-right: 40rpx;">
						<radio value="TEXT" :checked="form.voteOptionType=='TEXT'" />文字PK
					</label>
					<label class="radio">
						<radio value="IMAGE" :checked="form.voteOptionType=='IMAGE'" />图片PK
					</label>
				</radio-group>

				<view class="choice-box" v-if="form.voteOptionType=='IMAGE'">
					<view class="choice-item">
						<image-upload v-model="voteOptionsAffirmative" :limit="1" :width="120" :height="120"
							:showIcons="false"></image-upload>
						<input class="text" maxlength="16" v-model="form.voteOptions[0].name"
							placeholder="请输入选项1（16字以内）" />
					</view>
					<view class="choice-item">
						<image-upload v-model="voteOptionsOpposing" :limit="1" :width="120" :height="120"
							:showIcons="false"></image-upload>
						<input class="text" maxlength="16" v-model="form.voteOptions[1].name"
							placeholder="请输入选项2（16字以内）" />
					</view>
				</view>
				<view class="choice-box" v-if="form.voteOptionType=='TEXT'">
					<view class="choice-item text-item">
						<view class="label">选项1</view>
						<input class="text" maxlength="16" v-model="form.voteOptions[0].name"
							placeholder="请输入选项1（16字以内）" />
					</view>
					<view class="choice-item text-item">
						<view class="label">选项2</view>
						<input class="text" maxlength="16" v-model="form.voteOptions[1].name"
							placeholder="请输入选项2（16字以内）" />
					</view>
				</view>
			</view>
		</view>


		<!-- 提交按钮 -->
		<view class="submit-btn" @click="handleSubmit">确定</view>

		<!-- 选择话题弹窗 -->
		<view class="topic-selection-shadow" v-if="showTopicSelection">
			<view class="topic-selection-container">
				<view class="title-box">
					<view class="label">选择话题</view>
					<image src="/static/images/close-icon.png" class="close-icon" @click="handleCloseTopicSelection">
					</image>
				</view>
				<view class="topic-search-box">
					<view class="top-tag">#</view>
					<input v-model="topicParams.name" placeholder="请输入话题名称" class="input"
						placeholder-class="input-class" @keypress.enter="handleSearchTopic" />
				</view>
				<view class="topic-result-list">
					<template v-if="topicResultList&&topicResultList.length > 0">
						<view class="list-item" v-for="(item,index) in topicResultList" :key="index"
							@click="handleAddTopic(item)">
							<view class="circle-tag">#</view>
							<view class="result-text">{{item.name}}</view>
						</view>
					</template>
					<view class="list-item-none"
						v-if="topicResultList&&topicResultList.length == 0 && topicParams.name">
						<view class="list-item">
							<view class="circle-tag">#</view>
							<view class="result-text">{{topicParams.name}}</view>
						</view>
						<view class="create-text" @click="handleCreateTopic">创建此话题</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getTopicSelection,
		createNewTopic,
		crateNewDynamic
	} from '@/api/api.js';
	import ImageUpload from '@/components/ImageUpload.vue'
	import emotions from '@/utils/emjo';
	export default {
		data() {
			return {
				type: 'r1',
				showTopicSelection: false,
				topicParams: {
					pageSize: 10,
					pageNum: 1,
					name: ''
				},
				topicResultList: undefined,
				topicList: [],
				form: {
					content: '',
					type: 'TEXT',
					topicNames: [],
					topicIds: [],
					linkUrl: '',
					attachmentUrls: [],
					isEnableComment: 1,
					isEnableFeaturedComment: 0,
					isEnableVote: 0,
					voteTitle: '',
					voteOptionType: 'TEXT',
					voteOptions: [{
						name: '',
						imageUrl: ''
					}, {
						name: '',
						imageUrl: ''
					}],
				},
				voteOptionsAffirmative: [],
				voteOptionsOpposing: [],
				emotions,
				showEmjo: false
			}
		},
		components: {
			ImageUpload
		},
		onLoad(options) {
			let {
				topicId,
				topicName
			} = options;
			if (topicId) {
				this.topicList.push({
					name: topicName,
					id: topicId,

				})
			}
		},
		// 当内容变化时自动更新预览
		watch: {
			"form.content": {
				immediate: true,
				handler(val, oldVal) {
					if (val === oldVal) return;
					if (val && val.length < oldVal.length) {
						// 计算删除的字符长度（正常退格删1个，表情需要删N个）
						const deleteLen = oldVal.length - val.length;
						// 检查删除前的末尾是否是表情，且删除长度不够（比如表情是4个字符，只删了1个）
						const sortedEmojis = [...this.emotions].sort((a, b) => b.symbol.length - a.symbol.length);
						for (const emoji of sortedEmojis) {
							if (oldVal.endsWith(emoji.symbol) && deleteLen < emoji.symbol.length) {
								// 补删剩余的表情字符（比如表情4个字符，已删1个，再删3个）
								this.form.content = oldVal.slice(0, -emoji.symbol.length);
								break;
							}
						}
					}
				}
			}
		},
		methods: {
			// 允许评论，开启精选等操作
			handleChange(e, field) {
				console.log(e, field)
				this.form[field] = e.detail.value ? 1 : 0
			},
			// 图文PK或者文字PK
			radioChange(e) {
				console.log(e)
				this.form.voteOptionType = e.detail.value
			},
			handleSetComponentsType(type) {
				if (type && this.form.attachments && this.form.attachments.length > 0) {
					this.form.type = type
				} else {
					this.form.type = 'TEXT'
				}
			},
			// 发布动态
			handleSubmit() {
				if (this.topicList.length > 0) {
					this.form.topicNames = [];
					this.form.topicIds = [];
					this.topicList.forEach((item) => {
						this.form.topicNames.push(item.name);
						this.form.topicIds.push(item.id)
					})
				}
				// 开启PK校验
				if (this.form.isEnableVote == '1') {
					if (this.form.voteOptionType == 'IMAGE') {
						if (this.voteOptionsAffirmative.length == 0 || this.voteOptionsOpposing.length == 0) {
							uni.showToast({
								title: '请上传PK图片',
								icon: 'error'
							})
							return;
						}
					}
					if (this.form.voteOptionType == 'IMAGE') {
						this.$set(this.form.voteOptions[0], 'imageUrl', this.voteOptionsAffirmative[0].url);
						this.$set(this.form.voteOptions[1], 'imageUrl', this.voteOptionsOpposing[0].url);
					}
					if (!this.form.voteTitle) {
						uni.showToast({
							title: '请输入PK标题',
							icon: 'error'
						})
						return;
					}
					if (!this.form.voteOptions[0].name || !this.form.voteOptions[1].name) {
						uni.showToast({
							title: '请输入PK选项',
							icon: 'error'
						})
						return;
					}
				}
				crateNewDynamic(this.form).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '创建成功',
						})
						uni.$emit('hanldeDynamicRefresh')
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			},
			// 选择话题弹窗
			handleOpenTopicSelection() {
				this.showTopicSelection = true
			},
			// 关闭弹窗
			handleCloseTopicSelection() {
				this.showTopicSelection = false,
					this.topicResultList = undefined
				this.topicParams.name = ''
			},
			// 搜索话题
			handleSearchTopic() {
				getTopicSelection(this.topicParams).then(res => {
					console.log(res)
					this.topicResultList = res.rows
				})
			},
			// 创建话题
			handleCreateTopic() {
				let data = {
					name: this.topicParams.name
				}
				createNewTopic(data).then(res => {
					if (res.code == 200) {
						this.handleAddTopic(res.data);
					} else {
						uni.showToast({
							title: res.msg || '话题创建失败',
							icon: 'none'
						})
					}
				})
			},
			// 添加话题
			handleAddTopic(item) {
				this.topicList.push(item);
				// 关闭弹窗
				this.handleCloseTopicSelection();
			},
			// 删除话题
			handleDeleteTopic(index) {
				let _this = this;
				uni.showModal({
					title: '提示',
					content: '是否取消选择话题',
					success: function(res) {
						if (res.confirm) {
							_this.topicList.splice(index, 1)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			},
			// textarea聚焦时关闭表情窗口
			handleFocus() {
				this.$refs.uploadRef.closeEmjo()
			},
			// 添加表情
			handleAddEmjo(emotion) {
				console.log(emotion)
				this.form.content = this.form.content + emotion.symbol
			},
			// 删除表情
			deleteContent() {
				// 1. 处理 form.content 为空的情况，直接返回避免报错
				if (!this.form.content || this.form.content.trim() === '') {
					return;
				}
				let deleted = false;
				// 2. 按表情符号长度排序（长符号优先，避免短符号误匹配）
				const sortedEmojis = [...this.emotions].sort((a, b) => b.symbol.length - a.symbol.length);
				let lastIndex = -1;
				// 3. 检查内容是否以某个表情符号结尾，记录最后一个表情符号的位置
				for (const emoji of sortedEmojis) {
					if (this.form.content.endsWith(emoji.symbol)) {
						lastIndex = this.form.content.lastIndexOf(emoji.symbol);
						deleted = true;
					}
				}
				// 4. 若找到表情符号，删除所有匹配的表情符号
				if (deleted) {
					this.form.content = this.form.content.slice(0, lastIndex);
				} else {
					// 5. 若未匹配到表情，删除最后一个普通字符
					this.form.content = this.form.content.slice(0, -1);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/styles/publish.scss';

	.topic-list-box {
		display: flex;
		min-height: 120rpx;
		background-color: white;
		padding: 34rpx 34rpx 0 34rpx;
		box-sizing: border-box;
		flex-wrap: wrap;

	}
</style>