<script setup lang="ts">
import type { BackendCaseListItemDto, BackendEditCaseDto } from '@/api/backend/case/types'
import { useResetData } from '@/hooks'
import SelectTags from '@/components/common/SelectTags/index.vue'
import type { TagItemDto } from '@/api/tag/types'
import { TagLevelEnum, TagTypeEnum } from '@/constants'
import { selectDepOrUser } from '@/utils'
import { backendEditCase } from '@/api/backend'

const emit = defineEmits<{
  refresh: []
}>()

const [form] = useResetData<{
  id: number
  sourceProject: string
  sourceType: string
  caseType: string
  integrity: string
  cultureRelation: string

  title: string
  content: string

  cultureKeywordMain: string
  cultureKeywordSecond: number[]
  yearKeywordMain: string
  yearKeywordSecond: string
  sceneKeywordMain: string
  sceneKeywordSecond: number[]
  departmentList: { id: string; name: string }[]
}>({
  id: 0,
  sourceProject: '',
  sourceType: '',
  caseType: '',
  integrity: '',
  cultureRelation: '',
  title: '',
  content: '',
  cultureKeywordMain: '',
  cultureKeywordSecond: [],
  yearKeywordMain: '',
  yearKeywordSecond: '',
  sceneKeywordMain: '',
  sceneKeywordSecond: [],
  departmentList: [],
})

const visible = ref(false)

const open = (row: BackendCaseListItemDto) => {
  visible.value = true

  form.value = {
    id: row.id,
    sourceProject: row.sourceProject,
    sourceType: row.sourceType,
    caseType: row.caseType,
    integrity: row.integrity,
    cultureRelation: row.cultureRelation,
    title: row.title,
    content: row.content,
    // 文化关键词
    cultureKeywordMain: String(row.cultureKeywordMain[0]?.id || ''),
    cultureKeywordSecond: row.cultureKeywordSecond.map((item) => item.id),
    // 年度主推关键词
    yearKeywordMain: String(row.yearKeywordMain[0]?.id || ''),
    yearKeywordSecond: String(row.yearKeywordSecond[0]?.id || ''),
    // 关联场景主关键词
    sceneKeywordMain: String(row.sceneKeywordMain[0]?.id || ''),
    sceneKeywordSecond: row.sceneKeywordSecond.map((item) => item.id),
    // 关联部门
    departmentList: row.depIdList.map((id, index) => ({
      id: String(id),
      name: row.depNameList[index] || '',
    })),
  }
}

const filterTagsFn = (tagType: TagTypeEnum, allTags: TagItemDto[]) => {
  if (tagType === TagTypeEnum.CULTURE_TAG) {
    return allTags.filter((tag) => tag.id !== Number(form.value.cultureKeywordMain))
  } else if (tagType === TagTypeEnum.YEAR_TAG) {
    return allTags.filter((tag) => tag.id !== Number(form.value.yearKeywordMain))
  } else if (tagType === TagTypeEnum.SCENE_TAG) {
    return allTags.filter((tag) => tag.id !== Number(form.value.sceneKeywordMain))
  }
  return allTags
}

// 选择部门
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个部门，请重新选择')
  }
  form.value.departmentList = departmentList
}

// 删除部门
const delDept = (id: string) => {
  form.value.departmentList = form.value.departmentList.filter((i) => i.id !== id)
}

// 数据转换
const transformData = () => {
  const {
    cultureKeywordMain,
    cultureKeywordSecond,
    yearKeywordMain,
    yearKeywordSecond,
    sceneKeywordMain,
    sceneKeywordSecond,
    departmentList,
    ...rest
  } = form.value

  const data: BackendEditCaseDto = {
    ...rest,
    tagRelationDtoList: [],
    deptId: departmentList.map((i) => i.id).join(','),
    deptName: departmentList.map((i) => i.name).join(','),
  }

  // 添加文化关键词数据
  if (cultureKeywordMain) {
    data.tagRelationDtoList.push({
      tagId: Number(cultureKeywordMain),
      type: TagTypeEnum.CULTURE_TAG,
      keywordType: TagLevelEnum.MAIN_TAG,
    })
  }
  cultureKeywordSecond.forEach((id) => {
    data.tagRelationDtoList.push({
      tagId: id,
      type: TagTypeEnum.CULTURE_TAG,
      keywordType: TagLevelEnum.SUB_TAG,
    })
  })

  // 添加年度主推关键词数据

  if (yearKeywordMain) {
    data.tagRelationDtoList.push({
      tagId: Number(yearKeywordMain),
      type: TagTypeEnum.YEAR_TAG,
      keywordType: TagLevelEnum.MAIN_TAG,
    })
  }
  if (yearKeywordSecond) {
    data.tagRelationDtoList.push({
      tagId: Number(yearKeywordSecond),
      type: TagTypeEnum.YEAR_TAG,
      keywordType: TagLevelEnum.SUB_TAG,
    })
  }

  // 添加关联场景主关键词数据
  if (sceneKeywordMain) {
    data.tagRelationDtoList.push({
      tagId: Number(sceneKeywordMain),
      type: TagTypeEnum.SCENE_TAG,
      keywordType: TagLevelEnum.MAIN_TAG,
    })
  }
  sceneKeywordSecond.forEach((id) => {
    data.tagRelationDtoList.push({
      tagId: id,
      type: TagTypeEnum.SCENE_TAG,
      keywordType: TagLevelEnum.SUB_TAG,
    })
  })
  return data
}

