<template>
  <el-dialog
    v-model="dialogVisible"
    :title="announcement?.scheduled_at ? '修改定时发布时间' : '定时发布公告'"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="公告标题">
        <div class="text-gray-600">{{ announcement?.title }}</div>
      </el-form-item>

      <el-form-item label="定时发布日期" prop="scheduled_date">
        <el-date-picker
          v-model="form.scheduled_date"
          type="date"
          placeholder="选择定时发布日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
          class="w-full"
        />
      </el-form-item>

      <el-form-item label="定时发布时间" prop="scheduled_time">
        <el-time-picker
          v-model="form.scheduled_time"
          placeholder="选择定时发布时间"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          :disabled="!form.scheduled_date"
          class="w-full"
        />
      </el-form-item>

      <el-form-item label="提示信息">
        <div class="text-sm text-gray-500">
          <p>• 定时发布日期不能早于今天</p>
          <p>• 设置后公告将保持草稿状态，到指定时间自动发布</p>
          <p>• 可以随时取消定时发布，重新设置</p>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="flex justify-end space-x-3">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ announcement?.scheduled_at ? '确认修改' : '确认设置' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { announcementApi } from '@/api'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  announcement: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// 响应式数据
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  scheduled_date: '',
  scheduled_time: ''
})

// 表单验证规则
const rules = {
  scheduled_date: [
    { required: true, message: '请选择定时发布日期', trigger: 'change' }
  ],
  scheduled_time: [
    { required: true, message: '请选择定时发布时间', trigger: 'change' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 禁用过去的日期
const disabledDate = (time) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return time.getTime() < today.getTime()
}

// 监听对话框显示状态
watch(() => props.modelValue, (visible) => {
  if (visible && props.announcement) {
    if (props.announcement.scheduled_at) {
      const scheduledDate = new Date(props.announcement.scheduled_at)
      const year = scheduledDate.getFullYear()
      const month = String(scheduledDate.getMonth() + 1).padStart(2, '0')
      const day = String(scheduledDate.getDate()).padStart(2, '0')
      form.scheduled_date = `${year}-${month}-${day}`

      const hours = String(scheduledDate.getHours()).padStart(2, '0')
      const minutes = String(scheduledDate.getMinutes()).padStart(2, '0')
      const seconds = String(scheduledDate.getSeconds()).padStart(2, '0')
      form.scheduled_time = `${hours}:${minutes}:${seconds}`
    } else {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      form.scheduled_date = `${year}-${month}-${day}`

      const defaultTime = new Date()
      defaultTime.setHours(defaultTime.getHours() + 1)
      const hours = String(defaultTime.getHours()).padStart(2, '0')
      const minutes = String(defaultTime.getMinutes()).padStart(2, '0')
      const seconds = String(defaultTime.getSeconds()).padStart(2, '0')
      form.scheduled_time = `${hours}:${minutes}:${seconds}`
    }
  }
})

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  form.scheduled_date = ''
  form.scheduled_time = ''
}

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

  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  loading.value = true

  try {
    if (props.announcement.scheduled_at) {
      await announcementApi.updateSchedulePublishAnnouncement(props.announcement.id, {
        scheduled_time: `${form.scheduled_date} ${form.scheduled_time}`
      })
    } else {
      await announcementApi.schedulePublishAnnouncement(props.announcement.id, {
        scheduled_time: `${form.scheduled_date} ${form.scheduled_time}`
      })
    }

    ElMessage.success(props.announcement.scheduled_at ? '定时发布时间修改成功' : '定时发布设置成功')
    emit('success')
    handleClose()
  } catch (error) {
    ElMessage.error(error.message || '设置定时发布失败')
  } finally {
    loading.value = false
  }
}
</script>

