<template>
  <div class="bg-white p-6 mb-6 rounded-lg shadow-sm relative">
    <!-- 自实现的导览提示：UnoCSS 显眼样式 + 进入/离开过渡 -->
    <Transition name="tour-hint">
      <div
        v-show="showAskTabTour"
        role="alert"
        class="absolute top-0 right-0 z-10 min-w-52 max-w-72 rounded-xl border-l-4 border-blue-500 bg-gradient-to-br from-blue-50 to-indigo-50 px-4 py-4 pr-10 shadow-xl shadow-blue-200/40 ring-2 ring-blue-200/80"
      >
        <button
          type="button"
          aria-label="关闭导览"
          class="cursor-pointer absolute top-2 right-2 flex size-6 items-center justify-center rounded-lg text-slate-400 outline-none transition-colors hover:bg-slate-200/80 hover:text-slate-600"
          @click="closeAskTabTour"
        >
          <el-icon :size="16"><IEpClose /></el-icon>
        </button>
        <p class="mb-3 text-base font-semibold leading-snug text-slate-800">在这里发布你的问题</p>
        <span class="mb-3 block text-xs text-slate-500">操作指引</span>
        <el-button
          type="primary"
          size="small"
          class="rounded-lg font-medium shadow-sm"
          @click="closeAskTabTour"
        >
          结束导览
        </el-button>
      </div>
    </Transition>
    <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">
          <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
              :showMention="false"
              :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"
    />
  </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'
import { push } from 'notivue'
import { useTourStore } from '@/stores'

const tourStore = useTourStore()
const { showAskTabTour } = storeToRefs(tourStore)
// 暂时只有 问吧 和 实践 需要发布框 这俩都需要实名
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 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, , forReset] = 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 closeAskTabTour = () => {
  showAskTabTour.value = false
}

const validateForm = () => {
  if (!form.value.mainTagId) {
    push.warning('请选择主标签')
    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
    push.success(releaseStatus === ReleaseStatusTypeEnum.PUBLISH ? '发布成功' : '存草稿成功')
    // resetForm()
    forReset()
    // form.value.imgUrl = ''
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 导览提示进入/离开过渡 */
.tour-hint-enter-active,
.tour-hint-leave-active {
  transition:
    opacity 0.25s ease,
    transform 0.25s ease;
}
.tour-hint-enter-from,
.tour-hint-leave-to {
  opacity: 0;
  transform: translateX(8px) scale(0.96);
}
.tour-hint-enter-to,
.tour-hint-leave-from {
  opacity: 1;
  transform: translateX(0) scale(1);
}
</style>