const loading = ref(false)

const handleSave = async () => {
  loading.value = true
  try {
    const data = transformData()
    const res = await backendEditCase(data)
    if (res.code === 200) {
      ElMessage.success('编辑成功')
      visible.value = false
    }
    visible.value = false
    emit('refresh')
  } catch (error) {
    console.log(error, 'error')
  } finally {
    loading.value = false
  }
}

defineExpose({
  open,
})
</script>

<template>
  <el-dialog v-model="visible" title="编辑" width="35vw">
    <el-scrollbar height="500px">
      <el-form :model="form" label-width="auto" class="px-3" label-position="top">
        <el-form-item label="来源项目：">
          <el-input v-model="form.sourceProject" />
        </el-form-item>
        <el-form-item label="来源类型：">
          <el-input v-model="form.sourceType" />
        </el-form-item>
        <!-- 案例类型 -->
        <el-form-item label="案例类型：">
          <el-input v-model="form.caseType" />
        </el-form-item>
        <el-form-item label="案例完整性：">
          <el-input v-model="form.integrity" />
        </el-form-item>
        <el-form-item label="企业文化关联程度：">
          <el-input v-model="form.cultureRelation" />
        </el-form-item>
        <el-form-item label="案例标题：">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="案例文本内容：">
          <el-input
            type="textarea"
            v-model="form.content"
            :maxlength="5000"
            :show-word-limit="true"
            :rows="10"
          />
        </el-form-item>

        <!-- 下面是标签等相关的 -->

        <!-- 文化关键词 -->
        <el-form-item label="文化主关键词：">
          <div class="flex items-start">
            <div class="flex flex-wrap gap-3 items-start">
              主标签
              <SelectTags v-model="form.cultureKeywordMain" />
            </div>
            <div class="flex flex-wrap gap-3 items-start ml-5">
              副标签
              <SelectTags
                v-model="form.cultureKeywordSecond"
                :max-selected-tags="3"
                :filter-tags-fn="(allTags) => filterTagsFn(TagTypeEnum.CULTURE_TAG, allTags)"
              />
            </div>
          </div>
        </el-form-item>

        <!-- 年度主推关键词 -->
        <el-form-item label="年度主推主关键词：">
          <div class="flex items-start">
            <div class="flex flex-wrap gap-3 items-start">
              主标签
              <SelectTags v-model="form.yearKeywordMain" :tagType="TagTypeEnum.YEAR_TAG" />
            </div>
            <div class="flex flex-wrap gap-3 items-start ml-5">
              副标签
              <SelectTags
                v-model="form.yearKeywordSecond"
                :tagType="TagTypeEnum.YEAR_TAG"
                :filter-tags-fn="(allTags) => filterTagsFn(TagTypeEnum.YEAR_TAG, allTags)"
              />
            </div>
          </div>
        </el-form-item>

        <el-form-item label="关联场景主关键词：">
          <div class="flex items-start">
            <div class="flex flex-wrap gap-3 items-start">
              主标签
              <SelectTags v-model="form.sceneKeywordMain" :tagType="TagTypeEnum.SCENE_TAG" />
            </div>
            <div class="flex flex-wrap gap-3 items-start ml-5">
              副标签
              <SelectTags
                v-model="form.sceneKeywordSecond"
                :max-selected-tags="4"
                :tagType="TagTypeEnum.SCENE_TAG"
                :filter-tags-fn="(allTags) => filterTagsFn(TagTypeEnum.SCENE_TAG, allTags)"
              />
            </div>
          </div>
        </el-form-item>
        <!-- 关联部门 -->
        <el-form-item label="关联部门：">
          <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>
    </el-scrollbar>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
