<template>
  <div class="min-h-screen bg-gradient-to-br">
    <div class="max-w-4xl mx-auto">
      <!-- 主表单卡片 -->
      <div class="bg-white rounded-lg shadow-lg p-8">
        <el-form ref="formRef" :model="form" label-position="top" :rules="rules">
          <!-- 标题输入 -->
          <el-form-item class="mb-6" label="标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入【案例】标题"
              :maxlength="100"
              show-word-limit
              class="text-lg"
            />
          </el-form-item>

          <!-- 内容输入 -->
          <el-form-item class="mb-6 relative" label="内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              placeholder="添加案例文本内容..."
              :rows="12"
              :maxlength="5000"
              show-word-limit
            />
          </el-form-item>
          <!-- 文化关键词选择 -->
          <el-form-item label="文化关键词" class="mb-6" prop="mainTagId">
            <div class="flex items-start">
              <div class="flex flex-wrap gap-3 items-start">
                主标签
                <SelectTags v-model="form.mainTagId" />
              </div>
              <div class="flex flex-wrap gap-3 items-start ml-5">
                副标签
                <SelectTags
                  v-model="form.subTagIds"
                  :max-selected-tags="3"
                  :filter-tags-fn="filterTagsFn"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="关联场景" class="mb-6">
            <div class="flex items-start">
              <div class="flex flex-wrap gap-3 items-start">
                主标签
                <SelectTags
                  v-model="form.relatedScenariosMainTagId"
                  :tagType="TagTypeEnum.SCENE_TAG"
                />
              </div>
              <div class="flex flex-wrap gap-3 items-start ml-5">
                副标签
                <SelectTags
                  :tagType="TagTypeEnum.SCENE_TAG"
                  v-model="form.relatedScenariosSubTagIds"
                  :max-selected-tags="4"
                  :filter-tags-fn="filterRelatedScenariosTagsFn"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="关联部门" class="mb-6">
            <div class="flex items-start gap-3">
              <el-button class="button-new-tag" size="small" @click="selcetDept">
                + 添加部门
              </el-button>
              <el-tag
                v-for="tag in form.departmentList"
                :key="tag.id"
                closable
                type="primary"
                @close="() => delDept(tag.id)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 是否同步发布 -->
          <el-form-item label="是否同步发布到实践" class="mb-6" prop="isSync">
            <el-radio-group v-model="form.isSync">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 底部按钮组 -->
          <div class="flex items-center justify-end gap-4 pt-4">
            <el-button class="rounded-lg" @click="handleCancel"> 取消 </el-button>
            <!-- <el-button @click="handlePreview"> 预览 </el-button> -->
            <el-button class="rounded-lg" plain @click="handleSubmit(ReleaseStatusTypeEnum.DRAFT)">
              存草稿
            </el-button>
            <el-button
              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"
              type="primary"
              @click="handleSubmit(ReleaseStatusTypeEnum.PUBLISH)"
              :loading="loading"
            >
              提交
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { addOrUpdateCase, getCaseDetail } from '@/api'
import { useResetData } from '@/hooks'
import type { AddOrUpdateCaseDto } from '@/api'
import SelectTags from '@/components/common/SelectTags/index.vue'
import type { FormInstance } from 'element-plus'
import type { TagItemDto } from '@/api'
import {
  TagTypeEnum,
  TagLevelEnum,
  BooleanFlag,
  ReleaseStatusTypeEnum,
  AuditStatusEnum,
} from '@/constants'
import { selectDepOrUser } from '@/utils'
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import type { ISelectDept } from '@/utils/wxUtil'
const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const formRef = useTemplateRef<FormInstance>('formRef')
const loading = ref(false)
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  mainTagId: [{ required: true, message: '请选择文化关键词', trigger: 'blur' }],
  isSync: [{ required: true, message: '请选择是否同步发布到实践', trigger: 'blur' }],
}

const [form, resetForm] = useResetData({
  title: '',
  content: '',
  mainTagId: '',
  subTagIds: [] as number[],
  relatedScenariosMainTagId: '',
  relatedScenariosSubTagIds: [] as number[],
  isSync: BooleanFlag.NO,
  departmentList: [] as ISelectDept[],
})

// 选择部门
const selcetDept = async () => {
  const { departmentList } = await selectDepOrUser({
    mode: 'multi', // single multi
    type: ['department'],
    selectedDepartmentIds: form.value.departmentList.map((i) => i.id),
  })
  if (departmentList.length > 3) {
    return ElMessage.warning('最多只能选择3个部门，请重新选择')
  }
  console.log('选中的部门等等', departmentList)
  form.value.departmentList = departmentList
}

const delDept = (id: string) => {
  form.value.departmentList = form.value.departmentList.filter((i) => i.id !== id)
}
// 取消
const handleCancel = () => {
  resetForm()
  router.back()
}

