<template>
	<view class="content">
		<!-- 所属组织区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				所属组织
			</view>
			<picker :range="orgRange" range-key="name" @change="changeOrg">
				<view class="box_input">
					<view class="picker" :class="{ pick: form.orgName }">{{ form.orgName ? form.orgName : '请选择所属组织' }}</view>
					<uni-icons type="down" size="24" color="#A6A6A6"></uni-icons>
				</view>
			</picker>
		</view>

		<!-- 活动主题区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				活动主题
			</view>
			<view class="box_input">
				<input class="input" placeholder-style="color:#A6A6A6" placeholder="请输入活动主题" v-model="form.theme" />
			</view>
		</view>

		<!--活动详情区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				活动详情
			</view>

			<view class="box_richtext">
				<!-- 富文本输入框区域 -->
				<editor class="editor" placeholder="请输入活动详情" @ready="handleReady" @focus="handleFocus" @blur="handleBlur" @statuschange="handleStatusChange"></editor>

				<view class="tools" v-if="showTool">
					<!-- 大标题图标 -->
					<uni-icons :color="isTitle ? '#5278fb' : ''" fontFamily="CustomFont" :size="26" @click="handleTitle">&#xe609;</uni-icons>

					<!-- 加粗图标 -->
					<uni-icons :color="isBold ? '#5278fb' : ''" fontFamily="CustomFont" :size="26" @click="handleBold">&#xec83;</uni-icons>

					<!-- 倾斜图标 -->
					<uni-icons :color="isIncline ? '#5278fb' : ''" fontFamily="CustomFont" :size="26" @click="handleIncline">&#xe852;</uni-icons>

					<!-- 横线图标 -->
					<uni-icons fontFamily="CustomFont" :size="26" @click="handleRowLine">&#xe60a;</uni-icons>

					<!-- 图片图标 -->
					<uni-icons fontFamily="CustomFont" :size="26" @click="handleImage">&#xe8ba;</uni-icons>

					<!-- 确认图标 -->
					<uni-icons fontFamily="CustomFont" :size="26" @click="handleFinish">&#xe622;</uni-icons>
				</view>
			</view>
		</view>

		<!-- 活动开始时间区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				活动开始时间
			</view>
			<uni-datetime-picker type="datetime" v-model="form.startTime" placeholder="请选择活动开始时间" :start="dayjs(Date.now()).format('YYYY-MM-DD')" />
		</view>

		<!-- 活动结束时间区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				活动结束时间
			</view>
			<uni-datetime-picker type="datetime" v-model="form.endTime" placeholder="请选择活动结束时间" :start="dayjs(Date.now()).format('YYYY-MM-DD')" />
		</view>

		<!-- 活动地址区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				活动地址
			</view>
			<view class="box_input" @click="clickAddress">
				<view class="picker" :class="{ pick: form.address }">{{ form.address ? form.address : '请选择活动地址' }}</view>
				<uni-icons type="down" size="24" color="#A6A6A6"></uni-icons>
			</view>
		</view>

		<!-- 参与说明区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				参与说明
			</view>
			<view class="box_textarea">
				<textarea class="textarea" :maxlength="300" placeholder="请输入参与说明,最多300字" @blur="inputDesc"></textarea>
			</view>
		</view>

		<!-- 报名开始时间区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				报名开始时间
			</view>
			<uni-datetime-picker type="datetime" v-model="form.signsTime" placeholder="请选择报名开始时间" :start="dayjs(Date.now()).format('YYYY-MM-DD')" />
		</view>

		<!-- 报名结束时间区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				报名结束时间
			</view>
			<uni-datetime-picker type="datetime" v-model="form.signeTime" placeholder="请选择报名结束时间" :start="dayjs(Date.now()).format('YYYY-MM-DD')" />
		</view>

		<!-- 报名总人数区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				报名总人数
			</view>
			<view class="box_input">
				<input class="input" placeholder-style="color:#A6A6A6" placeholder="请输入报名总人数,0为不设限" v-model="form.totalNumber" />
			</view>
		</view>

		<!-- 报名范围区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				报名范围
			</view>
			<picker :range="addressList" @change="changeRange">
				<view class="box_input">
					<view class="picker" :class="{ pick: form.addressRange }">{{ form.addressRange ? form.addressRange : '请选择报名范围' }}</view>
					<uni-icons type="down" size="24" color="#A6A6A6"></uni-icons>
				</view>
			</picker>
		</view>

		<!-- 咨询方式区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				咨询方式
			</view>
			<view class="box_input">
				<input class="input" placeholder-style="color:#A6A6A6" placeholder="请输入咨询方式" v-model="form.phone" />
			</view>
		</view>

		<!-- 活动相册区域 -->
		<view class="box">
			<view class="box_title">
				<text class="text">*</text>
				活动相册
			</view>
			<switch :checked="form.showPhoto" @change="switchChange" />
		</view>

		<view class="btn" @click="handleSubmit">提交</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getClubPage, getInsertActivity } from '@/api/index.js'
import { uploadImage } from '@/api/uploadImage.js'
import dayjs from 'dayjs'
// #ifdef H5
import quill from 'quill'
window.Quill = quill
// #endif

