<template>
  <div>
    <el-dialog
      :title="dialogState === 1 ? 'به روزرسانی اطلاعات' : 'ساخت جایزه '"
      :visible.sync="centerDialogVisible"
      width="40%"
      center
    >
      <CRow>
        <CCol xl="12" class="my-3">
          <el-input v-model="award.title" placeholder="سر تیتر"></el-input>
          <p v-if="validation.title" class="errMsg">{{ validation.title.msg }}</p>

        </CCol>
          <CCol xl="12" class="my-3">
          <el-input v-model="award.desc" type="textarea" :rows="3" placeholder="توضیحات"> </el-input>
          <p v-if="validation.desc" class="errMsg">{{ validation.desc.msg }}</p>

        </CCol>
        <CCol xl="8" class="my-3">
          <persian-date-picker
            v-model="award.expireDate"
            display-format="jYYYY/jMM/jDD"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="تاریخ را انتخاب کنید"
            color="#065495"
          />
          <p v-if="validation.expireDate" class="errMsg">{{ validation.expireDate.msg }}</p>

        </CCol>
        <CCol xl="4" class="my-3">
          <el-input-number v-model="award.score" controls-position="right" :min="1" :max="10000"></el-input-number>
          <p v-if="validation.score" class="errMsg">{{ validation.score.msg }}</p>

        </CCol>
      </CRow>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">بستن</el-button>
        <el-button type="primary" @click="post(dialogState, award)">تایید</el-button>
      </span>
    </el-dialog>

    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0"> جوایز</CBreadcrumb>
      <CButton size="sm" color="success" @click="showDialog(0, {})" class="mr-auto">افزودن</CButton>
    </CustomSubHeader>

    <CRow>
      <CCol xl="6">
        <CCard>
          <CCardHeader>
            <slot name="header">
              <i class="fas fa-filter"></i>
              <b>فیلتر ها</b>
            </slot>
          </CCardHeader>

          <CCardBody>
            <CRow>
              <CCol sm="12">
                <h4>جستجو در لیست:</h4>
                <el-input
                  v-model="filterText"
                  clearable
                  placeholder=""
                  style="display: inline-block; max-width: 500px; margin-top: 8px"
                ></el-input>
              </CCol>
            </CRow>
          </CCardBody>
        </CCard>
      </CCol>
    </CRow>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <CIcon name="cil-grid" />
          جوایز
        </slot>
      </CCardHeader>

      <CCardBody>
        <el-table :data="filteredItems" style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>

          <el-table-column prop="score" label="امتیاز" width=""> </el-table-column>
          <el-table-column prop="title" label="سر تیتر" width=""> </el-table-column>
          <el-table-column prop="desc" label="توضیحات" width=""> </el-table-column>
          <el-table-column label="مهلت استفاده" width="">
            <template slot-scope="scope">
              {{ $jDate(scope.row.expireDate) }}
            </template>
          </el-table-column>

          <el-table-column label="تغییرات" width="110" align="center">
            <template slot-scope="scope">
              <CButton :key="scope.row._id" color="info" variant="outline" @click="showDialog(1, scope.row)">
                <i class="fa fa-pencil"></i>
              </CButton>
              <CButton :key="scope.row._id" color="danger" variant="outline" @click="deleteAward(scope.row._id)">
                <i class="fa fa-trash"></i>
              </CButton>
            </template>
          </el-table-column>
        </el-table>
      </CCardBody>
    </CCard>
  </div>
</template>

<script>
export default {
  name: 'AdminGpsAwardList',
  layout: 'admin',
  async asyncData({ $axios, error, query }) {
    try {
      const { data } = await $axios.get('/api/admin/gps/award')

      return {
        awards: data
      }
    } catch (error) {
      console.log(error)
    }
  },
  data() {
    return {
      awards: [],
      centerDialogVisible: false,
      award: {
        score: '',
        title: '',
        desc: '',
        expireDate: ''
      },
      filterText: '',
      dialogState: 0,
      validation: {}
    }
  },

  computed: {
    config() {
      return this.$config
    },
    filteredItems() {
      const filterText = this.filterText
      if (!this.filterText.length) return this.awards
      else {
        return this.awards.filter(item => {
          return item.score.includes(filterText) || item.title.includes(filterText) || item.desc.includes(filterText)
        })
      }
    }
  },
  methods: {
    showDialog(state, data) {
      if (state === 1) {
        this.dialogState = 1
        this.award = data
        this.centerDialogVisible = true
      } else {
        this.dialogState = 0
        this.award = {
          score: '',
          title: '',
          desc: '',
          expireDate: ''
        }
        this.centerDialogVisible = true
      }
    },
   deleteAward(id){
    this.$axios.delete(`/api/admin/gps/award/${id}`).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.centerDialogVisible = false
          this.$nuxt.refresh()
        })
        .catch(err => {
          if (err.response.data.status === 401) {
            return this.$message({
              type: 'warning',
              message: 'لطفا دوباره وارد حساب خود شوید'
            })
          }
          if (err.response.status === 422) this.validation = err.response.data.validation
          else {
            console.log(err)
            return this.$message({
              type: 'warning',
              message:  err.response.data.msg
            })
          }
        })
    },
    post(status, data) {
      console.log(data.expireDate);
      
      if(status === 1){
        this.$axios.put(`/api/admin/gps/award/${data._id}`,data).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })

          this.centerDialogVisible = false
          this.$nuxt.refresh()
        })
        .catch(err => {
          if (err.response.data.status === 401) {
            return this.$message({
              type: 'warning',
              message: 'لطفا دوباره وارد حساب خود شوید'
            })
          }
          if (err.response.status === 422) this.validation = err.response.data.validation
          else {
            console.log(err)
            return this.$message({
              type: 'warning',
              message:  err.response.data.msg
            })
          }
        })
      }else{
        this.$axios.post(`/api/admin/gps/award`,data).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.centerDialogVisible = false
          this.$nuxt.refresh()
        })
        .catch(err => {
          if (err.response.data.status === 401) {
            return this.$message({
              type: 'warning',
              message: 'لطفا دوباره وارد حساب خود شوید'
            })
          }
          if (err.response.status === 422) this.validation = err.response.data.validation
          else {
            console.log(err)
            return this.$message({
              type: 'warning',
              message:  err.response.data.msg
            })
          }
        })
      }
    }
  }
}
</script>
<style>
.datePickerWrapper {
  display: inline-block;
  width: 100%;

  .vpd-input-group {
    @include borderRadius(3px);
    overflow: hidden;

    input {
      &::placeholder {
        color: rgba(#000, 0.4);
      }
    }
  }
  .vpd-icon-btn {
    padding: 12px 10px !important;
  }
}
</style>
