<template>
	<ElDialog
		v-model="dialogVisible"
		title="创建视频会议"
		width="500px"
		:close-on-click-modal="false"
		@close="handleClose"
	>
		<ElForm
			ref="formRef"
			:model="formData"
			:rules="formRules"
			label-width="120px"
		>
			<ElFormItem label="会议名称" prop="meetingName">
				<ElInput
					v-model="formData.meetingName"
					placeholder="请输入会议名称"
					clearable
				/>
			</ElFormItem>

			<ElFormItem label="开始时间" prop="startTime" required>
				<ElDatePicker
					v-model="formData.startTime"
					type="datetime"
					placeholder="选择开始时间"
					format="YYYY-MM-DD HH:mm"
					value-format="YYYY-MM-DD HH:mm:ss"
					:disabled-date="disabledDate"
					style="width: 100%"
				/>
			</ElFormItem>

			<ElFormItem label="结束时间" prop="endTime" required>
				<ElDatePicker
					v-model="formData.endTime"
					type="datetime"
					placeholder="选择结束时间"
					format="YYYY-MM-DD HH:mm"
					value-format="YYYY-MM-DD HH:mm:ss"
					:disabled-date="disabledDate"
					style="width: 100%"
				/>
			</ElFormItem>

			<ElFormItem label="提前入会" prop="advance">
				<ElInputNumber
					v-model="formData.advance"
					:min="0"
					:max="60"
					placeholder="提前入会时间（分钟）"
					style="width: 100%"
				/>
				<div class="form-tip">用户可在会议开始前N分钟加入</div>
			</ElFormItem>

			<ElFormItem label="会议密码" prop="meetingPassword">
				<ElInput
					v-model="formData.meetingPassword"
					placeholder="可选，留空则无密码"
					clearable
					show-password
				/>
			</ElFormItem>

			<ElFormItem label="最大人数" prop="maxParticipants">
				<ElInputNumber
					v-model="formData.maxParticipants"
					:min="2"
					:max="100"
					placeholder="最大参与人数"
					style="width: 100%"
				/>
			</ElFormItem>
		</ElForm>

		<template #footer>
			<ElButton @click="handleClose">取消</ElButton>
			<ElButton type="primary" :loading="submitting" @click="handleSubmit">
				创建会议
			</ElButton>
		</template>
	</ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import {
	ElDialog,
	ElForm,
	ElFormItem,
	ElInput,
	ElInputNumber,
	ElDatePicker,
	ElButton,
	ElMessage,
	type FormInstance,
	type FormRules
} from 'element-plus'
import { workcaseChatAPI } from '@/api/workcase'
import type { CreateMeetingParam } from '@/types'

interface Props {
	modelValue: boolean
	roomId: string
	workcaseId: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
	'update:modelValue': [value: boolean]
	success: [meetingId: string]
}>()

const formRef = ref<FormInstance>()
const submitting = ref(false)

// 对话框显示状态
const dialogVisible = computed({
	get: () => props.modelValue,
	set: (val) => emit('update:modelValue', val)
})

// 表单数据
const formData = reactive<CreateMeetingParam>({
	roomId: props.roomId,
	workcaseId: props.workcaseId,
	meetingName: '',
	startTime: '',
	endTime: '',
	advance: 5,
	meetingPassword: '',
	maxParticipants: 10
})

// 表单验证规则
const formRules: FormRules = {
	meetingName: [
		{ max: 50, message: '会议名称不能超过50个字符', trigger: 'blur' }
	],
	startTime: [
		{ required: true, message: '请选择开始时间', trigger: 'change' }
	],
	endTime: [
		{ required: true, message: '请选择结束时间', trigger: 'change' },
		{
			validator: (rule, value, callback) => {
				if (value && formData.startTime) {
					const start = new Date(formData.startTime).getTime()
					const end = new Date(value).getTime()
					if (end <= start) {
						callback(new Error('结束时间必须晚于开始时间'))
					} else if (end - start < 5 * 60 * 1000) {
						callback(new Error('会议时长不能少于5分钟'))
					} else if (end - start > 24 * 60 * 60 * 1000) {
						callback(new Error('会议时长不能超过24小时'))
					} else {
						callback()
					}
				} else {
					callback()
				}
			},
			trigger: 'change'
		}
	],
	advance: [
		{ type: 'number', min: 0, max: 60, message: '提前入会时间范围为0-60分钟', trigger: 'blur' }
	],
	meetingPassword: [
		{ max: 20, message: '密码不能超过20个字符', trigger: 'blur' }
	],
	maxParticipants: [
		{ type: 'number', min: 2, max: 100, message: '参与人数范围为2-100人', trigger: 'blur' }
	]
}

// 禁用过去的日期
const disabledDate = (date: Date) => {
	return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 提交表单
const handleSubmit = async () => {
	if (!formRef.value) return

	try {
		// 验证表单
		await formRef.value.validate()

		submitting.value = true
		console.log(props.roomId)
		// 调用API创建会议
		const result = await workcaseChatAPI.createVideoMeeting({
			...formData,
			roomId: props.roomId,
			workcaseId: props.workcaseId
		})

		if (result.success && result.data) {
			ElMessage.success('会议创建成功')
			emit('success', result.data.meetingId!)
			handleClose()
		} else {
			ElMessage.error(result.message || '创建会议失败')
		}
	} catch (error) {
		console.error('创建会议失败:', error)
		if (error instanceof Error && error.message !== 'Validation failed') {
			ElMessage.error('创建会议失败，请重试')
		}
	} finally {
		submitting.value = false
	}
}

// 关闭对话框
const handleClose = () => {
	// 重置表单
	formRef.value?.resetFields()
	formData.meetingName = ''
	formData.startTime = ''
	formData.endTime = ''
	formData.advance = 5
	formData.meetingPassword = ''
	formData.maxParticipants = 10

	dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.form-tip {
	font-size: 12px;
	color: #909399;
	margin-top: 4px;
}
</style>
