<template>
  <div v-if="!loading" class="box-border pb-110">
    <div v-if="!previewOptions.show">
      <CreateNoteHeaderBanner v-model:bannerUrl="noteJson.travelNotesBanner" />
      <div class="mt-12">
        <van-cell-group class="border" inset>
          <van-field
            style="font-size: 16px; font-weight: 600"
            size="large"
            v-model="noteJson.projectTitle"
            rows="1"
            autosize
            clearable
            type="textarea"
            @update:model-value="handleInsertOrEditProjectTitle"
            placeholder="从这里开始游记大标题..."
            maxlength="50"
            show-word-limit
          ></van-field>
        </van-cell-group>
      </div>
      <CreateNoteForm
        v-model:departureTime="noteJson.departureTime"
        v-model:countTimes="noteJson.countTimes"
        v-model:endPlace="noteJson.endPlace"
        v-model:endPlaceId="noteJson.endPlaceId"
        v-model:role="noteJson.role"
        v-model:travelMode="noteJson.travelMode"
        v-model:averageCost="noteJson.averageCost"
        v-model:recommendationRate="noteJson.recommendationRate"
        v-model:travelNumber="noteJson.travelNumber"
      />

      <div class="flex items-center pl-16 pt-16 w-full h-40">
        <div class="w-2 h-14 bg-[#FF9300] mr-8"></div>
        <h1 class="text-sm font-bold">编辑游记文章</h1>
      </div>

      <VueDraggable
        :scroll="true"
        :handle="'.drag'"
        v-model="noteJson.travelNotesContent"
        :options="dragOptions"
      >
        <template v-for="(item, index) in noteJson.travelNotesContent" :key="item.tmpId">
          <div v-if="item.type === defaultSectionTitle.type" class="mb-12 box-border">
            <van-cell-group
              class="min-h-50 border flex h-full focus:border-[#FF9300] active:shadow-[_0px_6px_4px_0px_rgba(0,0,0,0.25)]"
              inset
            >
              <van-field
                v-model="item.content"
                rows="1"
                autosize
                class="text-base h-full"
                type="textarea"
                trigger="onChange"
                maxlength="30"
                validate-trigger="onChange"
                placeholder="请输入段落标题..."
                @click-input="handleInsertOrEditTitleIndex(index)"
                @update:model-value="handleInsertOrEditTitle"
              >
                <template #extra>
                  <div class="flex">
                    <div class="h-16 drag flex mr-10 items-center">
                      <img class="w-16 h-16" src="~/assets/img/note-create/drag.svg" alt="" />
                      <span class="text-sm text-black-3">拖拽</span>
                    </div>
                    <div class="w-16 h-16 z-0">
                      <img
                        @click="handleDeleteTitle(index)"
                        class="w-full h-full"
                        src="~/assets/img/note-create/delete.svg"
                        alt=""
                      />
                    </div>
                  </div>
                </template>
              </van-field>
            </van-cell-group>
          </div>

          <div
            v-else-if="item.type === defaultSectionContent.type"
            class="mb-12 relative box-border"
          >
            <van-cell-group
              class="border min-h-100 active:shadow-[_0px_6px_4px_0px_rgba(0,0,0,0.25)]"
              inset
            >
              <van-field
                autofocus
                v-model="item.content"
                rows="3"
                autosize
                maxlength="5000"
                class="text-base"
                type="textarea"
                trigger="onChange"
                validate-trigger="onChange"
                placeholder="请在这里输入游记正文..."
                @click-input="handleInsertOrEditTitleIndex(index)"
                @update:model-value="handleInsertOrEditTitle"
              >
                <template #extra>
                  <div class="flex">
                    <div class="h-16 drag flex mr-10 items-center">
                      <img class="w-16 h-16" src="~/assets/img/note-create/drag.svg" alt="" />
                      <span class="text-sm text-black-3">拖拽</span>
                    </div>
                    <div class="w-16 h-16 z-0">
                      <img
                        @click="handleDeleteTitle(index)"
                        class="w-full h-full"
                        src="../../assets/img/note-create/delete.svg"
                        alt=""
                      />
                    </div>
                  </div>
                </template>
              </van-field>
            </van-cell-group>
          </div>
          <!-- 有图片的样式 -->
          <div v-else-if="item.type === defaultSectionImage.type" class="relative box-border mb-12">
            <template v-if="item.content">
              <div>
                <van-cell-group
                  class="border h-full active:shadow-[_0px_6px_4px_0px_rgba(0,0,0,0.25)]"
                  inset
                >
                  <div v-if="item.content">
                    <img :src="item.content" alt="Uploaded Image" />
                  </div>
                </van-cell-group>
                <div
                  class="w-150 rounded-xl box-border px-10 h-20 flex justify-between items-center h-16 absolute top-12 right-26 z-100 bg-[#fff]/[0.5]"
                >
                  <span @click="handleSaveCover(item)" class="text-sm text-black-3">
                    设为封面图
                  </span>
                  <div class="drag flex items-center border-r-[1px] border-[#F3F3F3] pr-7">
                    <img class="w-16 h-16" src="~/assets/img/note-create/drag.svg" alt="" />
                    <span class="text-sm text-black-3">拖拽</span>
                  </div>

                  <div class="w-16 h-16 inline-block">
                    <img
                      @click="handleDeleteImage(index)"
                      class="w-full h-full"
                      src="../../assets/img/note-create/delete.svg"
                      alt=""
                    />
                  </div>
                </div>
              </div>
            </template>
            <!-- 没有图片的样式 -->
            <template v-else>
              <div class="h-200">
                <van-cell-group
                  class="border h-full active:shadow-[_0px_6px_4px_0px_rgba(0,0,0,0.25)]"
                  inset
                >
                  <div class="w-full h-full flex justify-center items-center">
                    <button
                      @click="handleSelectImage(index)"
                      class="box-border active:bg-[#000]/[0.1] text-base flex justify-center items-center px-28 py-10 rounded-full border"
                    >
                      <div class="h-16 w-16 mr-8">
                        <img class="w-full h-full" src="~/assets/img/note-create/img.svg" alt="" />
                      </div>

                      插入图片
                    </button>
                  </div>
                </van-cell-group>

                <div
                  class="w-136 flex justify-between items-center h-16 absolute top-10 right-26 z-100"
                >
                  <span @click="showToast('请上传图片')" class="text-sm text-black-3">
                    设为封面图
                  </span>
                  <div class="drag flex pr-7 items-center">
                    <img class="w-16 h-16" src="~/assets/img/note-create/drag.svg" alt="" />
                    <span class="text-sm text-black-3">拖拽</span>
                  </div>

                  <div class="w-16 h-16 inline-block">
                    <img
                      @click="handleDeleteImage(index)"
                      class="w-full h-full drag"
                      src="~/assets/img/note-create/delete.svg"
                      alt=""
                    />
                  </div>
                </div>
              </div>
            </template>
          </div>
        </template>
      </VueDraggable>

      <div class="px-16 flex justify-between">
        <button
          @click="handleInsertOrEditTitleOk(defaultSectionTitle)"
          class="w-110 active:bg-[#000]/[0.1] h-44 box-border text-base text-black-3 flex justify-center rounded-md items-center bg-[#F3F3F3]"
        >
          <van-icon name="plus" class="mr-5" color="#FF9300" />
          插入小标题
        </button>
        <button
          @click="handleInsertOrEditTitleOk(defaultSectionContent)"
          class="w-110 h-44 active:bg-[#000]/[0.1] box-border text-base text-black-3 flex justify-center rounded-md items-center bg-[#F3F3F3]"
        >
          <van-icon name="plus" class="mr-5" color="#FF9300" />
          插入内容
        </button>
        <button
          @click="handleInsertOrEditTitleOk(defaultSectionImage)"
          class="w-110 active:bg-[#000]/[0.1] h-44 box-border text-base text-black-3 flex justify-center rounded-md items-center bg-[#F3F3F3]"
        >
          <van-icon name="plus" class="mr-5" color="#FF9300" />
          插入图片
        </button>
      </div>

      <div
        class="fixed box-border px-16 pt-16 pb-31 shadow-[0_-4px_4px_0px_rgba(0,0,0,0.1)] bottom-0 left-0 w-full h-80 flex justify-between bg-white items-center"
      >
        <div class="flex justify-start items-center h-50">
          <div class="w-50 text-center" @click="showDialog(draftDialogContent)">
            <van-icon :name="draft" size="20px" />
            <p class="text-sm text-black-3">草稿</p>
          </div>
          <div class="w-50 text-center" @click="handlePreview">
            <van-icon name="eye-o" size="24px" />
            <p class="text-sm text-black-3">预览</p>
          </div>
        </div>

        <van-button
          class="w-full h-full flex items-center"
          size="large"
          type="primary"
          round
          color="#FD9A00"
          block
          :loading="publishLoading"
          @click="handlePublish"
        >
          <template #icon>
            <van-image width="22" height="22" :src="upload" />
          </template>
          发布
        </van-button>
      </div>
    </div>

    <div v-else class="w-full h-full">
      <div class="p-16">
        <img
          v-if="defaultNoteJson?.travelNotesBanner"
          :src="defaultNoteJson?.travelNotesBanner"
          class="aspect-[316/204] w-full object-cover rounded-lg"
        />
        <img
          v-else
          src="~/assets/img/note-create/note_create_banner_bg.png"
          class="aspect-[316/204] w-full object-cover rounded-lg"
        />

        <div class="flex mt-10">
          <img src="~/assets/img/article_title.png" class="w-[32px] h-[32px] shrink-0" alt="" />

          <div
            class="w-321 line-clamp-2 overflow-hidden truncate max-w-xs ml-10 text-xl whitespace-normal font-bold text-black-3"
          >
            {{ defaultNoteJson?.projectTitle ?? '游记标题' }}
          </div>
        </div>
        <div class="flex justify-end text-[#999] text-[12px]">
          {{ defaultNoteJson.createTime }}
        </div>
        <div
          class="relative border-2 border-dashed border-[#E3E3E3] pt-15 pb-15 mt-12 rounded-lg pl-20 text-[#4B99EA] text-[12px]"
          :style="{ background: `url(${dashBorder2})`, backgroundSize: '100% 100%' }"
        >
          <div class="">
            <van-row>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/date.png" alt="" />
                  <div class="font-bold leading-[20px]">出发时间/</div>
                  <div class="leading-[20px] flex-1">
                    {{ defaultNoteJson?.departureTime || '' }}
                  </div>
                </div>
              </van-col>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/time.png" alt="" />
                  <div class="font-bold leading-[20px]">出发天数/</div>
                  <div class="leading-[20px] flex-1">{{ defaultNoteJson?.countTimes || '' }}</div>
                </div>
              </van-col>
            </van-row>
          </div>
          <div class="mt-24">
            <van-row>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img
                    class="w-[20px] h-[20px] mr-5"
                    src="~/assets/img/yj/relationship.png"
                    alt=""
                  />
                  <div class="font-bold leading-[20px]">人物关系/</div>
                  <div class="leading-[20px] flex-1">{{ defaultNoteJson?.role || '' }}</div>
                </div>
              </van-col>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/money.png" alt="" />
                  <div class="font-bold leading-[20px]">人均费用/</div>
                  <div class="leading-[20px] flex-1">{{ defaultNoteJson?.averageCost || '' }}</div>
                </div>
              </van-col>
            </van-row>
          </div>
          <div class="mt-24">
            <van-row>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/plan.png" alt="" />
                  <div class="font-bold leading-[20px]">出行方式/</div>
                  <div class="leading-[20px] flex-1">
                    {{ defaultNoteJson?.travelMode || '' }}
                  </div>
                </div>
              </van-col>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/target.png" alt="" />
                  <div class="font-bold leading-[20px]">目的地/</div>
                  <div class="leading-[20px] flex-1">
                    {{ defaultNoteJson?.endPlace || '' }}
                  </div>
                </div>
              </van-col>
            </van-row>
          </div>
          <div class="mt-24">
            <van-row>
              <van-col span="12">
                <div class="w-[90%] flex">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/person.png" alt="" />
                  <div class="font-bold leading-[20px]">游玩人数/</div>
                  <div class="leading-[20px] flex-1">{{ defaultNoteJson?.travelNumber || '' }}</div>
                </div>
              </van-col>
              <van-col span="12">
                <div class="w-[90%] flex text-[#FD9A00]">
                  <img class="w-[20px] h-[20px] mr-5" src="~/assets/img/yj/star.png" alt="" />
                  <div class="font-bold leading-[20px]">推荐指数/</div>
                  <div class="leading-[20px] flex-1">
                    {{ defaultNoteJson?.recommendationRate || '' }}
                  </div>
                </div>
              </van-col>
            </van-row>
          </div>
        </div>
        <div class="mt-10" v-for="con in defaultNoteJson.travelNotesContent" :key="con.id">
          <template v-if="con.type == 'image'">
            <img :src="con.content" class="w-[full] rounded-xl" alt="" />
          </template>

          <template v-else>
            <div class="text-sm text-black-3" v-html="con.content"></div>
          </template>
        </div>
      </div>
      <div
        style="justify-content: space-between"
        class="fixed box-border mb-15 p-16 shadow-[0_-4px_4px_0px_rgba(0,0,0,0.1)] bottom-0 left-0 w-full h-80 flex justify-between bg-white items-center"
      >
        <div class="w-165">
          <van-button
            @click="handlePreview"
            style="color: #fd9a00"
            class="w-full h-full flex items-center"
            size="large"
            type="primary"
            round
            color="#FFF7E6"
          >
            继续编辑
          </van-button>
        </div>

        <div class="w-165">
          <van-button
            class="w-full h-full flex items-center"
            size="large"
            type="primary"
            round
            color="#FD9A00"
            block
            :loading="publishLoading"
            @click="handlePublish"
          >
            <template #icon>
              <van-image width="22" height="22" :src="upload" />
            </template>
            确定发布
          </van-button>
        </div>
      </div>
    </div>
    <CreateNoteUserInfoModal
      v-model:visible="userInfoOptions.show"
      @submit-ok="handleCollectUserInfoOk"
    />
    <CreateNotePublishResultModal v-model:visible="publishResultModalOptions" />
  </div>
