<script setup>
import { ref, reactive, onMounted, watch } from "vue";

import ClassicEditor from "ckeditor5-custom-build/build/ckeditor.js";
const editor = ClassicEditor;
const editorConfig = ref({
  simpleUpload: {
    // The URL that the images are uploaded to.
    uploadUrl: '/adminapi/article/uploadImage',
    // // Headers sent along with the XMLHttpRequest to the upload server.
    headers: {
      'X-CSRF-TOKEN': 'CSFR-Token',
      'Authorization' : `${sessionStorage.getItem('token')}`
    }
  },
  image: {
    resize: true,
    toolbar: [
      "imageTextAlternative",
      "|",
      "imageStyle:alignLeft",
      "imageStyle:alignRight",
      "|",
      "imageStyle:alignBlockLeft",
      "imageStyle:block",
      "imageStyle:alignBlockRight",
    ],
    styles: [
      'full',
      'alignLeft',
      'alignRight',
    ],
  },
});

import { getNews, addNews, updateNews } from "@/api/news";


const props = defineProps({
  editid: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits(["close"]);

const formType = ref("insert");

const loading = ref(false);
const formRef = ref(null);
const form = ref({
  id: 0,
  title: "",
  content: "",
});

onMounted(async () => {
  if (props.editid) {
    let res = await getNews(props.editid);
    if (res.code === 200) {
      form.value = res.data;
      formType.value = "update";
    }
  }
});

const rules = reactive({
  username: [{ required: true, message: "管理員帳號必填", trigger: 'blur' }],
})

const cancelForm = () => {
  emit("close", false);
};

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let res;
      let message;
      if (formType.value === "update") {
        form.value.id = props.editid;
        res = await updateNews(form.value);
        message = "修改成功.";
      } else {
        res = await addNews(form.value);
        message = "新增成功.";
      }

      if (res.code === 200) {
        ElMessage({
          message: message,
          type: 'success',
        });
        emit("close", true);
      }
    } else {
      ElMessage({
        message: "操作失敗.",
        type: 'error',
      });
      return false
    }
  })
};
</script>

<template>
  <div>
    <el-form 
      ref="formRef" 
      :model="form" 
      status-icon 
      :rules="rules" 
      label-width="120px">
      <el-form-item label="標題" prop="title">
          <el-input v-model="form.title" />
      </el-form-item>
      <div class="">
        <ckeditor :editor="editor" v-model="form.content" :config="editorConfig"></ckeditor>
      </div>
    </el-form>
    <div class="demo-drawer__footer" style="text-align: right;">
      <el-button @click="cancelForm">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm(formRef)">{{
        loading ? '提交中 ...' : '確認'
      }}</el-button>
    </div>
  </div>
</template>

<style lang="less" scoped>
:deep(.ck-editor__editable_inline) {
    height: 400px;
}
</style>