// 组织数组
const orgRange = ref([])

// 报名范围数组
const addressList = ['全部', '组织成员']

// 富文本编辑器实例
const editorCtx = ref()

// 富文本工具栏显示隐藏控制
const showTool = ref(false)

// 是否为大标题
const isTitle = ref(false)

// 是否加粗
const isBold = ref(false)

// 是否倾斜
const isIncline = ref(false)

// 提交数据
const form = ref({
	// 所属组织
	orgName: '',
	// 所属组织ID
	orgId: '',
	// 活动主题
	theme: '',
	// 活动详情
	themeDetail: '',
	// 活动开始时间
	startTime: '',
	// 活动结束时间
	endTime: '',
	// 活动地址
	address: '',
	// 纬度
	lat: '',
	// 经度
	lng: '',
	// 参与说明
	describes: '',
	// 报名开始时间
	signsTime: '',
	// 报名结束时间
	signeTime: '',
	// 报名总人数
	totalNumber: '',
	// 报名范围
	addressRange: '',
	// 组织成员：1 全部：2
	scope: '',
	// 咨询方式
	phone: '',
	// 活动相册
	showPhoto: false,
	// 是否可上传照片 是：1 否：2
	isImage: 2
})

onMounted(() => {
	// 获取组织分页下拉数据
	getOrgList()
})

// 获取组织分页下拉数据
const getOrgList = async () => {
	let data = {
		currentPage: 1,
		pageCount: 100
	}
	const res = await getClubPage(data)
	// console.log(res)
	orgRange.value = res.data.list
}

// 选择所属组织时触发的回调
const changeOrg = (e) => {
	// console.log(e.detail.value)
	let index = e.detail.value
	form.value.orgName = orgRange.value[index].name
	form.value.orgId = orgRange.value[index].id
	// console.log(form.value)
}

// 富文本编辑器初始化完成时触发
const handleReady = () => {
	uni.createSelectorQuery()
		.select('.editor')
		.context((res) => {
			// 获取富文本编辑器实例
			editorCtx.value = res.context
		})
		.exec()
}

// 富文本编辑器聚焦时触发
const handleFocus = () => {
	showTool.value = true
}

// 富文本编辑器失焦时触发
const handleBlur = () => {
	// showTool.value = false
	editorCtx.value.getContents({
		success: (res) => {
			// console.log(res)
			if (res.html.trim() == '<p><br></p>') {
				uni.showToast({
					title: '活动详情不能为空',
					icon: 'none'
				})
				return
			} else {
				// getImgSrc(res.html)
				form.value.themeDetail = res.html
				// console.log(form.value)
			}
		}
	})
}

// 改变编辑器内样式时触发
const handleStatusChange = (e) => {
	// console.log(e.detail)
	let detail = e.detail
	checkStatus(detail, 'header')
	checkStatus(detail, 'bold')
	checkStatus(detail, 'italic')
}

// 校验工具栏是否应该高亮
const checkStatus = (detail, name) => {
	if (detail.hasOwnProperty(name)) {
		if (name == 'header') {
			isTitle.value = true
		}
		if (name == 'bold') {
			isBold.value = true
		}
		if (name == 'italic') {
			isIncline.value = true
		}
	} else {
		if (name == 'header') {
			isTitle.value = false
		}
		if (name == 'bold') {
			isBold.value = false
		}
		if (name == 'italic') {
			isIncline.value = false
		}
	}
}

// 点击大标题图标回调
const handleTitle = () => {
	isTitle.value = !isTitle.value
	editorCtx.value.format('header', isTitle.value ? 'h2' : '')
}

// 点击加粗图标回调
const handleBold = () => {
	isBold.value = !isBold.value
	editorCtx.value.format('bold')
}

// 点击倾斜图标回调
const handleIncline = () => {
	isIncline.value = !isIncline.value
	editorCtx.value.format('italic')
}

// 点击横线图标回调
const handleRowLine = () => {
	editorCtx.value.insertDivider()
}

// 点击图片图标回调
const handleImage = () => {
	uni.chooseImage({
		success: async (res) => {
			// console.log(res)

			uni.showLoading({
				title: '上传中...',
				mask: true
			})

			for (let item of res.tempFilePaths) {
				let temp = await uploadImage(item)
				let result = JSON.parse(temp.data)
				// console.log(result)

				if (result.code == 200) {
					// 编辑器插入图片
					editorCtx.value.insertImage({
						src: result.data.fileUrl
					})
				}
			}
			uni.hideLoading()
		}
	})
}

// 点击确认图标回调
const handleFinish = () => {
	showTool.value = false
	editorCtx.value.getContents({
		success: (res) => {
			// console.log(res)
			if (res.html.trim() == '<p><br></p>') {
				uni.showToast({
					title: '活动详情不能为空',
					icon: 'none'
				})
				return
			} else {
				// getImgSrc(res.html)
				form.value.themeDetail = res.html
				// console.log(form.value)
			}
		}
	})
}

