<template>
  <div class="bg-white p-6 mb-6 rounded-lg shadow-sm">
    <div class="flex-1 bg-white rounded-lg border border-gray-200">
      <!-- 主输入区域 -->

      <div class="flex gap-3 mb-2 items-start">
        <!-- 用户头像 -->
        <el-avatar
          :size="48"
          :src="userAvatar"
          class="flex-shrink-0"
          @click="() => console.log(form)"
        >
          <el-icon>
            <IEpUser />
          </el-icon>
        </el-avatar>

        <!-- 输入区域 -->
        <div class="flex-1">
          <!-- 话题标签输入 -->
          <div class="mb-4">
            <el-input
              v-model="form.title"
              :placeholder="textMap[type].title"
              class="tag-input"
              clearable
            />
          </div>
          <!-- 主要内容输入 -->
          <div class="relative mb-3">
            <RichTextarea
              :placeholder="textMap[type].content"
              :maxlength="maxLength"
              :imgList="imgList"
              :uploadPercent="uploadPercent"
              v-model="form.content"
              @deleteImg="handleDeleteImg"
              :height="100"
            />
          </div>
          <!-- 标签内容 -->
          <div class="mb-2">
            <!-- 选择的标签内容 -->
            <div class="flex items-center gap-2">
              <span v-if="mainTagText" class="text-sm text-gray-500"
                >主标签：
                <el-tag>{{ mainTagText }}</el-tag>
              </span>
              <span v-if="subTagTextList.length > 0" class="text-sm text-gray-500"
                >副标签：
                <el-tag class="mr-2" v-for="tag in subTagTextList" :key="tag">{{ tag }}</el-tag>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 工具栏 -->
      <div class="flex items-center justify-between pl-15">
        <!-- 左侧工具按钮 -->
        <div class="flex items-center gap-1">
          <el-tooltip content="添加标签" placement="top" :visible="visibleTagTooltip">
            <el-button
              ref="tagButtonRef"
              text
              class="w-10 h-10 text-gray-500 hover:bg-gray-100 hover:text-gray-700 rounded-lg"
              @click="handleAddTag"
              @mouseenter="visibleTagTooltip = true"
              @mouseleave="visibleTagTooltip = false"
            >
              <el-icon size="18">
                <IEpCollectionTag />
              </el-icon>
            </el-button>
          </el-tooltip>

          <UploadImgIcon @fileChange="handleFileChange">
            <el-tooltip content="添加图片" placement="top">
              <el-button
                text
                class="w-10 h-10 text-gray-500 hover:bg-gray-100 hover:text-gray-700 rounded-lg"
                :disabled="uploadPercent > 0"
              >
                <el-icon size="18">
                  <span v-if="!imgList.length && uploadPercent > 0"> <IEpLoading /></span>
                  <span v-else> <IEpPicture /></span>
                </el-icon>
              </el-button>
            </el-tooltip>
          </UploadImgIcon>
        </div>

        <!-- 右侧操作按钮 -->
        <div class="flex items-center gap-3">
          <el-button
            class="px-4 py-2 text-gray-600 hover:text-gray-800 hover:bg-gray-50 rounded-lg border border-gray-200 text-sm"
            @click="handlePublish(ReleaseStatusTypeEnum.DRAFT)"
          >
            存草稿
          </el-button>

          <el-button
            type="primary"
            :disabled="disabledSubmit"
            :loading="loading"
            class="px-6 py-2 bg-blue-500 hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg text-white text-sm font-medium shadow-sm hover:shadow-md transition-all duration-200"
            @click="handlePublish(ReleaseStatusTypeEnum.PUBLISH)"
          >
            发布 {{ type === ArticleTypeEnum.QUESTION ? '问题' : '实践' }}
          </el-button>
        </div>
      </div>
    </div>
    <SelectTagsDialog
      v-model:mainTagId="form.mainTagId"
      v-model:tagList="form.tagList"
      ref="selectTagsDialogRef"
    />

    <el-tour v-model="openTour" :mask="false" placement="left-start" type="primary">
      <el-tour-step :target="tagButtonRef?.$el" description="在这里选择标签" placement="top" />
    </el-tour>
  </div>