</template>

<script setup>
import { useFileDialog } from '@vueuse/core'
import upload from '~/assets/img/note-create/upload.svg'
import draft from '~/assets/img/note-create/draft.svg'
// import { cloneDeep } from 'lodash-es'
import { VueDraggable } from 'vue-draggable-plus'

import { nanoid } from 'nanoid'

const dragOptions = {
  disabled: false, // 是否禁用拖拽
  animation: 150 // 拖拽时的动画效果持续时间
}

const { open, onChange } = useFileDialog({
  accept: '.png,.png,.jpeg,.JPG,Png '
})

const { loading, setLoading } = useLoading()
loading.value = false

const defaultSectionTitle = {
  type: 'sectionTitle',
  content: ''
}
const defaultSectionContent = {
  type: 'sectionContent',
  content: ''
}
const defaultSectionImage = {
  type: 'image',
  content: ''
}

const defaultNoteJson = {
  travelNotesBanner: null,
  projectTitle: null,
  departureTime: null,
  countTimes: null,
  endPlaceId: null,
  endPlace: null,
  role: null,
  travelMode: null,
  averageCost: null,
  recommendationRate: null,
  travelNumber: null,
  travelNotesContent: []
}
const noteJson = reactive(defaultNoteJson)

watch(noteJson, () => {}, { deep: true, immediate: true })

