<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-6">
        <admin-panel>
          <el-form>
            <el-form-item prop="title" :class="validation.fa_name ? 'is-error' : ''" label="نام فارسی">
              <el-input v-model="formData.blogCategory_details.fa.name"></el-input>
              <p class="err" v-if="validation.fa_name">{{ validation.fa_name.msg }}</p>
            </el-form-item>
            <el-form-item prop="title" :class="validation.en_name ? 'is-error' : ''" label="نام انگلیسی">
              <el-input v-model="formData.blogCategory_details.en.name"></el-input>
              <p class="err" v-if="validation.en_name">{{ validation.en_name.msg }}</p>
            </el-form-item>
          </el-form>
        </admin-panel>
      </div>
    </div>
  </div>
</template>


<script>
export default {
  data() {
    return {
      formData: {
        blogCategory_details: {
          fa: {
            name: ''
          },
          en: {
            name: ''
          }
        }
      },
      validation: {},
      uploading: false,
      uploadProgress: null
    }
  },
  computed: {
    title() {
      if (!this.uploading) {
        return 'افزودن دسته بندی'
      } else {
        return this.uploadProgress
      }
    }
  },
  methods: {
    upload() {
      this.validation = {}
      const data = {
        fa_name: this.formData.blogCategory_details.fa.name,
        en_name: this.formData.blogCategory_details.en.name
      }

      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.post(`/api/private/blogCategories`, data, axiosConfig)
          .then(response => {
            if (response.data) {
              this.$message({
                message: 'دسته بندی با موفقیت ثبت شد.',
                type: 'success'
              });
              this.$router.push({name: 'admin-blog-category'})
            }
          }).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: 'باشه'
          })
        }
      })
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  layout: 'admin'
}
</script>
