<template>
  <div class="container-fluid">
    <div class="row">
      <admin-title-bar :title="title">
        <el-button @click="$router.back()" type="primary">برگشت به صفحه قبل</el-button>
        <el-button type="success" @click="upload">بروزرسانی</el-button>
      </admin-title-bar>

      <div class="col-12">
        <admin-panel>
          <h2>تصویر</h2>
          <el-divider></el-divider>
          <img :src="post.cover" alt="" style="width: 100%">
          <input type="file" ref="cover" @change="preview">
          <p class="err" v-if="validation.cover">{{ validation.cover.msg }}</p>

          <el-form class="secondTitle">
            <el-form-item prop="category" :class="validation.category ? 'is-error' : ''" label="دسته بندی">
              <el-select v-model="post.category" placeholder="انتخاب کنید">
                <el-option
                    v-for="item in blogCategories"
                    :key="item._id"
                    :label="item.blogCategory_details.fa.name"
                    :value="item._id">
                </el-option>
              </el-select>
              <p class="err" v-if="validation.category">{{ validation.category.msg }}</p>
            </el-form-item>

            <el-form-item prop="published" label="وضعیت انتشار پست">
              <el-switch v-model="post.published" style="margin-right: 15px;"></el-switch>
            </el-form-item>
          </el-form>
        </admin-panel>
      </div>

      <!-- fa -->
      <div class="col-6">
        <admin-panel>
          <h2>فارسی</h2>
          <el-divider></el-divider>
          <el-form>
            <el-form-item prop="title" :class="validation.fa_title ? 'is-error' : ''" label="عنوان">
              <el-input v-model="post.post_details.fa.title"></el-input>
              <p class="err" v-if="validation.fa_title">{{ validation.fa_title.msg }}</p>
            </el-form-item>

            <el-form-item prop="short_description" :class="validation.fa_short_description ? 'is-error' : ''" label="توضیح کوتاه">
              <el-input type="textarea" v-model="post.post_details.fa.short_description"></el-input>
              <p class="err" v-if="validation.fa_short_description">{{ validation.fa_short_description.msg }}</p>
            </el-form-item>
          </el-form>

          <el-divider></el-divider>
          <h6 style="margin-bottom: 30px;">توضیحات پست</h6>
          <client-only>
            <ckeditor v-model="post.post_details.fa.description" :config="editorConfig"></ckeditor>
            <p class="err" v-if="validation.fa_description">{{ validation.fa_description.msg }}</p>
          </client-only>
        </admin-panel>
      </div>

      <!-- en -->
      <div class="col-6">
        <admin-panel>
          <h2>انگلیسی</h2>
          <el-divider></el-divider>
          <el-form>
            <el-form-item prop="title" :class="validation.en_title ? 'is-error' : ''" label="عنوان">
              <el-input v-model="post.post_details.en.title"></el-input>
              <p class="err" v-if="validation.en_title">{{ validation.en_title.msg }}</p>
            </el-form-item>

            <el-form-item prop="short_description" :class="validation.en_short_description ? 'is-error' : ''" label="توضیح کوتاه">
              <el-input type="textarea" v-model="post.post_details.en.short_description"></el-input>
              <p class="err" v-if="validation.en_short_description">{{ validation.en_short_description.msg }}</p>
            </el-form-item>
          </el-form>

          <el-divider></el-divider>
          <h6 style="margin-bottom: 30px;">توضیحات پست</h6>
          <client-only>
            <ckeditor v-model="post.post_details.en.description" :config="editorConfig_en"></ckeditor>
            <p class="err" v-if="validation.en_description">{{ validation.en_description.msg }}</p>
          </client-only>
        </admin-panel>
      </div>

    </div>
  </div>
</template>


<script>
export default {
  data() {
    return {
      post: null,
      blogCategories: null,
      editorConfig: {
        language: 'fa',
        extraPlugins: ['bidi', 'justify']
      },
      editorConfig_en: {
        language: 'en',
        extraPlugins: ['bidi', 'justify']
      },
      validation: {},
      uploading: false,
      uploadProgress: null
    }
  },
  computed: {
    title() {
      if (!this.uploading) {
        return 'ویرایش پست'
      } else {
        return this.uploadProgress
      }
    }
  },
  methods: {
    upload() {
      this.validation = {}
      const data = new FormData()

      data.append('fa_title', this.post.post_details.fa.title)
      data.append('en_title', this.post.post_details.en.title)

      data.append('fa_description', this.post.post_details.fa.description)
      data.append('en_description', this.post.post_details.en.description)

      data.append('fa_short_description', this.post.post_details.fa.short_description)
      data.append('en_short_description', this.post.post_details.en.short_description)

      data.append('published', this.post.published)
      data.append('category', this.post.category)

      if (this.$refs.cover.files[0]) data.append('cover', this.$refs.cover.files[0])

      const axiosConfig = {
        onUploadProgress: progressEvent => {
          this.uploading = true
          this.uploadProgress = 'درحال آپلود ' + Math.floor(((progressEvent.loaded / progressEvent.total) * 100)) + '%'

          if ((progressEvent.loaded / progressEvent.total) * 100 === 100) {
            this.uploading = false
          }
        }
      }
      this.$axios.put(`/api/private/blog/${this.post._id}`, data, axiosConfig)
          .then(response => {
            this.$message({
              message: 'پست با موفقیت بروزرسانی شد.',
              type: 'success'
            })
            this.post = response.data
          }).catch(error => {
        if (error.response.status === 422) {
          this.validation = error.response.data.validation
          this.$message({
            type: 'error',
            message: 'اطلاعات رو بررسی و دوباره تلاش کنید'
          })
        } else {
          this.$alert(error.response.data.message, 'خطا', {
            confirmButtonText: 'باشه',

          })
        }
      })
    },
    preview(event) {
      this.post.cover = URL.createObjectURL(event.target.files[0]);
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  layout: 'admin',
  async asyncData({$axios, params}) {
    const post = await $axios.get(`/api/public/blog/${params.post}`)
    const blogCategories = await $axios.get(`/api/public/blogCategories`)
    return {
      post: post.data,
      blogCategories: blogCategories.data
    }
  }
}
</script>
