<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <el-tag v-if="download._creator && download._creator.first_name" type="primary">
        <span>ایجاد یا اصلاح کننده: </span>
        <span> {{ download._creator.first_name + ' ' + download._creator.last_name }} </span>
      </el-tag>
      <CButton
        size="sm"
        color="primary"
        class="mr-auto"
        :to="{ name: 'admin-downloads-page', params: { page: $route.params.page } }"
        >برگشت به صفحه قبل</CButton
      >
      <CButton size="sm" color="success" style="margin-right: 10px" :disabled="pending" @click="upload"
        >بروزرسانی</CButton
      >
    </CustomSubHeader>
    <CRow>
      <CCol xl="6">
        <CCard>
          <CCardBody>
            <CForm>
              <CSelect
                label="دسته بندی"
                placeholder="دسته بندی را انتخاب کنید"
                horizontal
                :options="mappedCategories(dCategories)"
                :value.sync="download.category"
                :description="validation.category ? validation.category.msg : null"
                :class="validation.category ? 'err' : null"
              >
              </CSelect>

              <CInput
                v-model="download.title"
                label="عنوان"
                horizontal
                :description="validation.title ? validation.title.msg : null"
                :class="validation.title ? 'err' : null"
              />

              <CTextarea
                v-model="download.short_description"
                label="توضیح کوتاه"
                horizontal
                rows="3"
                :description="validation.short_description ? validation.short_description.msg : null"
                :class="validation.short_description ? 'err' : null"
              />

              <CRow form class="form-group" :class="validation.description ? 'err' : null">
                <CCol tag="label" sm="3" class="col-form-label">توضیحات</CCol>
                <CCol sm="9">
                  <client-only>
                    <ckeditor v-model="download.description" :config="editorConfig"></ckeditor>
                  </client-only>
                  <small v-if="validation.description" class="form-text text-muted w-100">
                    {{ validation.description.msg }}
                  </small>
                </CCol>
              </CRow>
            </CForm>
          </CCardBody>
        </CCard>
      </CCol>
      <CCol xl="6">
        <CCard>
          <CCardBody>
            <h1>تصویر:</h1>
            <el-divider />
            <CRow>
              <CCol col="12" class="mb-3">
                <img :src="download.image" alt="" style="width: 100%; max-width: 500px" />
              </CCol>
              <CCol col="1">
                <span>کاور</span>
              </CCol>
              <CCol col="11">
                <input ref="image" type="file" @change="imagePreview" />
              </CCol>
              <CCol col="11" class="mr-auto mt-3">
                <small v-if="validation.image" class="form-text alert-danger w-100">
                  {{ validation.image.msg }}
                </small>
                <small v-else class="form-text text-muted w-100">
                  بهتر است تصویر با فرمت png و پسزمینه شفاف باشد.
                </small>
              </CCol>
            </CRow>
          </CCardBody>
        </CCard>
      </CCol>
      <CCol xl="6">
        <CCard>
          <CCardHeader>
            <i class="far fa-plus"></i>
            <strong>افزودن فایل</strong>
          </CCardHeader>
          <CCardBody>
            <CForm>
              <CSelect
                label="سیستم عامل"
                placeholder="سیستم عامل را انتخاب کنید"
                horizontal
                :options="mappedOS(appOS)"
                :value.sync="app.os"
                :description="validation.os ? validation.os.msg : null"
                :class="validation.os ? 'err' : null"
              >
              </CSelect>

              <CInput
                v-model="app.name"
                label="نام"
                horizontal
                :description="validation.name ? validation.name.msg : null"
                :class="validation.name ? 'err' : null"
              />

              <CRow>
                <CCol col="3">
                  <span>فایل برنامه</span>
                </CCol>
                <CCol col="9">
                  <input ref="file" type="file" />
                </CCol>
                <CCol col="9" class="mr-auto mt-3">
                  <small v-if="validation.file" class="form-text alert-danger w-100">
                    {{ validation.file.msg }}
                  </small>
                </CCol>
              </CRow>

              <CButton color="success" class="mt-3" :disabled="pending" @click.prevent="addApp">افزودن</CButton>
            </CForm>
          </CCardBody>
        </CCard>
      </CCol>
      <CCol xl="6">
        <CCard>
          <CCardHeader>
            <i class="fas fa-list"></i>
            <strong>لیست فایل ها</strong>
          </CCardHeader>
          <CCardBody>
            <CListGroup>
              <CListGroupItem
                v-for="(item, index) in download.files"
                :key="item._id"
                target="_blank"
                download
                :href="item.file"
                :color="index % 2 ? 'light' : 'dark'"
              >
                <CRow>
                  <CCol col="11">
                    {{ item.name }}
                  </CCol>
                  <CCol col="1" style="text-align: left">
                    <i class="fas fa-trash-alt delete-btn" @click.prevent="delApp(item._id)"></i>
                  </CCol>
                </CRow>
              </CListGroupItem>
            </CListGroup>
          </CCardBody>
        </CCard>
      </CCol>
    </CRow>
  </div>
