<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="动态标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入动态标题" />
      </el-form-item>

      <el-form-item label="动态内容" prop="content">
        <Editor v-model="formData.content" height="200px" />
      </el-form-item>

      <el-form-item label="发布方" prop="author">
        <el-input v-model="formData.author" placeholder="请输入发布方" />
      </el-form-item>

      <el-form-item label="封面图片" prop="coverImage">
        <UploadImg v-model="formData.coverImage" :limit="1" />
      </el-form-item>

      <el-form-item label="动态类型" prop="postType">
        <el-select v-model="formData.postType" placeholder="请选择动态类型" style="width: 100%">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMM_POST_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-divider content-position="left">
        <el-icon><InfoFilled /></el-icon>
        发布信息
      </el-divider>

      <el-form-item label="发布时间" prop="publishType">
        <el-radio-group v-model="formData.publishType">
          <el-radio :value="1">立即发布</el-radio>
          <el-radio :value="2">定时发布</el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="formData.publishType === 2"
          v-model="formData.publishTime"
          type="datetime"
          placeholder="选择发布时间"
          value-format="x"
          style="margin-left: 12px"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endType">
        <el-radio-group v-model="formData.endType">
          <el-radio :value="1">长期有效</el-radio>
          <el-radio :value="2">定时结束</el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="formData.endType === 2"
          v-model="formData.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="x"
          style="margin-left: 12px"
        />
      </el-form-item>

      <el-form-item label="发布范围" prop="communityIds">
        <el-select
          v-model="formData.communityIds"
          placeholder="请选择小区"
          clearable
          filterable
          multiple
          collapse-tags
          collapse-tags-tooltip
          style="width: 100%"
        >
          <el-option
            v-for="item in communityOptions"
            :key="item.id"
            :label="item.communityName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="消息推送" prop="pushEnabled">
        <el-switch v-model="formData.pushEnabled" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CommunityPostApi, CommunityPost } from '@/api/community/post'
import { CommunityApi, CommunitySimpleVO } from '@/api/community/community'
import { InfoFilled } from '@element-plus/icons-vue'

/** 社区动态 表单 */
defineOptions({ name: 'CommunityPostForm' })

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({
  id: undefined,
  title: undefined,
  content: undefined,
  author: undefined,
  coverImage: undefined,
  postType: undefined,
  publishType: 1,
  publishTime: undefined,
  endType: 1,
  endTime: undefined,
  communityIds: [],
  pushEnabled: false
})
const formRules = reactive({
  title: [{ required: true, message: '动态标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '动态内容不能为空', trigger: 'blur' }],
  author: [{ required: true, message: '发布方不能为空', trigger: 'blur' }],
  postType: [{ required: true, message: '动态类型不能为空', trigger: 'change' }],
  publishType: [{ required: true, message: '发布类型不能为空', trigger: 'change' }],
  endType: [{ required: true, message: '结束类型不能为空', trigger: 'change' }],
  communityIds: [{ required: true, message: '请选择发布范围', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const communityOptions = ref<CommunitySimpleVO[]>([]) // 小区选项列表

/** 加载小区列表 */
const loadCommunityList = async () => {
  try {
    communityOptions.value = await CommunityApi.getCommunitySimpleList()
  } catch (error) {
    console.error('加载小区列表失败:', error)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载小区列表
  await loadCommunityList()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await CommunityPostApi.getCommunityPost(id)
      formData.value = {
        id: data.id,
        title: data.title,
        content: data.content,
        author: data.author,
        coverImage: data.coverImage,
        postType: data.postType,
        publishType: data.publishType || 1,
        publishTime: data.publishTime,
        endType: data.endType || 1,
        endTime: data.endTime,
        communityIds: Array.isArray(data.communityIds) ? data.communityIds : [],
        pushEnabled: data.pushEnabled !== undefined ? data.pushEnabled : false
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      id: formData.value.id,
      title: formData.value.title,
      content: formData.value.content,
      author: formData.value.author,
      coverImage: formData.value.coverImage,
      postType: formData.value.postType,
      publishType: formData.value.publishType,
      publishTime: formData.value.publishType === 1 ? undefined : formData.value.publishTime,
      endType: formData.value.endType,
      endTime: formData.value.endType === 1 ? undefined : formData.value.endTime,
      communityIds: formData.value.communityIds,
      pushEnabled: formData.value.pushEnabled
    } as unknown as CommunityPost
    if (formType.value === 'create') {
      await CommunityPostApi.createCommunityPost(data)
      message.success(t('common.createSuccess'))
    } else {
      await CommunityPostApi.updateCommunityPost(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    content: undefined,
    author: undefined,
    coverImage: undefined,
    postType: undefined,
    publishType: 1,
    publishTime: undefined,
    endType: 1,
    endTime: undefined,
    communityIds: [],
    pushEnabled: false
  }
  formRef.value?.resetFields()
}

</script>
