<template>
	<view class="page_publish">
		<view class="publish_header">
			<uni-icons type="back" size="24" color="#333333" @click="goBack"></uni-icons>
			<text class="header_title">发布通知</text>
			<text class="header_placeholder"></text>
		</view>

		<scroll-view scroll-y class="publish_content">
			<view class="form_item">
				<view class="form_row form_row_type">
					<text class="form_label">通知类型</text>
					<view class="form_content">
						<picker mode="selector" :range="typeOptions" :value="typeIndex" @change="handleTypeChange">
							<view class="filter_item">
								<text class="filter_text" :class="{ placeholder: typeIndex === -1 }">{{
									formData.noticeType || '请选择类型' }}</text>
								<uni-icons type="down" size="16" color="#999999"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
			</view>

			<view class="form_item">
				<view class="form_row form_row_type">
					<text class="form_label">通知标题</text>
					<view class="form_content">
						<input type="text" class="form_input" v-model="formData.title" placeholder="请输入任务名称" />
					</view>
				</view>
			</view>

			<view class="form_item">
				<view class="form_row">
					<text class="form_label">通知内容</text>
					<view class="form_content">
						<view class="textarea_container">
							<textarea class="form_textarea" v-model="formData.content" placeholder="请输入通知内容"
								:maxlength="-1"></textarea>
							<!-- <view class="textarea_actions">
								<image src="/static/image/publish/full.png" class="full_icon" mode="aspectFit"></image>
								<text class="action_text">全屏编辑</text>
							</view> -->
						</view>
					</view>
				</view>
			</view>

			<view class="form_item">
				<view class="form_row">
					<text class="form_label">发布时间</text>
					<view class="form_content">
						<custom-radio v-model="publishType" :options="publishOptions" />
						<view v-if="publishType === 1" class="time_picker">
							<uni-datetime-picker v-model="publishDateTime" type="datetime" :start="startTime"
								:end="endTime" return-type="string" />
						</view>
					</view>
				</view>
			</view>

			<view class="form_item">
				<view class="form_row">
					<text class="form_label">通知对象</text>
					<view class="form_content">
						<view class="object_row">
							<view class="object_info">
								<text class="object_count">{{ objectTypeLabel || '请选择' }}</text>
								<text class="object_count">已选{{ selectedCount }}人</text>
							</view>
							<view class="object_action" @click="selectObject">
								<text class="action_text">选择通知对象</text>
								<text class="action_arrow">></text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="form_item" v-if="isEdit">
				<view class="form_row">
					<text class="form_label">通知状态</text>
					<view class="form_content">
						<view class="switch_row">
							<view class="switch_container">
								<switch :checked="formData.status" color="#2E64FA" @change="onStatusChange" />
							</view>
							<text class="switch_text">说明：关闭后通知不对通知对象显示</text>
						</view>
					</view>
				</view>
			</view>

			<view class="form_item" v-if="isEdit && formData.status">
				<view class="form_row">
					<text class="form_label">已读记录</text>
					<view class="form_content">
						<custom-radio v-model="saveRecord" :options="recordOptions" />
						<text class="record_tip">说明：{{ saveRecord === 0 ? '已读记录将被保留' : '已读记录将被清空，重新记录' }}</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="publish_footer">
			<view class="confirm_btn" @click="handleSave">
				<text class="btn_text">确定</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
import uniDatetimePicker from '@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue';
import overviewApi from '@/reqApi/overview.js';
import CustomRadio from '@/components/customRadio.vue';

const showTypePicker = ref(false);
const publishType = ref(0);
const isEdit = ref(false);
const saveRecord = ref(0);
const typeIndex = ref(-1);
const typeData = ref([]);
const typeOptions = ref([]);