// 保存
const transformData = (releaseStatus: ReleaseStatusTypeEnum): AddOrUpdateCaseDto => {
  const {
    mainTagId,
    subTagIds,
    relatedScenariosMainTagId,
    relatedScenariosSubTagIds,
    departmentList,
    ...rest
  } = form.value
  const obj: AddOrUpdateCaseDto = {
    ...rest,
    releaseStatus,
    tagRelationDtoList: [],
    sourceUser: '',
    deptId: '',
    deptName: '',
  }
  // 添加文化标签内容
  obj.tagRelationDtoList.push({
    tagId: Number(mainTagId),
    type: TagTypeEnum.CULTURE_TAG,
    keywordType: TagLevelEnum.MAIN_TAG,
  })
  subTagIds.forEach((id) => {
    obj.tagRelationDtoList.push({
      tagId: id,
      type: TagTypeEnum.CULTURE_TAG,
      keywordType: TagLevelEnum.SUB_TAG,
    })
  })
  // 添加关联场景
  obj.tagRelationDtoList.push({
    tagId: Number(relatedScenariosMainTagId),
    type: TagTypeEnum.SCENE_TAG,
    keywordType: TagLevelEnum.MAIN_TAG,
  })
  relatedScenariosSubTagIds.forEach((id) => {
    obj.tagRelationDtoList.push({
      tagId: id,
      type: TagTypeEnum.SCENE_TAG,
      keywordType: TagLevelEnum.SUB_TAG,
    })
  })

  // 添加部门相关字段
  obj.deptId = departmentList.map((i) => i.id).join(',')
  obj.deptName = departmentList.map((i) => i.name).join(',')

  obj.sourceUser = userInfo.value.userId
  return obj
}

const showSubmitGuide = ref(false)

// 提交
const handleSubmit = async (releaseStatus: ReleaseStatusTypeEnum) => {
  await formRef.value?.validate()

  if (showSubmitGuide.value) {
    await ElMessageBox.confirm('该案例库已审核通过，修改后需重新审核,确定提交吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  }

  loading.value = true
  try {
    await addOrUpdateCase({ ...transformData(releaseStatus) })
    ElMessage.success('提交成功')
    resetForm()
    router.back()
  } catch (error) {
    console.log('error', error)
  } finally {
    loading.value = false
  }
}

const showSubmissionGuide = () => {
  const countdown = ref(0)
  let timer: NodeJS.Timeout | null = null

  const MessageContent = (): VNode => {
    return (
      <div>
        <div class="px-5 py-4 leading-7">
          <div class="mb-4 text-base">
            1、YA伙伴实名投稿，分享您在工作中践行公司文化或解决实际业务的成功案例与经验。
          </div>
          <div class="mb-1 text-base">2、投稿时，您可自主选择：</div>
          <div class="text-sm mb-1">
            （1）公开公示：案例将实名展示YA文化“实践”版块，成为全员可见的光荣榜，用于分享、激励和学习。
          </div>
          <div class="text-sm mb-4">
            （2）私有入库：案例将直接进入亚声内部案例管理系统，作为宝贵的内部知识资产供管理层分析和参考，分析参考时不会展示分享人信息。
          </div>
          <div class="mb-4 text-base">
            3、通过奖品激励与光荣榜展示，鼓励伙伴分享，在尊重伙伴个人意愿的同时，将优秀实践经验沉淀为组织财富，实现个人成长与团队赋能的双赢。
          </div>

          <div class="flex justify-center pt-3 border-t border-[#ebeef5]">
            <el-button
              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"
              disabled={countdown.value > 0}
              loading={countdown.value > 0}
              onClick={() => {
                if (countdown.value === 0) {
                  ElMessageBox.close()
                }
              }}
            >
              {countdown.value > 0 ? `${countdown.value}s` : '确定'}
            </el-button>
          </div>
        </div>
      </div>
    )
  }
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      if (timer) clearInterval(timer)
    }
  }, 1000)

  ElMessageBox({
    title: '投稿说明',
    center: true,
    message: MessageContent,
    lockScroll: true,
    showConfirmButton: false,
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
  })
}

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

onDeactivated(() => {
  // 重置表单
  resetForm()
})

onActivated(async () => {
  const id = Number(router.currentRoute.value.query.id)
  if (id) {
    // 编辑草稿箱
    const { data } = await getCaseDetail(id)
    const cultureTagList = data.caseTags.filter((i) => i.type === TagTypeEnum.CULTURE_TAG)
    const relatedScenariosTagList = data.caseTags.filter((i) => i.type === TagTypeEnum.SCENE_TAG)
    const obj = {
      id: data.id,
      title: data.title,
      content: data.content,

      mainTagId: String(
        cultureTagList.find((i) => i.keywordType === TagLevelEnum.MAIN_TAG)?.tagId || '',
      ),
      subTagIds: cultureTagList
        .filter((i) => i.keywordType === TagLevelEnum.SUB_TAG)
        .map((i) => i.tagId),
      relatedScenariosMainTagId: String(
        relatedScenariosTagList.find((i) => i.keywordType === TagLevelEnum.MAIN_TAG)?.tagId || '',
      ),
      relatedScenariosSubTagIds: relatedScenariosTagList
        .filter((i) => i.keywordType === TagLevelEnum.SUB_TAG)
        .map((i) => i.tagId),
      isSync: data.isSync,
      departmentList: data.depIdList.map((id, index) => ({
        id: String(id),
        name: data.depNameList[index] || '',
      })),
    }
    form.value = obj
    console.log('form', form.value)

    // 已经同意的案例库 二次修改需要提示
    if (data.isAudit === AuditStatusEnum.AGREED) {
      showSubmitGuide.value = true
    } else {
      showSubmitGuide.value = false
    }
  } else {
    showSubmissionGuide()
  }
})
</script>

<style scoped>
:deep(.el-textarea__inner) {
  font-size: 15px;
  line-height: 1.6;
}

:deep(.el-input__inner) {
  font-size: 16px;
}

/* 渐变背景文字 */
.text-transparent {
  -webkit-text-fill-color: transparent;
}
</style>
