<template>
  <div>
    <el-form label-position="top">
      <el-form-item label="标题" required>
        <el-input
          v-model="form.title"
          class="w-1/2 min-h-24"
          placeholder="请输入内容标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属版块"  required>
        <el-select v-model="form.moduleIds" multiple filterable>
          <el-option v-for="(item, index) in moduleList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面"  required>
        <UploadImage v-model:url="form.cover" :key="coverKey" type="image" />
      </el-form-item>
      <el-form-item label="内容" required>
        <div class="border border-solid border-gray-200">
          <Toolbar
            :editor="editorRef"
            :defaultConfig="{
              excludeKeys: [
                'uploadVideo'
              ]
            }"
            mode="default"
            class="border-b border-solid border-gray-200"
          />
          <div class="h-96">
            <Editor
              v-model="form.content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="editorCreated"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="router.back">返回</el-button>
        <el-button type="primary" @click="saveArticle">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { shallowRef, ref, reactive, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { request, uploadToOSS } from "@/utils";
import UploadImage from '@/components/UploadImage.vue';
import { ElMessage, ElMessageBox } from "element-plus";

const [route, router] = [useRoute(), useRouter()];

const editorRef = shallowRef();
const editorCreated = editor => {
  editorRef.value = editor;
  // nextTick(() => {
  //   const toolbar = DomEditor.getToolbar(editor)
  //   console.log(DomEditor, editor, toolbar);
  //   const curToolbarConfig = toolbar.getConfig()
  //   console.log( curToolbarConfig.toolbarKeys )
  // })
};
defineOptions({
  name: ""
});
const form = ref({
  title: "",
  moduleIds: [],
  content: "",
  sort: 0,
  cover: [],
  id: undefined
});
const editorConfig = {
  placeholder: '请输入内容....',
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        console.log(file);
        // file 即选中的文件
        const url = await uploadToOSS(file, file.name);
        // 最后插入图片
        insertFn(url, 'image');
      }
    }
  }
};
const moduleList = ref([])
const fetchModules = async () => {
  const { data } = await request.get("/articleService/module/paginate", {
    params: {
      page: 1,
      pageSize: 9999
    }
  });
  moduleList.value = data.list
};
const coverKey = ref(Date.now())
const getDetail = async () => {
  const { data } = await request.get(`/articleService/article`, {
    params: {
      id: route.query.id
    }
  })
  form.value = {
    ...form.value,
    ...data,
    cover: Array.isArray(data.cover) ? data.cover.map((v, k) => ({ name: `cover${k}.${v.split('.').at(-1)}`, url: v })) : [],
    moduleIds: (data.modules || []).map(v => v.id)
  }
  coverKey.value++

}
const saveArticle = async () => {
  if (!form.value.title || !form.value.content || !form.value.moduleIds.length) return ElMessage.error('请填选必填项')
  const req = { ...form.value }
  req.cover = req.cover.map(v => v.url)
  await request.post(form.value.id ? `/articleService/article/update` : `/articleService/article`, req)
  ElMessage.success('操作成功')
  route.query.id && getDetail()
}
onMounted(() => {
  fetchModules()
  route.query.id && getDetail()
})
</script>

<style lang="scss" scoped></style>
