<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_title ? 'is-error' : ''" label="عنوان فارسی">
							<el-input v-model="formData.history_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="title" :class="validation.en_title ? 'is-error' : ''" label="عنوان انگلیسی">
							<el-input v-model="formData.history_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="title" :class="validation.fa_caption ? 'is-error' : ''" label="توضیحات فارسی">
							<el-input type="textarea" v-model="formData.history_details.fa.caption"></el-input>
							<p class="err" v-if="validation.fa_caption">{{validation.fa_caption.msg}}</p>
						</el-form-item>
						
						<el-form-item prop="title" :class="validation.en_caption ? 'is-error' : ''" label="توضیحات انگلیسی">
							<el-input type="textarea" v-model="formData.history_details.en.caption"></el-input>
							<p class="err" v-if="validation.en_caption">{{validation.en_caption.msg}}</p>
						</el-form-item>
						
						<el-form-item prop="title" :class="validation.year ? 'is-error' : ''" label="سال">
							<el-input v-model="formData.year" placeholder="سال را چهار رقمی و به شمسی وارد کنید. مثال: 1399"></el-input>
							<p class="err" v-if="validation.year">{{validation.year.msg}}</p>
						</el-form-item>
					</el-form>
				</admin-panel>
			</div>
			<div class="col-6">
				<admin-panel>
					<h2 class="secondTitle">تصویر</h2>
					<el-divider></el-divider>
					<img :src="formData.image" alt="" style="width: 100%;max-width: 400px;display: block;">
					<input type="file" ref="image" @change="preview">
					<p class="err" v-if="validation.image">{{validation.image.msg}}</p>
				</admin-panel>
			</div>
		</div>
	</div>
</template>


<script>
   export default {
      data() {
         return {
            formData: null,
            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.formData.history_details.fa.title)
            data.append('en_title', this.formData.history_details.en.title)
            data.append('fa_caption', this.formData.history_details.fa.caption)
            data.append('en_caption', this.formData.history_details.en.caption)
            data.append('year', this.formData.year)

            if (this.$refs.image.files[0]) {
               data.append('image', this.$refs.image.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/history/${this.formData._id}`, data, axiosConfig)
               .then(response => {
                  if (response.data) {
                     this.$message({
                        message: 'تغییرات با موفقیت انجام شد.',
                        type: 'success'
                     });
                  }
               }).catch(error => {
               if (error.response.status === 422) {
                  this.validation = error.response.data.validation
                  this.$message({
                     type: 'error',
                     message: 'اطلاعات رو بررسی و دوباره تلاش کنید'
                  })
               } else {
                  this.$alert(error.response.data.error.message, 'خطا', {
                     confirmButtonText: 'باشه',

                  })
               }

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