</template>

<script>
import axiosUploadProcess from '@/mixins/axiosUploadProcess'

export default {
  name: 'AddminDownloadDetails',
  mixins: [axiosUploadProcess],
  layout: 'admin',
  async asyncData({ $axios, params, error }) {
    try {
      const dCategories = await $axios.get(`/api/public/dCategory`)
      const download = await $axios.get(`/api/public/downloads/${params.item}`)
      return {
        dCategories: dCategories.data,
        download: download.data
      }
    } catch (e) {
      error({ status: 404, message: 'Page not found' })
    }
  },
  data() {
    return {
      title: 'ویراش فایل',
      dCategories: null,
      download: null,
      editorConfig: {
        language: 'fa',
        extraPlugins: ['bidi', 'justify']
      },
      app: {
        name: '',
        os: '',
        file: ''
      },
      appOS: ['windows', 'linux', 'mac', 'android', 'ios'],
      validation: {},
      uploading: false,
      uploadProgress: null,
      pending: false
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  methods: {
    upload() {
      this.pending = true
      this.validation = {}
      const data = new FormData()
      data.append('title', this.download.title)
      data.append('short_description', this.download.short_description)
      data.append('description', this.download.description)
      data.append('category', this.download.category)
      if (this.$refs.image.files[0]) data.append('image', this.$refs.image.files[0])

      this.$axios
        .put(`/api/admin/downloads/${this.download._id}`, data, this.axiosConfig)
        .then(response => {
          if (response.data) {
            this.pending = false
            this.$message({
              message: 'آیتم با موفقیت بروزرسانی شد.',
              type: 'success'
            })
            this.download = response.data
          }
        })
        .catch(error => {
          this.pending = false
          if (error.response.status === 422) {
            this.validation = error.response.data.validation
            this.$message({
              type: 'error',
              message: 'اطلاعات رو بررسی و دوباره تلاش کنید'
            })
          } else {
            this.$alert(error.response.data.message, 'خطا', {
              confirmButtonText: 'باشه'
            })
          }
        })
    },
    addApp() {
      this.pending = true
      this.validation = {}

      const data = new FormData()
      data.append('page_id', this.download._id)
      data.append('name', this.app.name)
      data.append('os', this.app.os)
      data.append('file', this.$refs.file.files[0])

      this.$axios
        .post(`/api/admin/downloads/file`, data, this.axiosConfig)
        .then(response => {
          this.pending = false
          if (response.data) {
            this.$message({
              message: 'آیتم با موفقیت افزوده شد.',
              type: 'success'
            })
            this.app = {
              name: '',
              os: '',
              file: ''
            }
            this.$refs.file.value = null
            this.download.files = response.data
          }
        })
        .catch(error => {
          this.pending = false
          if (error.response.status === 422) {
            this.validation = error.response.data.validation
            this.$message({
              type: 'error',
              message: 'اطلاعات رو بررسی و دوباره تلاش کنید'
            })
          } else {
            this.$alert(error.response.data.message, 'خطا', {
              confirmButtonText: 'باشه'
            })
          }
        })
    },
    delApp(id) {
      this.$confirm('این مورد حذف شود؟', 'هشدار', {
        confirmButtonText: 'بله',
        cancelButtonText: 'لغو',
        type: 'warning'
      })
        .then(() => {
          this.$axios
            .delete(`/api/admin/downloads/file/${id}`)
            .then(response => {
              this.download.files = this.download.files.filter(item => item._id !== id)
              this.$message({
                type: 'success',
                message: 'آیتم حذف شد'
              })
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: err.response.data.message
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'warning',
            message: 'عملیات لغو شد'
          })
        })
    },
    imagePreview(event) {
      this.download.image = URL.createObjectURL(event.target.files[0])
    },
    mappedCategories(arr) {
      return arr.map(item => {
        return {
          label: item.name,
          value: item._id
        }
      })
    },
    mappedOS(arr) {
      return arr.map(item => {
        return {
          label: item,
          value: item
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.delete-btn {
  transition: 0.1s;
  -webkit-transition: 0.1s;
  -moz-transition: 0.1s;
  -ms-transition: 0.1s;
  -o-transition: 0.1s;
  padding: 5px 10px;
  display: inline-block;
  border: 1px solid transparent;
  border-radius: 5px;

  &:hover {
    color: red;
    border-color: red;
  }
}
</style>
