<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" class="!w-50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
      :validate-on-rule-change="false"
    >
      <el-form-item label="活动名称" prop="activityTitle">
        <el-input v-model="formData.activityTitle" placeholder="请输入活动名称" class="!w-240px"/>
      </el-form-item>
			<el-form-item label="举办机构" prop="activityOrganizer">
        <el-input v-model="formData.activityOrganizer" placeholder="请输入举办机构名称" class="!w-240px"/>
      </el-form-item>
      <el-form-item label="开始时间" prop="activityStartDate">
        <el-date-picker v-model="formData.activityStartDate" :disabledDate="disabledDates" value-format="x" type="date" placeholder="请选择活动开始时间" class="!w-240px" />
      </el-form-item>
			<el-form-item label="结束时间" prop="activityEndDate">
        <el-date-picker v-model="formData.activityEndDate" :disabledDate="disabledEndDates" value-format="x" type="date" placeholder="请选择活动结束时间" class="!w-240px" />
      </el-form-item>
			<el-form-item label="投票频率" prop="votingRule.dateType">
				<el-radio-group v-model="formData.votingRule.dateType">
					<el-radio value="day">每天</el-radio>
					<el-radio value="month">每月</el-radio>
					<el-radio value="year">每年</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="指定频率内可投票数" prop="votingRule.num">
				<el-input-number v-model="formData.votingRule.num" :min="1" :step="1" />
			</el-form-item>
			<el-form-item label="活动图片" prop="headImg">
        <UploadImg v-model="formData.headImg" height="150px" width="150px" :fileSize="20" />
      </el-form-item>
			<el-form-item label="活动背景图" prop="activityContent.backgroundImg">
        <UploadImg v-model="formData.activityContent.backgroundImg" height="150px" width="150px" :fileSize="20" />
      </el-form-item>
      <el-form-item label="活动内容" prop="activityContent.content">
        <Editor v-model="formData.activityContent.content" height="150px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { VotingActivityApi } from '@/api/menduner/system/vote'

defineOptions({ name: 'VotingActivityForm' })
defineProps({
  area: Array,
  position: Array
})
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
	votingActivityId: undefined,
	activityTitle: undefined,
	activityStartDate: undefined,
	activityEndDate: undefined,
	activityContent: {
		backgroundImg: undefined,
		content: undefined
	},
	activityOrganizer: undefined,
	votingRule: {
		dateType: 'day', // 投票频率：day - 日，month - 月，year - 年
		num: 1 // 指定频率内最多投票次数
	},
	headImg: undefined
})

const formRules = reactive({
  activityTitle: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
  activityStartDate: [{ required: true, message: '活动开始时间', trigger: 'change' }],
  activityEndDate: [{ required: true, message: '活动结束时间', trigger: 'change' }],
  activityOrganizer: [{ required: true, message: '举办机构不能为空', trigger: 'blur' }],
  headImg: [{ required: true, message: '活动图片不能为空', trigger: 'change' }],
	'activityContent.backgroundImg': [{ required: true, message: '活动背景图不能为空', trigger: 'change' }],
	'activityContent.content': [{ required: true, message: '活动内容不能为空', trigger: 'blur' }],
	'votingRule.dateType': [{ required: true, message: '投票频率不能为空', trigger: 'change' }],
	'votingRule.num': [{ required: true, message: '投票频率不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

// 过去的日期不可选
const disabledDates = (date) => {
  const currentDate = new Date()
  currentDate.setDate(currentDate.getDate() - 1)
  return date.getTime() < currentDate.getTime()
}

// 根据选择的开始时间，结束时间不可选
const disabledEndDates = (date) => {
  const currentDate = new Date()
  currentDate.setDate(currentDate.getDate() - 1)

  const activityStartDate = formData.value.activityStartDate
  // 没有选择开始时间时默认过去的时间不可选
  if (!activityStartDate) {
    return date.getTime() < currentDate.getTime()
  }

  // 有开始时间则根据开始时间设置不可选范围
  const startDate = new Date(activityStartDate)
  startDate.setDate(startDate.getDate() + 1)
  return date.getTime() < startDate.getTime()
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await VotingActivityApi.getVotingActivity(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await VotingActivityApi.createVotingActivity(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await VotingActivityApi.updateVotingActivity(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
		votingActivityId: undefined,
		activityTitle: undefined,
		activityStartDate: undefined,
		activityEndDate: undefined,
		activityContent: {
			backgroundImg: undefined,
			content: undefined
		},
		activityOrganizer: undefined,
		votingRule: {
			dateType: 'day',
			num: 1
		},
		headImg: undefined
	}
  formRef.value?.resetFields()
}
</script>