const id = useRouteQuery('id')

// onMounted(() => {
//   getPlaceOptions()
// }),
watch(
  id,
  () => {
    getNoteDetail()
  },
  { immediate: true }
)

// 删除的弹窗内容
const deleteDialogContent = {
  title: '温馨提示',
  message: '是否删除',
  confirmButtonColor: '#FF9300'
}

// 保存草稿的弹窗内容
const draftDialogContent = {
  title: '是否保存到草稿箱',
  message: '保存后，可在“我的-我的游记-草稿箱”查看',
  confirmButtonText: '保存草稿',
  confirmButtonColor: '#FF9300',
  cancelButtonText: '不保存'
}

// 显示弹窗
const showDialog = (parmas) => {
  showConfirmDialog(parmas)
    .then(() => {
      handleSaveDraft()
    })
    .catch(() => {})
}

// // 获取目的地
// const placeOptions = ref([])
// async function getPlaceOptions() {
//   const { data } = await request('/website/tourism/publishTravelNotes/getWriteBelongTab')
//   placeOptions.value = data
// }

// 获取草稿详情
async function getNoteDetail() {
  try {
    setLoading(true)
    const res = await request(
      `/website/tourism/publishTravelNotes/getDraftDetail?writeId=${id.value}`
    )
    const data = res.data ?? {}
    Object.keys(noteJson).forEach((key) => {
      noteJson[key] = data[key]
      noteJson.travelNotesContent = data.travelNotesContent ?? []
      if (noteJson.travelNotesContent.length === 0) {
        noteJson.travelNotesContent.push({
          type: defaultSectionContent.type,
          content: '',
          tmpId: nanoid()
        })
      }
    })

    // placeOptions.value.find(item=>item.id)
    if (data?.endPlaceDictMap?.id) {
      noteJson.endPlaceId = data?.endPlaceDictMap?.id
      noteJson.endPlace = data?.endPlaceDictMap?.name
    }
    if (data?.endPlaceDictMap?.name) {
      noteJson.endPlace = data?.endPlaceDictMap?.name
      noteJson.endPlaceId = data?.endPlaceDictMap?.id
    }

    setLoading(false)
  } catch (error) {
    setLoading(false)
  }
}

