<template>
  <CommonPage show-footer back>
    <template #action>
      <NButton type="primary" @click="handleEdit">
        保存文章
      </NButton>
    </template>

    <div class="editor-wrap">
      <n-form
        ref="modalFormRef" class="form wh-full" label-placement="left" label-align="left" :label-width="80"
        :model="modalForm"
      >
        <n-form-item
          label="文章名称" path="title" :rule="{
            required: true,
            message: '请输入文章名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.title" />
        </n-form-item>

        <n-form-item
          label="文章分类" path="categoryId" :rule="{
            required: true,
            type: 'number',
            trigger: ['change', 'blur'],
            message: '请输入文章分类',
          }"
        >
          <n-tree-select
            v-model:value="modalForm.categoryId" :options="allCategory" label-field="title" key-field="id"
            placeholder="根分类" clearable
          />
        </n-form-item>

        <n-tabs type="line" animated>
          <template v-for="(lang, index) in langs" :key="lang">
            <n-tab-pane :name="lang" :tab="langLabel[lang]" :index="index">
              <n-form-item
                label="文章名称" path="title" :rule="{
                  required: true,
                  message: '请输入文章名称',
                  trigger: ['input', 'blur'],
                }"
              >
                <n-input v-model:value="modalForm.translations[index].title" />
              </n-form-item>
              <div class="h-450">
                <VividEditor v-model="modalForm.translations[index].content" :dark="isDark" :handle-image-upload="handleUpload" :handle-video-upload="handleVideoUpload">
                  <SlashCommand />
                  <DragHandle />
                </VividEditor>
              </div>
            </n-tab-pane>
          </template>
        </n-tabs>
      </n-form>
    </div>
  </CommonPage>
</template>

<script setup>
import { DragHandle, SlashCommand, VividEditor } from '@4dkankan/vivid'
import { useUserStore } from '@/store/index.js'
import { initTranslations, langLabel, langs } from '@/utils/translations'
import { useDark } from '@vueuse/core'
import { NButton, useThemeVars } from 'naive-ui'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import categoryApi from '../category/api'
import articleApi from './api'
import '@4dkankan/vivid/dist/style.css'

const isDark = useDark()
const vars = useThemeVars()
const modalFormRef = ref('')
const { userId } = useUserStore()
const router = useRouter()
const route = useRoute()
const modalForm = ref({
  title: '',
  categoryId: null,
  content: '',
  userId,
})
initTranslations(modalForm.value, ['title', 'content'])
onMounted(async () => {
  console.log('edit', route.params.id)
  const { data } = await articleApi.getOne(route.params.id)
  if (data) {
    modalForm.value = {
      ...modalForm.value,
      ...data,
      userId,
    }
  }
})
const allCategory = ref([])
categoryApi.getAll().then(({ data = [] }) => (allCategory.value = data))

function handleEdit() {
  modalFormRef.value?.validate((errors) => {
    if (!errors) {
      let isPass = true
      langs.value.forEach((lang) => {
        const trans = modalForm.value.translations.find(i => i.locale === lang)
        if (trans.title === '') {
          window.$message.error(`请填写文章名称${langLabel[lang]}标题！`)
          isPass = false
        }
      })
      if (isPass) {
        articleApi.update(modalForm.value)
        $message.success('保存成功！')
        router.push('/article')
      }
    }
    else {
      $message.error('请填写对应项！')
      console.log('errors', errors)
    }
  })
}

function handleUpload(file) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve) => {
    console.log('handleUpload', file)
    const data = new FormData()
    data.append('file', file)
    const res = await articleApi.uploadImage(data)
    console.log('res', res)
    resolve(res.data)
  })
}
function handleVideoUpload(file) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve) => {
    // console.log('handleUpload', file)
    const data = new FormData()
    data.append('file', file)
    const res = await articleApi.uploadImage(data)
    // console.log('res', res)
    resolve(res.data)
  })
}
</script>

<style>
.editor-wrap {
  width: 100%;
  height: 100%;
}
</style>
