<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="getUserAvatar(blogEdit.authorId)" />
      </b-media-aside>
      <b-media-body>
        <h6 class="mb-25">
          {{ getUserFullName(blogEdit.authorId) }}
        </h6>
        <b-card-text>{{ dateFormat(blogEdit.updated_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="Title" 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="Category" label-for="blog-edit-category" class="mb-2">
            <v-select id="blog-edit-category" v-model="blogEdit.tags"
              :dir="$store.state.appConfig.isRTL ? 'rtl' : 'ltr'" multiple :options="categoryOption" />
          </b-form-group>
        </b-col>
        <b-col cols="12">
          <b-form-group label="Content" 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">
              Featured Image
            </h4>
            <b-media no-body vertical-align="center" class="flex-column flex-md-row">
              <b-media-aside>
                <b-img ref="refPreviewEl" :src="getBannerImg(blogEdit.id)" height="110" width="170"
                  class="rounded mr-2 mb-1 mb-md-0" />
              </b-media-aside>
              <b-media-body>
                <small class="text-muted">Required image resolution 800x400, image size 10mb.</small>
                <b-card-text class="my-50">
                  <!-- <b-link id="blog-image-text">
                    C:\fakepath\{{ blogFile ? blogFile.name : 'banner.jpg' }}
                  </b-link> -->
                </b-card-text>
                <div class="d-inline-block">
                  <b-form-file ref="refInputEl" v-model="blogFile" accept=".jpg, .png, .gif" placeholder="Choose file"
                    @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="saveChanges">
            Save Changes
          </b-button>
          <b-link :to="{ name: 'blog-detail', params: { id: blogId } }">
            <b-button v-ripple.400="'rgba(186, 191, 199, 0.15)'" variant="outline-secondary">
              Cancel
            </b-button>
          </b-link>
        </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 useJwt from '@/auth/jwt/useJwt'
import { format } from 'date-fns'
import { zhTW } from 'date-fns/locale'

export default {
  components: {
    BCard,
    BMedia,
    BAvatar,
    BCardText,
    BMediaAside,
    BMediaBody,
    BForm,
    BLink,
    BImg,
    BRow,
    BCol,
    BButton,
    BFormGroup,
    BFormInput,
    BFormFile,
    vSelect,
    quillEditor,
  },
  directives: {
    Ripple,
  },
  data() {
    return {
      blogId: this.$route.params.id,
      blogEdit: {},
      blogFile: null,
      blogImageList: [],
      categoryOption: ['Fashion', 'Food', 'Gaming', 'Quote', 'Video'],
      statusOption: ['Published', 'Pending', 'Draft'],
      snowOption: {
        theme: 'snow',
      },
      userData: getUserData(),
    }
  },
  created() {
    useJwt.getPost('/api/user/index').then(res => {
      this.userList = res.data;
    });

    useJwt.getPost('/api/blog-image/index').then(res => {
      this.blogImageList = res.data;
    });

    useJwt.getPost('/api/blog/show', { blogId: this.blogId }).then(res => {
      this.blogEdit = res.data;
    });
  },
  setup() {
    const refInputEl = ref(null)
    const refPreviewEl = ref(null)

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

    return {
      refInputEl,
      refPreviewEl,
      inputImageRenderer,
    }
  },
  methods: {
    dateFormat(date) {
      return format(new Date(date), 'yyyy-MM-dd hh:mm', { locale: zhTW })
    },
    getUserAvatar(userId) {
      return ('/images/_/_/_/_/MessagePractise/resources/js/src/assets/images/avatars/' + userId + '-small.png');
    },
    getUserFullName(userId) {
      for (var i = 0; i < this.userList.length; i++) {
        if (this.userList[i].id == userId) {
          return this.userList[i].name;
        }
      }
      return 'none';
    },
    getBannerImg(blogId) {
      for (var i = 0; i < this.blogImageList.length; i++) {
        if (this.blogImageList[i].blogId == blogId) {
          return this.blogImageList[i].savePath;
        }
      }
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.onload = function () { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    },
    saveChanges() {
      useJwt.getPost('/api/blog/edit', {
        blogId: this.blogId,
        title: this.blogEdit.title,
        content: this.blogEdit.content,
        tags: JSON.stringify(this.blogEdit.tags),
      })
        .then(res => {
          if(res.data == 'success') {
            console.log(res.data);
          } else {
            console.log(res.data);
          }
        });

      // save image to /app/blog/banner
      var img = this.$refs.refPreviewEl.src;
      var formdata = new FormData;
      formdata.append('blogId', this.blogId);
      formdata.append('fileName', this.blogFile.name);
      formdata.append('bannerImage', this.blogFile);
      if (this.blogFile) {
        useJwt.getPost('/api/blog-image/store', formdata)
          .then(res => {
            console.log(res.data);
          });
      }
    }
  },
}
</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';
</style>