/************ 插入段落标题逻辑 ********** */
const insertTilteOptions = reactive({
  show: false,
  content: null,
  editIndex: null
})

const editIndex = ref(null)

// 点击那个插入的内容那个就是框的下标
function handleInsertOrEditTitleIndex(index) {
  editIndex.value = index
}

// 点击编辑大标题，
function handleInsertOrEditProjectTitle(value) {
  noteJson.travelNotesContent.projectTitle = value
}
// 点击编辑或者新增段落标题，弹出dialog
function handleInsertOrEditTitle(value) {
  noteJson.travelNotesContent[editIndex.value].content = value
}

// 确认编辑或者新增段落标题
function handleInsertOrEditTitleOk(newTitle) {
  noteJson.travelNotesContent.push({
    ...newTitle,
    tmpId: nanoid()
  })
}

// 删除段落标题
function handleDeleteTitle(index) {
  showConfirmDialog(deleteDialogContent)
    .then(() => {
      noteJson.travelNotesContent.splice(index, 1)
    })
    .catch(() => {})
}

/******************插入正文相关逻辑*******************/

// 单个点击上传图片的事件
const handleSelectImage = (index) => {
  handleInsertOrEditTitleIndex(index)
  open()
}

onChange(async (files) => {
  if (!files.length) return

  const formData = new FormData()
  formData.append('uploadFile', files[0])
  formData.append('asImage', true)
  formData.append('fieldName', 'travelNotesBanner')
  const maxSize = 5 * 1024 * 1024 // 10 MB
  if (files[0].size > maxSize) {
    showToast('上传图片过大，请重新上传')
    return
  } else {
    try {
      showLoadingToast({
        message: '图片上传中...',
        duration: 1000000
      })

      const { data } = await request('/admin/app/tourismProjectTravelNotesWrite/upload', {
        method: 'post',
        body: formData
      })
      const url = data.fileUrl
      if (noteJson.travelNotesContent[editIndex.value].type == 'image') {
        noteJson.travelNotesContent[editIndex.value].content = url
        closeToast()
      }
    } catch (error) {
      closeToast()
      showToast('图片上传失败')
    }
  }
})

