<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton size="sm" color="primary" class="mr-auto" :to="{name: 'admin-team'}">برگشت به صفحه قبل</CButton>
      <CButton v-if="$route.params.team === 'new'" size="sm" color="success" class="mr-1" @click="post">افزودن</CButton>
      <CButton v-else size="sm" color="success" class="mr-1" @click="update">بروزرسانی</CButton>
    </CustomSubHeader>
    <CRow>
      <CCol lg="6">
        <CCard>
          <CCardBody>
            <CForm>
              <h4>شماره ترتیب نمایش</h4>
              <el-divider></el-divider>
              <el-select v-model="team.index" filterable>
                <el-option v-for="index in 10000" :key="index" :label="index" :value="index" v-if="checkIndexes(index)"/>
              </el-select>
              <p class="text-danger" v-if="validation.index">{{ validation.index.msg }}</p>
              <h4 class="mt-5">فارسی</h4>
              <el-divider></el-divider>
              <CInput
                  :class="validation.fa_first_name ? 'err' : null"
                  label="نام فارسی"
                  :description="validation.fa_first_name ? validation.fa_first_name.msg : null"
                  v-model="team.locale.fa.first_name"
              />
              <CInput
                  :class="validation.fa_last_name ? 'err' : null"
                  label="نام خانوادگی فارسی"
                  :description="validation.fa_last_name ? validation.fa_last_name.msg : null"
                  v-model="team.locale.fa.last_name"
              />
              <CInput
                  :class="validation.fa_position ? 'err' : null"
                  label="سمت فارسی"
                  :description="validation.fa_position ? validation.fa_position.msg : null"
                  v-model="team.locale.fa.position"
              />


              <h4 class="mt-5">انگلیسی</h4>
              <el-divider></el-divider>
              <CInput
                  :class="validation.en_first_name ? 'err' : null"
                  label="نام انگلیسی"
                  :description="validation.en_first_name ? validation.en_first_name.msg : null"
                  v-model="team.locale.en.first_name"
              />
              <CInput
                  :class="validation.en_last_name ? 'err' : null"
                  label="نام خانوادگی انگلیسی"
                  :description="validation.en_last_name ? validation.en_last_name.msg : null"
                  v-model="team.locale.en.last_name"
              />
              <CInput
                  :class="validation.en_position ? 'err' : null"
                  label="سمت انگلیسی"
                  :description="validation.en_position ? validation.en_position.msg : null"
                  v-model="team.locale.en.position"
              />

            </CForm>
          </CCardBody>
        </CCard>
      </CCol>
      <CCol lg="6">
        <CCard>
          <CCardBody>
            <h2>تصویر</h2>
            <el-divider></el-divider>
            <img :src="team.image" alt="" style="width: 100%;max-width: 600px;">
            <input type="file" ref="image" @change="preview">
            <p class="text-danger" v-if="validation.image">{{ validation.image.msg }}</p>
          </CCardBody>
        </CCard>
      </CCol>
    </CRow>
  </div>
</template>

<script>
export default {
  data() {
    return {
      teams: null,
      team: null,
      validation: {}
    }
  },
  computed: {
    title() {
      return this.$route.params.team === 'new' ? 'افزودن عضو جدید' : 'مشاهده اطلاعات شخص'
    }
  },
  methods: {
    preview() {
      this.team.image = URL.createObjectURL(event.target.files[0])
    },
    post() {
      this.validation = {}

      const data = new FormData()
      data.append('index', this.team.index)

      data.append('fa_first_name', this.team.locale.fa.first_name)
      data.append('en_first_name', this.team.locale.en.first_name)

      data.append('fa_last_name', this.team.locale.fa.last_name)
      data.append('en_last_name', this.team.locale.en.last_name)

      data.append('fa_position', this.team.locale.fa.position)
      data.append('en_position', this.team.locale.en.position)

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

      this.$axios.post(`/api/admin/team`, data, this.axiosConfig)
          .then(response => {
            this.$message({
              type: 'success',
              message: 'عضو با موفقیت ایجاد شد.'
            })
            this.$router.push({name: 'admin-team'})
          })
          .catch(err => {
            if (err.response.status === 401) {
              return this.$message({
                type: 'error',
                message: 'لطفا دوباره وارد سیستم شوید.'
              })
            }
            if (err.response.status === 422) {
              this.validation = err.response.data.validation
              return this.$message({
                type: 'warning',
                message: 'پارامتر ها رو بررسی و دوباره تلاش کنید'
              })
            } else console.log(err.response.data)
          })
    },
    update() {
      this.validation = {}
      const data = new FormData()
      data.append('index', this.team.index)

      data.append('fa_first_name', this.team.locale.fa.first_name)
      data.append('en_first_name', this.team.locale.en.first_name)

      data.append('fa_last_name', this.team.locale.fa.last_name)
      data.append('en_last_name', this.team.locale.en.last_name)

      data.append('fa_position', this.team.locale.fa.position)
      data.append('en_position', this.team.locale.en.position)

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

      this.$axios.put(`/api/admin/team/${this.team._id}`, data, this.axiosConfig)
          .then(response => {
            this.$message({
              type: 'success',
              message: 'اطلاعات بروزرسانی شد.'
            })
            this.$refs.image.value = null
            this.$nuxt.refresh()
          })
          .catch(err => {
            if (err.response.status === 401) {
              return this.$message({
                type: 'error',
                message: 'لطفا دوباره وارد سیستم شوید.'
              })
            }
            if (err.response.status === 422) this.validation = err.response.data.validation
            else console.log(err.response.data)
          })
    },
    checkIndexes(index) {
      return Boolean(!this.teams.filter(item => item.index === index).length)
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  layout: 'admin',
  async asyncData({$axios, params, error}) {
    try {
      const teams = await $axios.get(`/api/public/teams`)
      if (params.team !== 'new') {
        const team = await $axios.get(`/api/public/team/${params.team}`)
        return {
          teams: teams.data,
          team: team.data
        }
      } else {
        return {
          teams: teams.data,
          team: {
            locale: {
              fa: {
                first_name: '',
                last_name: '',
                position: ''
              },
              en: {
                first_name: '',
                last_name: '',
                position: ''
              }
            },
            image: '',
            index: ''
          }
        }
      }
    } catch (e) {
      error({status: 404, message: 'page not found'})
    }
  }
}
</script>