</template>
<!-- 发布实践 或者 问吧 的 发布框 -->
<script setup lang="ts">
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import SelectTagsDialog from './components/selectTagsDialog.vue'
import { useResetData, useUploadImg } from '@/hooks'
import { ArticleTypeEnum, ReleaseStatusTypeEnum, SendTypeEnum } from '@/constants'
import { useTagsStore } from '@/stores'
import { addOrUpdatePractice, addOrUpdateArticle } from '@/api'
import type { AddOrUpdatePracticeDto } from '@/api'
import type { ElButton } from 'element-plus'
import { useAnimate } from '@vueuse/core'
import RichTextarea from '../RichTextarea/index.vue'
import UploadImgIcon from '../UploadImgIcon/index.vue'

// 暂时只有 问吧 和 实践 需要发布框 这俩都需要实名
type ArticleType = ArticleTypeEnum.QUESTION | ArticleTypeEnum.PRACTICE

const { type, maxLength = 500 } = defineProps<{
  type: ArticleType
  maxLength?: number
}>()

const loading = ref(false)

const textMap: Record<
  ArticleType,
  { title: string; content: string; api: (data: any) => Promise<any> }
> = {
  [ArticleTypeEnum.QUESTION]: {
    title: '问题标题',
    content: '请输入问题内容',
    api: addOrUpdateArticle,
  },
  [ArticleTypeEnum.PRACTICE]: {
    title: '实践标题',
    content: '请输入实践内容',
    api: addOrUpdatePractice,
  },
}

const tagsStore = useTagsStore()
const { tagList } = storeToRefs(tagsStore)

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 问吧 和 实践 需要实名 后续如果要改在这里改
const isReal = computed(
  () => type === ArticleTypeEnum.PRACTICE || type === ArticleTypeEnum.QUESTION,
)
const userAvatar = computed(() =>
  isReal.value ? userInfo.value.avatar : userInfo.value.hiddenAvatar,
)

const selectTagsDialogRef =
  useTemplateRef<InstanceType<typeof SelectTagsDialog>>('selectTagsDialogRef')

// const fileInputRef = useTemplateRef<HTMLInputElement>('fileInputRef')

const openTour = ref(false)

const disabledSubmit = computed(() => {
  return !form.value.title || !form.value.content
})

const tagButtonRef = useTemplateRef<InstanceType<typeof ElButton>>('tagButtonRef')
const tagButtonEl = computed(() => tagButtonRef.value?.$el)
const visibleTagTooltip = ref(false)

const DURATION = 500
const { play } = useAnimate(
  tagButtonEl,
  [
    { transform: 'translateY(0)' },
    { transform: 'translateY(-10px)' },
    { transform: 'translateY(0)' },
  ],
  {
    duration: DURATION,
    easing: 'ease-in-out',
    immediate: false,
  },
)

const [form, resetForm] = useResetData({
  title: '',
  content: '',
  imgUrl: '',
  releaseStatus: ReleaseStatusTypeEnum.PUBLISH,
  mainTagId: '',
  tagList: [],
  sendType: SendTypeEnum.IMMEDIATE,
  sendTime: '',
})

const { imgList, handleFileChange, handleDeleteImg, uploadPercent } = useUploadImg(
  toRef(form.value, 'imgUrl'),
)

const mainTagText = computed(() => {
  return tagList.value.find((tag) => tag.id === Number(form.value.mainTagId))?.title
})

const subTagTextList = computed(() => {
  return form.value.tagList.map((tag) => tagList.value.find((t) => t.id === tag)?.title)
})

const handleAddTag = () => {
  selectTagsDialogRef.value?.open()
}

const validateForm = () => {
  if (!form.value.mainTagId) {
    ElMessage.warning({
      message: '请选择主标签',
      offset: 200,
    })
    play()
    visibleTagTooltip.value = true

    return false
  }

  return true
}
const transformForm = (releaseStatus: ReleaseStatusTypeEnum): AddOrUpdatePracticeDto => {
  return {
    ...form.value,
    releaseStatus,
    faceUrl: imgList.value[0] || '',
    imgUrl: form.value.imgUrl,
    tagList: [form.value.mainTagId, ...form.value.tagList].map((item, index) => ({
      sort: index,
      tagId: Number(item),
    })),
    type: type,
  }
}
const handlePublish = async (releaseStatus: ReleaseStatusTypeEnum) => {
  if (!validateForm()) return

  loading.value = true
  try {
    await textMap[type].api(transformForm(releaseStatus))
    loading.value = false
    ElMessage.success(releaseStatus === ReleaseStatusTypeEnum.PUBLISH ? '发布成功' : '存草稿成功')
    resetForm()
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped></style>
