<template>
  <div class="min-h-screen bg-gradient-to-br pb-10">
    <!-- 主编辑区域 -->
    <div class="bg-white rounded-lg shadow-lg border border-gray-100/50 overflow-hidden">
      <div class="px-10 py-5">
        <!-- 标题输入 -->
        <el-form-item prop="title" class="mb-8">
          <el-input
            v-model="form.title"
            :placeholder="`在这里输入你的${text}标题...`"
            class="title-input text-3xl font-bold"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 3 }"
            resize="none"
          />
        </el-form-item>

        <!-- 富文本编辑器 -->
        <div>
          <el-form-item prop="content">
            <!-- 问吧和实践不是富文本 -->
            <template
              v-if="
                form.type === ArticleTypeEnum.PRACTICE || form.type === ArticleTypeEnum.QUESTION
              "
            >
              <el-input
                :placeholder="`请输入${text}内容`"
                v-model="form.content"
                type="textarea"
                :rows="30"
                :maxlength="2000"
                show-word-limit
              />
            </template>
            <template v-else>
              <!-- 回显回来可能会有bug 所以需要key 重新渲染一下-->
              <WangEditor :key v-model="form.content" class="min-h[90vh]" />
            </template>
          </el-form-item>
        </div>
      </div>
    </div>

    <!-- 底部固定按钮栏 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg">
      <div class="max-w-[1200px] mx-auto px-4 py-4">
        <div class="flex justify-center gap-4">
          <el-button @click="handleClosed" class="rounded-lg min-w[120px]"> 取消 </el-button>
          <el-button
            type="primary"
            :disabled="!canPublish"
            @click="openDrawer"
            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 min-w[120px]"
          >
            {{ isEdit ? '编辑' : '发布' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 右侧抽屉：发布配置 -->
    <el-drawer
      v-model="drawerVisible"
      title="文章信息"
      direction="rtl"
      size="500px"
      :before-close="handleDrawerClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="px-4">
        <!-- 基础设置 -->
        <div>
          <!-- 文章类型 -->
          <el-form-item label="文章类型" prop="type">
            <el-button
              type="primary"
              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 min-w[120px]"
            >
              {{ text }}
            </el-button>
          </el-form-item>

          <!-- 内容图片 实践和问吧需要上传内容图片 然后默认第一张是封面图 -->
          <template
            v-if="form.type === ArticleTypeEnum.PRACTICE || form.type === ArticleTypeEnum.QUESTION"
          >
            <el-form-item label="图片">
              <UploadFile v-model="form.imgUrl" :limit="1" class="w-full" />
            </el-form-item>
          </template>

          <!-- 帖子 专栏专访 是富文本 需要上传封面图 封面图 -->
          <template v-else>
            <el-form-item label="封面图" prop="faceUrl">
              <UploadFile class="w-fit" v-model="form.faceUrl" :limit="1" />
            </el-form-item>
          </template>

          <!-- 标签和主标签 除了帖子 都需要上传 -->
          <template v-if="form.type !== ArticleTypeEnum.POST">
            <el-form-item label="主标签" prop="mainTagId">
              <SelectTags v-model="form.mainTagId" class="w-full" />
            </el-form-item>

            <el-form-item label="副标签 (最多3个)">
              <SelectTags
                v-model="form.tagList"
                :filter-tags-fn="filterTagsFn"
                :max-selected-tags="3"
                class="w-full"
              />
            </el-form-item>
          </template>
        </div>

        <!-- 专栏配置 (条件显示) -->
        <template
          v-if="form.type === ArticleTypeEnum.COLUMN || form.type === ArticleTypeEnum.INTERVIEW"
        >
          <div>
            <el-form-item label="所属栏目" prop="relateColumnId">
              <el-select
                v-model="form.relateColumnId"
                :placeholder="`请选择${text}栏目`"
                class="w-full"
              >
                <el-option
                  v-for="item in relateColumnList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="主标签" prop="mainTagId">
              <SelectTags v-model="form.mainTagId" class="w-full" />
            </el-form-item>

            <el-form-item label="副标签 (最多3个)">
              <SelectTags
                v-model="form.tagList"
                :filter-tags-fn="filterTagsFn"
                :max-selected-tags="3"
                class="w-full"
              />
            </el-form-item> -->

            <el-form-item label="是否推荐" prop="isRecommend">
              <!-- 改为radio单选框 -->
              <el-radio-group v-model="form.isRecommend">
                <el-radio :value="BooleanFlag.YES">是</el-radio>
                <el-radio :value="BooleanFlag.NO">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="同步同事吧"
              prop="isRelateColleague"
              v-if="form.type === ArticleTypeEnum.COLUMN"
            >
              <el-radio-group v-model="form.isRelateColleague">
                <el-radio :value="BooleanFlag.YES">是</el-radio>
                <el-radio :value="BooleanFlag.NO">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 如果是官方账号的话还有推送相关的配置  以及能上传视频-->
            <template v-if="userInfo.isOfficialAccount">
              <el-form-item label="推送给">
                <el-button class="button-new-tag" size="small" @click="handleSelectUserAndDept">
                  + 添加部门
                </el-button>
                <span class="ml-2 text-sm text-gray-600"> {{ selectedText }}已选择下属部门</span>
              </el-form-item>
              <el-form-item label="推送类型" prop="pushType">
                <el-radio-group v-model="form.pushType">
                  <el-radio :value="SendTypeEnum.IMMEDIATE">立即推送</el-radio>
                  <el-radio :value="SendTypeEnum.SCHEDULED">定时推送</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.pushType === SendTypeEnum.SCHEDULED" prop="pushTime">
                <el-date-picker
                  v-model="form.pushTime"
                  type="datetime"
                  placeholder="选择推送时间"
                  :disabled-date="(time: Date) => time.getTime() < Date.now() - 1000 * 60 * 60 * 24"
                  value-format="X"
                />
              </el-form-item>

              <!-- 插入视频 顶部或者底部 radio -->
              <el-form-item label="插入视频" prop="videoLocation">
                <el-radio-group v-model="form.videoLocation">
                  <el-radio :value="VideoPositionEnum.TOP">顶部</el-radio>
                  <el-radio :value="VideoPositionEnum.BOTTOM">底部</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="视频" prop="articleVideoUrl">
                <UploadVideo v-model="form.articleVideoUrl" btnClass="flex-col" />
              </el-form-item>
            </template>
          </div>
        </template>

        <!-- 发布设置 -->
        <div>
          <el-form-item label="发布时间" prop="sendType">
            <el-radio-group v-model="form.sendType">
              <el-radio :value="SendTypeEnum.IMMEDIATE">立即发布</el-radio>
              <el-radio :value="SendTypeEnum.SCHEDULED">定时发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.sendType === SendTypeEnum.SCHEDULED" prop="sendTime">
            <el-date-picker
              v-model="form.sendTime"
              type="datetime"
              placeholder="选择发布时间"
              :disabled-date="(time: Date) => time.getTime() < Date.now() - 1000 * 60 * 60 * 24"
              value-format="X"
            />
          </el-form-item>
        </div>
      </el-form>

      <!-- 抽屉底部按钮 -->
      <template #footer>
        <div class="flex gap-3 justify-end">
          <el-button @click="handleDrawerClose" class="rounded-lg">取消</el-button>
          <el-button @click="handleSubmit(ReleaseStatusTypeEnum.DRAFT)" class="rounded-lg">
            存草稿
          </el-button>
          <el-button
            :loading="loading"
            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 min-w[120px]"
          >
            确认{{ isEdit ? '编辑' : '发布' }}
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import WangEditor from '@/components/common/WangEditor/index.vue'
import {
  ArticleTypeEnum,
  SendTypeEnum,
  BooleanFlag,
  ReleaseStatusTypeEnum,
  articleTypeListOptions,
  VideoPositionEnum,
} from '@/constants'
import UploadFile from '@/components/common/UploadFile/index.vue'
import UploadVideo from '@/components/common/UploadVideo/index.vue'
import { useResetData } from '@/hooks'
import { useColumnStore } from '@/stores/column'
import { useInterviewStore } from '@/stores/interview'
import { storeToRefs } from 'pinia'
import { addOrUpdateArticle, addOrUpdatePractice, getArticleDetail } from '@/api'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { selectDepOrUser } from '@/utils'
import type { FormItemRule } from 'element-plus'

const columnStore = useColumnStore()
const { columnList } = storeToRefs(columnStore)
const interviewStore = useInterviewStore()
const { interviewList } = storeToRefs(interviewStore)
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const loading = ref(false)

const router = useRouter()
const route = useRoute()
const type = route.params.type as ArticleTypeEnum
const text = articleTypeListOptions.find((item) => item.value === type)?.label

const canPublish = computed(() => {
  return form.value.title && form.value.content
})

const relateColumnList = computed(() =>
  type === ArticleTypeEnum.COLUMN ? columnList.value : interviewList.value,
)

// 抽屉控制
const drawerVisible = ref(false)

const formRef = useTemplateRef<FormInstance>('formRef')
const [form, resetForm] = useResetData({
  id: undefined as number | undefined,
  type,
  title: '',
  content: '',
  faceUrl: '',
  imgUrl: '',
  relateColumnId: '' as string | number,
  mainTagId: '',
  tagList: [] as number[],
  isRelateColleague: BooleanFlag.NO,
  isRecommend: BooleanFlag.NO,
  sendType: SendTypeEnum.IMMEDIATE,
  sendTime: '',
  releaseStatus: ReleaseStatusTypeEnum.PUBLISH,

  // 推送设置
  pushType: SendTypeEnum.IMMEDIATE,
  pushTime: '',
  pushList: [],

  // 视频
  videoLocation: VideoPositionEnum.TOP,
  articleVideoUrl: '',
})

const rules: Record<string, FormItemRule[]> = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择文章类型', trigger: 'blur' }],
  faceUrl: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
  imgUrl: [{ required: true, message: '请上传内容图片', trigger: 'blur' }],
  sendType: [{ required: true, message: '请选择发布类型', trigger: 'blur' }],
  sendTime: [
    { required: true, message: '请选择发布时间', trigger: 'trigger' },
    {
      validator: (rule, value, callback) => {
        if (form.value.sendType === SendTypeEnum.SCHEDULED && !value) {
          callback(new Error('请选择发布时间'))
        }
      },
      trigger: 'trigger',
    },
  ],
  releaseStatus: [{ required: true, message: '请选择发布状态', trigger: 'blur' }],
  mainTagId: [{ required: true, message: '请选择主标签', trigger: 'blur' }],
  isRecommend: [{ required: true, message: '是否推荐', trigger: 'trigger' }],
  isRelateColleague: [{ required: true, message: '是否同步同事吧', trigger: 'trigger' }],
  relateColumnId: [{ required: true, message: '请选择对应的栏目', trigger: 'trigger' }],

  // 推送设置
  pushType: [{ required: true, message: '请选择推送类型', trigger: 'trigger' }],
  pushTime: [{ required: true, message: '请选择推送时间', trigger: 'trigger' }],
  pushList: [{ required: true, message: '请选择推送对象', trigger: 'trigger' }],
}

// 选中的部门
const selectedDepts = ref<{ id: string; name: string }[]>([])
// 选中的成员
const selectedUsers = ref<{ id: string; name: string }[]>([])
const selectedText = computed(() => {
  let text = ''
  if (selectedDepts.value.length > 0) {
    text += `已选择${selectedDepts.value.length}个部门`
  }
  if (selectedUsers.value.length > 0) {
    text += `已选择${selectedUsers.value.length}个成员`
  }
  return text
})

const handleSelectUserAndDept = async () => {
  const { departmentList, userList } = await selectDepOrUser({
    mode: 'multi',
    type: ['user', 'department'],
    selectedDepartmentIds: selectedDepts.value.map((item) => item.id),
    selectedUserIds: selectedUsers.value.map((item) => item.id),
  })
  console.log(departmentList, userList)
  selectedDepts.value = departmentList.map((item) => ({
    id: item.id,
    name: item.name,
  }))
  selectedUsers.value = userList.map((item) => ({
    id: item.id,
    name: item.name,
  }))
}

const filterTagsFn = (allTags: any[]) => {
  return allTags.filter((tag) => tag.id !== Number(form.value.mainTagId))
}

const transFormData = (releaseStatus: ReleaseStatusTypeEnum) => {
  const { tagList, ...data } = form.value as any

  data.tagList = [data.mainTagId, ...tagList].map((item, index) => ({
    tagId: Number(item),
    sort: index,
  }))
  data.releaseStatus = releaseStatus
  if (data.type === ArticleTypeEnum.PRACTICE || data.type === ArticleTypeEnum.QUESTION) {
    // 手动设置一下封面图
    if (data.imgUrl) {
      data.faceUrl = data.imgUrl.split(',')[0] || ''
    }
  }

  if (
    (data.type === ArticleTypeEnum.COLUMN || data.type === ArticleTypeEnum.INTERVIEW) &&
    userInfo.value.isOfficialAccount
  ) {
    data.pushList = [
      ...selectedDepts.value.map((item) => ({
        valueId: item.id,
        valueType: 1,
        valueName: item.name,
      })),
      ...selectedUsers.value.map((item) => ({
        valueId: item.id,
        valueType: 2,
        valueName: item.name,
      })),
    ]
  }

  return data
}

// 打开抽屉
const openDrawer = () => {
  drawerVisible.value = true
}

// 关闭抽屉
const handleDrawerClose = () => {
  drawerVisible.value = false
}

// 取消按钮
const handleClosed = () => {
  resetForm()
  router.back()
}

// 提交表单
const handleSubmit = async (releaseStatus: ReleaseStatusTypeEnum) => {
  try {
    console.log(form.value, 'form.value')
    await formRef.value?.validate()
    loading.value = true
    const res =
      form.value.type === ArticleTypeEnum.PRACTICE
        ? await addOrUpdatePractice(transFormData(releaseStatus))
        : await addOrUpdateArticle(transFormData(releaseStatus))
    console.log(res)
    drawerVisible.value = false
    ElMessage.success(releaseStatus === ReleaseStatusTypeEnum.PUBLISH ? '发布成功' : '存草稿成功')
    resetForm()
    router.back()
    // 发布成功后的逻辑...
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

const key = ref(0)
const isEdit = computed(() => !!route.query.id)
onActivated(async () => {
  key.value++
  resetForm()

  await nextTick()
  if (isEdit.value) {
    console.log(route.query.id, '编辑 或者 草稿箱')
    // 要编辑回显
    const { data } = await getArticleDetail(route.query.id as string)
    // 首先回显基础的信息
    // 标题 内容 主标签 副标签 所属栏目 是否推荐 是否同步同事吧 发布时间 发布状态
    const {
      id,

      title,
      content,
      relateColumnId,
      isRecommend,
      isRelateColleague,
      sendType,
      sendTime,

      tagIdList,
    } = data

    form.value = {
      ...form.value,
      title,
      content,
      relateColumnId,
      isRecommend,
      isRelateColleague,
      sendType,
      sendTime,
      id,
    }

    // 回显主副标签
    form.value.mainTagId = tagIdList[0] ? String(tagIdList[0]) : ''
    form.value.tagList = tagIdList.slice(1) || []

    const { imgUrl, faceUrl } = data

    if (type === ArticleTypeEnum.QUESTION || type === ArticleTypeEnum.PRACTICE) {
      form.value.imgUrl = imgUrl
    } else {
      form.value.faceUrl = faceUrl
    }
    // 回显推送人员设置
    if (
      (type === ArticleTypeEnum.COLUMN || type === ArticleTypeEnum.INTERVIEW) &&
      userInfo.value.isOfficialAccount
    ) {
      selectedDepts.value = data.pushList
        .filter((item) => item.valueType === 1)
        .map((item) => ({
          id: item.valueId,
          name: item.valueName,
        }))
      selectedUsers.value = data.pushList
        .filter((item) => item.valueType === 2)
        .map((item) => ({
          id: item.valueId,
          name: item.valueName,
        }))
    }
  }
})
</script>

<style scoped>
/* 标题输入框样式 */
:deep(.title-input .el-textarea__inner) {
  border: none;
  padding: 0;
  font-size: 2rem;
  font-weight: 700;
  line-height: 1.3;
  color: #1f2937;
  background: transparent;
  box-shadow: none !important;
}

:deep(.title-input .el-textarea__inner:focus) {
  outline: none;
  box-shadow: none !important;
}

:deep(.title-input .el-textarea__inner::placeholder) {
  color: #d1d5db;
  font-weight: 600;
}

/* 表单项标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  font-size: 0.875rem;
}

/* 抽屉内容滚动 */
:deep(.el-drawer__body) {
  padding: 20px 0;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