const getCurrentDateTime = () => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	const hours = String(now.getHours()).padStart(2, '0');
	const minutes = String(now.getMinutes()).padStart(2, '0');
	const seconds = String(now.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const publishDateTime = ref(getCurrentDateTime());
const startTime = ref('2024-01-01 00:00:00');
const endTime = ref('2030-12-31 23:59:59');

const publishOptions = [
	{ label: '立即发布', value: 0 },
	{ label: '预约发布', value: 1 }
];

const recordOptions = [
	{ label: '保存', value: 0 },
	{ label: '不保存', value: 1 }
];

const formData = reactive({
	title: '',
	noticeType: '',
	content: '',
	status: true
});

const selectedCount = ref(0);
const selectedUsers = ref([]);
const schoolYearId = ref('');
const noticeTypeId = ref('');
const objectTypeLabel = ref('');
const editId = ref('');
const originalNoticeType = ref(0);

const fetchNoticeTypeList = async () => {
	try {
		const res = await overviewApi.noticeTypeList();
		if (res.data && Array.isArray(res.data)) {
			typeData.value = res.data.map(item => ({
				id: item.id,
				name: item.name
			}));
			typeOptions.value = typeData.value.map(item => item.name);
		}
	} catch (error) {
		console.error('获取通知类型失败:', error);
	}
};

onMounted(() => {
	fetchNoticeTypeList();
	
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	if (currentPage.options && currentPage.options.id) {
		isEdit.value = true;
		editId.value = currentPage.options.id;
		fetchNoticeDetail(currentPage.options.id);
	}
});

const fetchNoticeDetail = async (id) => {
	try {
		const res = await overviewApi.notices_edit({ id });
		if (res.data) {
			const data = res.data;
				formData.title = data.noticeName || '';
			const content = data.noticeContent || '';
			formData.content = content.replace(/<[^>]+>/g, '');
			formData.status = data.isClose !== true;
			noticeTypeId.value = data.typeId || '';
			
			const typeIndexVal = typeData.value.findIndex(item => item.id === data.typeId);
			typeIndex.value = typeIndexVal >= 0 ? typeIndexVal : -1;
			
			publishType.value = data.sendTimeType === 2 ? 1 : 0;
			publishDateTime.value = data.releaseTime || getCurrentDateTime();
			
			saveRecord.value = data.isSave === true ? 0 : 1;
			
			if (data.noticeType) {
				const typeMap = {
					1: '按部门',
					2: '按学科',
					3: '按年级',
					4: '按权限',
					5: '按学生'
				};
				objectTypeLabel.value = typeMap[data.noticeType] || '';
				originalNoticeType.value = data.noticeType;
			}
			
			if (data.userList && Array.isArray(data.userList)) {
				selectedUsers.value = data.userList.map(user => ({
					id: user.userId,
					name: user.thirdName
				}));
				selectedCount.value = selectedUsers.value.length;
			}
		}
	} catch (error) {
		console.error('获取通知详情失败:', error);
	}
};

onShow(() => {
	const result = uni.getStorageSync('selectObjectResult');
	if (result) {
		try {
			const data = JSON.parse(result);
			if (data) {
				objectTypeLabel.value = data.tab;
				selectedCount.value = data.count;
				selectedUsers.value = data.users;
			}
		} catch (e) {
			console.error('解析选择结果失败:', e);
		}
		uni.removeStorageSync('selectObjectResult');
	}
});

const handleTypeChange = (e) => {
	typeIndex.value = e.detail.value;
	const selectedItem = typeData.value[typeIndex.value];
	if (selectedItem) {
		formData.noticeType = selectedItem.name;
		noticeTypeId.value = selectedItem.id;
	}
};

const goBack = () => {
	uni.redirectTo({ url: '/pages/notice/overview/index' });
};

const onStatusChange = (e) => {
	formData.status = e.detail.value;
	if (formData.status) {
		saveRecord.value = 0;
	}
};

const selectObject = () => {
	const lastSelection = {
		tab: objectTypeLabel.value,
		users: selectedUsers.value,
		noticeType: originalNoticeType.value || getNoticeTypeValue(objectTypeLabel.value),
		isEdit: isEdit.value
	};
	uni.setStorageSync('selectObjectLastSelection', JSON.stringify(lastSelection));
	uni.navigateTo({ url: '/pages/notice/publish/selectObject' });
};

const handleObjectSelect = (data) => {
	if (data) {
		objectTypeLabel.value = data.tab;
		selectedCount.value = data.count;
		selectedUsers.value = data.users;
	}
};

const getCurrentTime = () => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	const hours = String(now.getHours()).padStart(2, '0');
	const minutes = String(now.getMinutes()).padStart(2, '0');
	const seconds = String(now.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const getNoticeTypeValue = (tab) => {
	const map = {
		'按部门': 1,
		'按学科': 2,
		'按年级': 3,
		'按权限': 4,
		'按学生': 5
	};
	return map[tab] || 1;
};

const handleSave = async () => {
	if (!formData.title) {
		uni.showToast({ title: '请输入通知标题', icon: 'none' });
		return;
	}
	if (!formData.content) {
		uni.showToast({ title: '请输入通知内容', icon: 'none' });
		return;
	}
	if (!objectTypeLabel.value) {
		uni.showToast({ title: '请选择通知对象', icon: 'none' });
		return;
	}
	if (selectedUsers.value.length === 0) {
		uni.showToast({ title: '请选择通知人员', icon: 'none' });
		return;
	}
	
	if (!schoolYearId.value) {
		try {
			const res = await overviewApi.findSchoolYear();
			if (res.data && res.data.length > 0) {
				schoolYearId.value = res.data[0].id;
			}
		} catch (error) {
			console.error('获取学年失败:', error);
			uni.showToast({ title: '获取学年信息失败', icon: 'none' });
			return;
		}
	}
	
	uni.showLoading({ title: '发布中...' });
	
	try {
		const objectType = getNoticeTypeValue(objectTypeLabel.value);
		const params = {
			typeId: noticeTypeId.value || '',
			noticeName: formData.title,
			noticeContent: btoa(unescape(encodeURIComponent(formData.content))),
			sendTimeType: publishType.value + 1,
			releaseTime: publishType.value === 0 ? getCurrentTime() : publishDateTime.value,
			noticeType: objectType,
			isClose: isEdit.value ? !formData.status : false,
			isSave: isEdit.value ? (saveRecord.value === 0) : false,
			fileList: []
		};
		
		if (isEdit.value && editId.value) {
			params.id = editId.value;
		}
		
		const userList = selectedUsers.value.map(user => {
			const userInfo = {
				userType: objectType === 5 ? 2 : 1,
				userId: user.id,
				thirdName: user.name.split('(')[0].trim(),
				thirdCode: user.name.match(/\((.*?)\)/)?.[1] || ''
				
			};
			return userInfo;
		});
		
		if (userList.length > 0) {
			params.userList = userList;
		}
		
		const res = await overviewApi.save_notices(params);
		if (res.code === 200) {
			uni.showToast({ title: '发布成功', icon: 'success' });
			setTimeout(() => {
				uni.redirectTo({ url: '/pages/notice/overview/index' });
			}, 1500);
		} else {
			uni.showToast({ title: res.message || '发布失败', icon: 'none' });
		}
	} catch (error) {
		console.error('发布失败:', error);
		uni.showToast({ title: '发布失败', icon: 'none' });
	} finally {
		uni.hideLoading();
	}
};
</script>

<style lang="scss" scoped>
.page_publish {
	// min-height: 100vh;
	// background-color: #F5F5F5;
	display: flex;
	flex-direction: column;
}

.publish_header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 96rpx;
	padding: 0 24rpx;
	background-color: #FFFFFF;
	border-bottom: 2rpx solid #F3F3F3;

	.header_title {
		font-weight: 500;
		font-size: 32rpx;
		color: #333333;
	}

	.header_placeholder {
		width: 48rpx;
	}
}

.publish_content {
	flex: 1;
	box-sizing: border-box;
	padding: 120rpx 24rpx 158rpx 24rpx;
}

.form_item {
	background-color: #FFFFFF;
	border-radius: 8rpx;
	padding-bottom: 24rpx;
	margin-bottom: 24rpx;
	border-bottom: 2rpx solid #F3F3F3;
	&:last-child {
		border-bottom: none;
	}
	.form_label {
		font-size: 28rpx;
		color: #666666;
		font-weight: 400;
		white-space: nowrap;
		flex-shrink: 0;
		margin-right: 16rpx;

		&::after {
			content: ':';
			margin-left: 8rpx;
		}
	}

	// 通知类型
	.form_row {
		display: flex;
		align-items: flex-start;

		.form_content {
			flex: 1;
		}
	}

	.form_row_type {
		align-items: center;

		.filter_item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 16rpx;
			height: 72rpx;
			line-height: 72rpx;
			background-color: #FFFFFF;
			border-radius: 8rpx;
			width: 240rpx;
			border: 2rpx solid #DCDFE6;

			.filter_text {
				font-size: 28rpx;
				color: #333333;
				margin-right: 8rpx;

				&.placeholder {
					color: #909399;
				}
			}
		}
	}

	.form_input {
		font-size: 28rpx;
		color: #333333;
		padding: 0 24rpx;
		background-color: #FFFFFF;
		border-radius: 8rpx;
		width: 100%;
		height: 72rpx;
		box-sizing: border-box;
		border: 2rpx solid #E9E9E9;
	}

	.form_select {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16rpx;
		background-color: #F5F7FA;
		border-radius: 8rpx;
		border: 2rpx solid #DCDFE6;

		.select_text {
			font-size: 28rpx;
			color: #333333;
		}

		.select_right {
			.select_arrow {
				font-size: 28rpx;
				color: #999999;
			}
		}
	}

	.textarea_container {
		position: relative;

		.form_textarea {
			width: 100%;
			height: 240rpx;
			font-size: 28rpx;
			color: #333333;
			line-height: 1.6;
			padding: 14rpx 24rpx 56rpx 24rpx;
			background-color: #FFFFFF;
			border-radius: 8rpx;
			box-sizing: border-box;
			border: 2rpx solid #E9E9E9;
		}

		.textarea_actions {
			position: absolute;
			bottom: 13rpx;
			right: 16rpx;
			display: flex;
			align-items: center;
			gap: 8rpx;

			.full_icon {
				width: 28rpx;
				height: 28rpx;
			}

			.action_text {
				font-weight: 400;
				font-size: 28rpx;
				color: #2E64FA;
			}
		}
	}

	.time_picker {
		margin-top: 20rpx;
		min-width: 300rpx;
		height: 68rpx;
		float: right;

		:deep(.uni-date-x--border) {
			height: 68rpx;
		}

		:deep(.uni-date-x) {
			padding: 0 16rpx;	
			height: 48rpx;
		}

		:deep(.uni-date-x--text) {
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
		}

		:deep(.uni-date__x-input) {
			font-size: 28rpx;
			color: #333333;

		}
	}

	.object_row {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.object_info {
			display: flex;
			align-items: center;
			gap: 12rpx;

			.object_count {
				font-size: 28rpx;
				color: #2E64FA;
			}
		}

		.object_action {
			display: flex;
			align-items: center;
			gap: 8rpx;

			.action_text {
				font-size: 28rpx;
				color: #2E64FA;
			}

			.action_arrow {
				font-size: 28rpx;
				color: #2E64FA;
			}
		}
	}

	.object_tip {
		font-size: 24rpx;
		color: #F56C6C;
		margin-top: 12rpx;
		display: block;
	}

	.switch_row {
		display: flex;
		flex-direction:column;
		// gap: 16rpx;

		.switch_container {
			transform: scale(0.8);
			transform-origin: left center;
		}

		.switch_text {
			font-weight: 400;
			font-size: 28rpx;
			color: #999999;
		}
	}

	.record_tip {
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		margin-top: 16rpx;
		display: block;
	}
}

.publish_footer {
	padding: 24rpx;
	padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
	background-color: #FFFFFF;

	.confirm_btn {
		width: 702rpx;
		height: 90rpx;
		background: #2E64FA;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		text-align: center;
		line-height: 90rpx;
		.btn_text {
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
		}
	}
}
</style>