<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
const route = useRoute();
const router = useRouter();

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 { getEsg, addEsg, updateEsg } from "@/api/esg";

const formType = ref("insert");

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

onMounted(async () => {
  if (route.query.id) {
    let res = await getEsg(route.query.id);
    if (res.code === 200) {
      form.value = res.data;
      formType.value = "update";
    }else{
      ElMessage({
        message: "取得資料失敗.",
        type: 'error',
      });
      router.push('/news/esg');
    }
  }
});

const rules = reactive({
  title: [{ required: true, message: "ESG標題必填", trigger: 'blur' }],
})

const cancelForm = () => {
  router.push('/news/esg');
};

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

      if (res.code === 200) {
        ElMessage({
          message: message,
          type: 'success',
        });
        router.push('/news/esg');
      }
    } else {
      ElMessage({
        message: "請檢查輸入資料是否正確.",
        type: 'error',
      });
      return false
    }
  })
};
</script>

<template>
  <div class="main">
    <!-- Breadcrumb: Start -->
    <div class="breadcrumb-section">
      <div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item> 最新消息 </el-breadcrumb-item>
          <el-breadcrumb-item> ESG </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div>
        <el-button type="primary" @click="$router.back()">回產業動態列表</el-button>
      </div>
    </div>
    <!-- Breadcrumb: End -->

    <el-card>
    <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>
  </el-card>
  </div>
</template>

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

.demo-drawer__footer{
  margin-top: 20px;
}
</style>