// 点击选择地址回调
const clickAddress = () => {
	uni.chooseLocation({
		success: (res) => {
			// console.log(res)
			form.value.address = res.address
			form.value.lat = res.latitude
			form.value.lng = res.longitude
			// console.log(form.value)
		},
		fail: (err) => {
			console.log(err)
		}
	})
}

// 参与说明输入框失去焦点回调
const inputDesc = (e) => {
	// console.log(e)
	form.value.describes = e.detail.value
	// console.log(form.value)
}

// 选择报名范围时的回调
const changeRange = (e) => {
	let index = e.detail.value
	form.value.addressRange = addressList[index]
	form.value.scope = index == 0 ? 2 : 1
	// console.log(form.value)
}

// 活动相册切换回调
const switchChange = (e) => {
	// console.log(e)
	form.value.showPhoto = e.detail.value
	form.value.isImage = form.value.showPhoto ? 1 : 2
	// console.log(form.value)
}

// 提交按钮回调
const handleSubmit = () => {
	// 校验提交值是否为空
	let flag = checkValue()

	if (!flag) {
		uni.showModal({
			title: '提示',
			content: '确定提交吗？',
			success: (res) => {
				if (res.confirm) {
					submitReq()
				}
			}
		})
	}
}

// 提交请求
const submitReq = async () => {
	const res = await getInsertActivity(form.value)
	uni.showToast({
		title: res.message,
		icon: 'success',
		mask: true
	})
	setTimeout(() => {
		uni.reLaunch({
			url: '/pages/activity/activity'
		})
	}, 1500)
}

// 校验提交值是否为空
const checkValue = () => {
	let keyList = Object.keys(form.value)

	// 提示信息
	keyList.forEach((ele) => {
		// console.log(ele)
		if (ele == 'phone') {
			let regPhone = /^1[3-9]\d{9}$/

			if (!regPhone.test(form.value[ele])) {
				uni.showToast({
					title: `手机号码格式有误`,
					icon: 'none'
				})

				// 符合条件时强制打断循环
				keyList.length = 0
			}
		}
		if (form.value[ele] === '') {
			uni.showToast({
				title: `${mapValue(ele)}不能为空`,
				icon: 'none'
			})

			// 符合条件时强制打断循环
			keyList.length = 0
		}
	})

	// 判断是否是空值 true 为有空值
	let t = keyList.every((ele) => form.value[ele] === '')
	return t
}

// 映射
const mapValue = (v) => {
	let msg = ''
	switch (v) {
		case 'orgName':
		case 'orgId':
			msg = '所属组织'

			break

		case 'theme':
			msg = '活动主题'

			break

		case 'themeDetail':
			msg = '活动详情'

			break

		case 'startTime':
			msg = '活动开始时间'

			break

		case 'endTime':
			msg = '活动结束时间'

			break

		case 'address':
		case 'lat':
		case 'lng':
			msg = '活动地址'

			break

		case 'describes':
			msg = '参与说明'

			break

		case 'signsTime':
			msg = '报名开始时间'

			break

		case 'signeTime':
			msg = '报名结束时间'

			break

		case 'totalNumber':
			msg = '报名总人数'

			break

		case 'addressRange':
		case 'scope':
			msg = '报名范围'

			break

		case 'phone':
			msg = '咨询方式'

			break

		default:
			msg = '内容'
			break
	}

	return msg
}
</script>

<style lang="scss" scoped>
.content {
	.box {
		margin-bottom: 15rpx;
		font-size: 28rpx;

		.box_title {
			display: flex;
			margin-bottom: 15rpx;

			.text {
				color: #d43030;
			}
		}

		.box_input {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 22rpx;
			width: 710rpx;
			height: 80rpx;
			border-radius: 6rpx;
			background-color: #f5f5f5;

			.input {
				width: 100%;
				height: 100%;
				font-size: 28rpx;
			}

			.picker {
				color: #a6a6a6;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			.pick {
				color: #000;
			}
		}

		.box_textarea {
			width: 710rpx;
			height: 308rpx;
			border-radius: 6rpx;
			background-color: #f5f5f5;

			.textarea {
				box-sizing: border-box;
				padding: 10rpx;
				width: 100%;
				height: 100%;
				font-size: 28rpx;
			}
		}

		.box_richtext {
			position: relative;
			box-sizing: border-box;
			padding: 15rpx 20rpx;
			width: 710rpx;
			height: 400rpx;
			border-radius: 6rpx;
			border: 2rpx solid #e6e6e6;
			background-color: #f5f5f5;

			.editor {
				width: 100%;
				height: 302rpx;
				min-height: 302rpx;
			}

			.tools {
				position: absolute;
				left: 0;
				right: 0;
				bottom: 0;
				display: flex;
				justify-content: space-around;
				align-items: center;
				height: 80rpx;
			}
		}
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 95rpx 0;
		width: 710rpx;
		height: 80rpx;
		font-size: 28rpx;
		color: #fff;
		border-radius: 8rpx;
		background-color: #007aff;
	}
}

::v-deep {
	.uni-date-editor--x {
		background-color: #f5f5f5;
	}
	.uni-date-x {
		background-color: #f5f5f5;
	}
}
</style>
