<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :close-on-click-modal="false"
    width="500px"
    class="post-dialog"
    :lock-scroll="true"
    align-center
    @closed="handleClosed"
  >
    <div v-loading="loading" class="bg-white/95 rounded-16px p-24px backdrop-blur-10px">
      <!-- <keep-alive> -->
      <component :is="currentFormComp" ref="formComponentRef" />
      <!-- </keep-alive> -->

      <!-- 底部按钮 -->
      <div class="flex justify-end gap-1">
        <el-button class="rounded-lg" @click="handleClosed">取消</el-button>
        <el-button class="rounded-lg" @click="handleSubmit(ReleaseStatusTypeEnum.DRAFT)">
          存草稿
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmit(ReleaseStatusTypeEnum.PUBLISH)"
          class="px-6 py-2 bg-blue-500 hover:bg-blue-600 rounded-lg text-white text-sm font-medium shadow-sm hover:shadow-md transition-all duration-200"
        >
          发布
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import type { Component } from 'vue'

// 如果 你已经按需引入了 那么写 这个就会有css bug 所以 这里不写 就是你如果写这个的话 那么 他不会引入css
// import { ElDialog } from 'element-plus'
// import { Plus } from '@element-plus/icons-vue'
import { addOrUpdateArticle, addOrUpdatePractice } from '@/api'
import { ArticleTypeEnum, ReleaseStatusTypeEnum } from '@/constants'
import LoadingComponent from '@/components/common/LoadingComponent/index.vue'

interface ApiMap {
  [ArticleTypeEnum.VIDEO]: typeof addOrUpdateArticle
  [ArticleTypeEnum.QUESTION]: typeof addOrUpdateArticle
  [ArticleTypeEnum.POST]: typeof addOrUpdateArticle
  [ArticleTypeEnum.PRACTICE]: typeof addOrUpdatePractice
  [ArticleTypeEnum.COLUMN]: typeof addOrUpdateArticle
  [ArticleTypeEnum.INTERVIEW]: typeof addOrUpdateArticle
}
interface TypeConfig<T extends ArticleTypeEnum> {
  title: string
  component: Component
  api?: ApiMap[T]
}

const typeMap: {
  [key in ArticleTypeEnum]: TypeConfig<key>
} = {
  [ArticleTypeEnum.VIDEO]: {
    title: '视频',
    component: defineAsyncComponent({
      loader: () => import('./postForm.tsx'),
      delay: 200,
      loadingComponent: LoadingComponent,
    }),
  },
  [ArticleTypeEnum.QUESTION]: {
    title: '问题',
    component: defineAsyncComponent({
      loader: () => import('./postForm.tsx'),
      delay: 200,
      loadingComponent: LoadingComponent,
    }),
  },
  [ArticleTypeEnum.POST]: {
    title: '帖子',
    component: defineAsyncComponent({
      loader: async () => {
        const start = Date.now()

        const comp = await import('./postForm.tsx')
        const cost = Date.now() - start
        console.log('cost', cost)
        const min = 1000 // 最低 200ms

        if (cost < min) {
          await new Promise((r) => setTimeout(r, min - cost))
        }

        return comp
      },
      delay: 200,
      loadingComponent: LoadingComponent,
    }),
    api: addOrUpdateArticle,
  },
  [ArticleTypeEnum.PRACTICE]: {
    title: '实践',
    component: defineAsyncComponent({
      loader: () => import('./practiceForm.tsx'),
      delay: 200,
      loadingComponent: LoadingComponent,
    }),
    api: addOrUpdatePractice,
  },
  [ArticleTypeEnum.COLUMN]: {
    title: '专栏',
    component: defineAsyncComponent({
      loader: () => import('./colnumForm.tsx'),
      delay: 200,
      loadingComponent: LoadingComponent,
    }),
    api: addOrUpdateArticle,
  },
  [ArticleTypeEnum.INTERVIEW]: {
    title: '专访',
    component: defineAsyncComponent({
      loader: () => import('./interviewForm.tsx'),
      delay: 200,
      loadingComponent: LoadingComponent,
    }),
    api: addOrUpdateArticle,
  },
}

const dialogTitle = computed(() => '发布' + typeMap[articleType.value].title)
export interface BaseFormExpose {
  resetFields: () => void
  getValidatedFormData: (releaseStatus: ReleaseStatusTypeEnum) => Promise<unknown>
}
const formComponentRef = useTemplateRef<BaseFormExpose>('formComponentRef')

const currentFormComp = computed(() => {
  return typeMap[articleType.value].component
})

const dialogVisible = ref(false)

const articleType = ref<ArticleTypeEnum>(ArticleTypeEnum.PRACTICE)
const loading = ref(false)

// 打开弹窗
const open = (type: ArticleTypeEnum) => {
  articleType.value = type
  dialogVisible.value = true
}

// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  formComponentRef?.value?.resetFields()
}

const handleClosed = () => {
  dialogVisible.value = false
  formComponentRef.value?.resetFields()
}

const handleSubmit = async (releaseStatus: ReleaseStatusTypeEnum) => {
  loading.value = true
  try {
    const formData = (await formComponentRef.value?.getValidatedFormData(releaseStatus)) as any
    if (!formData) return
    console.log(formData)
    await typeMap[articleType.value].api?.({
      ...formData,
    })
    ElMessage.success('发布成功')
    // 这里可以添加发布逻辑
    close()
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  open,
  close,
})
</script>