/******************插入图片逻辑*******************/

function handleDeleteImage(index) {
  showConfirmDialog(deleteDialogContent)
    .then(() => {
      if (noteJson.travelNotesContent[index].type === 'image') {
        noteJson.travelNotesContent.splice(index, 1)
      }
    })
    .catch(() => {})
}

// 设为封面图
function handleSaveCover(item) {
  noteJson.travelNotesContent.forEach((e) => {
    if (e.type === 'image') {
      e.cover = 0
    }
    item.cover = 1
  })
  showToast('设置封面成功,保存到草稿箱或发布才生效')
}

// 保存草稿
async function handleSaveDraft() {
  let parmas = {}

  try {
    parmas = { ...noteJson }
    parmas.endPlace = noteJson.endPlaceId
    await request('/website/tourism/publishTravelNotes/saveDraft', {
      method: 'post',
      body: {
        ...parmas,
        id: id?.value
      }
    })

    showToast('草稿保存成功')
  } finally {
  }
}

// 预览
const previewOptions = reactive({
  show: false
})

function handlePreview() {
  previewOptions.show = !previewOptions.show
}

// 收集个人信息
const userInfoOptions = reactive({
  show: false
})

function handleCollectUserInfoOk() {
  requestPublish()
}

const publishResultModalOptions = ref(false)

// 发布
async function handlePublish() {
  if (!noteJson.travelNotesBanner) {
    showNotify({
      type: 'warning',
      message: '请设置游记头图',
      duration: 3000
    })
    return
  }
  if (!noteJson.projectTitle) {
    showNotify({
      type: 'warning',
      message: '请输入游记标题',
      duration: 3000
    })
    return
  }
  if (!noteJson.endPlace) {
    showNotify({
      type: 'warning',
      message: '请选择目的地',
      duration: 3000
    })
    return
  }
  if (noteJson.travelNotesContent.length === 0) {
    showNotify({
      type: 'warning',
      message: '游记内容不能为空',
      duration: 3000
    })
    return
  }

  const { data: isPerfect } = await request('/website/tourism/publishTravelNotes/isPerfect')
  if (isPerfect === 0) {
    // 需要收集个人信息
    userInfoOptions.show = true
  } else {
    requestPublish()
  }
}

const publishLoading = ref(false)

async function requestPublish() {
  let parmas = {}
  try {
    publishLoading.value = true

    parmas = { ...noteJson }
    if (noteJson.endPlaceId) {
      parmas.endPlace = noteJson.endPlaceId
    }

    await request('/website/tourism/publishTravelNotes/publishDraft', {
      method: 'post',
      body: {
        ...parmas,
        id: id.value
      }
    })

    publishResultModalOptions.value = true
    publishLoading.value = false
  } catch (error) {
    publishLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
::v-deep .van-field:focus {
  caret-color: #ff9300 !important;
  outline: none;
}
</style>
