
<template>
  <b-card
    v-if="Object.keys(blogEdit).length"
    class="blog-edit-wrapper">
    <!-- media -->
    <b-media
      no-body
      vertical-align="center">
      <b-media-aside class="mr-75">
        <b-avatar
          size="38"
          :src="require('@/assets/images/avatars/' + userData.id + '-small.png')" />
      </b-media-aside>
      <b-media-body>
        <h6 class="mb-25">
          {{ userData.name }}
        </h6>
        <b-card-text>{{ formatTime(blogEdit.created_at) }}</b-card-text>
      </b-media-body>
    </b-media>
    <!--/ media -->

    <!-- form -->
    <b-form class="mt-2">
      <b-row>
        <b-col md="6">
          <b-form-group
            label="標題"
            label-for="blog-edit-title"
            class="mb-2">
            <b-form-input
              id="blog-edit-title"
              v-model="blogEdit.title" />
          </b-form-group>
        </b-col>
        <b-col md="6">
          <b-form-group
            label="分類"
            label-for="blog-edit-category"
            class="mb-2">
            <v-select
              id="blog-edit-category"
              v-model="blogEdit.category"
              :dir="$store.state.appConfig.isRTL ? 'rtl' : 'ltr'"
              multiple
              :options="categoryOption" />
          </b-form-group>
        </b-col>
        <b-col cols="12">
          <b-form-group
            label="內文"
            label-for="blog-content"
            class="mb-2">
            <quill-editor
              id="blog-content"
              v-model="blogEdit.content"
              :options="snowOption" />
          </b-form-group>
        </b-col>
        <b-col
          cols="12"
          class="mb-2">
          <div class="border rounded p-2">
            <h4 class="mb-1">
              封面圖
            </h4>
            <b-media
              no-body
              vertical-align="center"
              class="flex-column flex-md-row">
              <b-media-aside>
                <b-img
                  ref="refPreviewEl"
                  :src="blogEdit.thumbnail"
                  height="110"
                  width="170"
                  class="rounded mr-2 mb-1 mb-md-0" />
              </b-media-aside>
              <b-media-body>
                <small class="text-muted">圖片建議尺寸為 800x400,容量上限為 10MB</small>
                <b-card-text class="my-50">
                  <b-link id="blog-image-text">
                    {{ blogEdit.thumbnail }}
                  </b-link>
                </b-card-text>
                <div class="d-inline-block">
                  <b-form-file
                    ref="refInputEl"
                    v-model="blogFile"
                    accept=".jpg, .png, .gif"
                    placeholder="選擇圖片"
                    @input="inputImageRenderer" />
                </div>
              </b-media-body>
            </b-media>
          </div>
        </b-col>
        <b-col
          cols="12"
          class="mt-50">
          <b-button
            v-ripple.400="'rgba(255, 255, 255, 0.15)'"
            variant="primary"
            class="mr-1"
            @click="editComment()">
            變更貼文
          </b-button>
          <b-button
            v-ripple.400="'rgba(186, 191, 199, 0.15)'"
            variant="info">
            暫存貼文
          </b-button>
        </b-col>
      </b-row>
    </b-form>
    <!--/ form -->
  </b-card>
</template>


<script>
import {
  BCard,
  BMedia,
  BAvatar,
  BCardText,
  BMediaAside,
  BMediaBody,
  BForm,
  BRow,
  BCol,
  BFormGroup,
  BFormInput,
  BImg,
  BFormFile,
  BLink,
  BButton,
} from 'bootstrap-vue'
import vSelect from 'vue-select'
import { quillEditor } from 'vue-quill-editor'
import Ripple from 'vue-ripple-directive'
import { useInputImageRenderer } from '@core/comp-functions/forms/form-utils'
import { ref } from '@vue/composition-api'
import { getUserData } from '@/auth/utils'
import moment from 'moment'
import useJwt from '@/auth/jwt/useJwt'
import ToastificationContent from "@core/components/toastification/ToastificationContent.vue";

export default {
  components: {
    BCard,
    BMedia,
    BAvatar,
    BCardText,
    BMediaAside,
    BMediaBody,
    BForm,
    BLink,
    BImg,
    BRow,
    BCol,
    BButton,
    BFormGroup,
    BFormInput,
    BFormFile,
    vSelect,
    quillEditor,
  },
  directives: {
    Ripple,
  },
  data() {
    return {
      userData: getUserData(),
      blogEdit: {},
      blogFile: null,
      categoryOption: ['台灣小吃', '美食', '熱炒店', '吃到飽'],
      statusOption: ['Published', 'Pending', 'Draft'],
      snowOption: {
        theme: 'snow',
      },
    }
  },
  created() {
    useJwt.postData('/api/message/detail', { 'id': this.$route.params.id }).then(response => {
      this.blogEdit = response.data.blog;
      this.blogEdit.category = response.data.blog.tag.split(',');
      if(this.blogEdit.author_id != this.userData.id){
        this.$router.push({ name: 'pages-blog-list' });
      }
    }).catch(error => {
      console.log(error)
    });
  },
  setup() {
    const refInputEl = ref(null)
    const refPreviewEl = ref(null)

    const { inputImageRenderer } = useInputImageRenderer(refInputEl, base64 => {
      refPreviewEl.value.src = base64
    })

    return {
      refInputEl,
      refPreviewEl,
      inputImageRenderer,
    }
  },
  methods: {
    formatTime(value) {
      return moment(value).format("LLL");
    },
    formatTag(value) {
      return value.split(",");
    },
    formatImage(value) {
      return value.includes("http") ? value : "/images/" + value;
    },
    editComment() {
      let formData = new FormData();
      formData.append('id', this.$route.params.id);
      formData.append('title', this.blogEdit.title);
      formData.append('content', this.blogEdit.content);
      formData.append('preview', "preview");
      let tag = '';
      if (this.blogEdit.category.length > 0) {
        tag = this.blogEdit.category.join(',');
      }
      formData.append('tag', tag);
      let thumbnail = this.blogFile == null ? this.blogEdit.thumbnail : this.blogFile;
      formData.append('thumbnail', thumbnail);

      useJwt.postData('/api/message/editMessage', formData).then(response => {
        this.$router.push({ name: 'pages-blog-detail', params: { id: this.$route.params.id } });
      }).catch(error => {
        console.log(error)
        this.$toast({
          component: ToastificationContent,
          props: {
            title: `錯誤`,
            icon: 'AlertTriangleIcon',
            variant: 'warning',
            text: error,
          },
        })
      });

    },
  }
}
</script>

<style lang="scss">
@import '~@resources/scss/vue/libs/vue-select.scss';
@import '~@resources/scss/vue/libs/quill.scss';
@import '~@resources/scss/vue/pages/page-blog.scss';
.custom-file-input:lang(en)~.custom-file-label::after {
  content: '選擇檔案';
}
</style>
