<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <!--      <CButton size="sm" color="success" :to="{name: 'admin-discounts-discount',params:{profile: 'new'}}" class="mr-auto">افزودن</CButton>-->
    </CustomSubHeader>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <i class="fal fa-bars"></i>
          <span>{{ list_title }}</span>
        </slot>
      </CCardHeader>
      <CCardBody>
        <h2>افزودن کد تخفیف</h2>
        <el-divider></el-divider>
        <el-button-group>
          <el-button :type="newDiscountIsPublic ? 'info' : 'primary'" @click="newDiscountIsPublic = false" icon="el-icon-arrow-left">کد تخفیف اختصاصی</el-button>
          <el-button :type="newDiscountIsPublic ? 'primary' : 'info'" @click="newDiscountIsPublic = true" icon="el-icon-arrow-left">کد تخفیف عمومی</el-button>
        </el-button-group>
        <br>
        <el-select
            v-if="!newDiscountIsPublic"
            v-model="discount_user_id"
            filterable
            style="width: 300px;margin-top: 20px;margin-bottom: 10px;">
          <el-option
              v-for="item in users"
              :key="item._id"
              :value="item._id"
              :label="item.business_code + ' ' + '(' + item.first_name + ' ' + item.last_name + ')'"/>
        </el-select>
        <p class="text-danger" v-if="validation.discount_user_id">{{ validation.discount_user_id.msg }}</p>

        <div v-if="newDiscountIsPublic" style="margin-top: 20px;margin-bottom: 10px;">
          <el-switch
              style="direction: ltr;margin-bottom: 20px;"
              v-model="publicDiscountIsAuto"
              active-text="ایجاد کد تخفیف توسط سیستم"
              inactive-text="وارد کردن کد دستی">
          </el-switch>

          <el-input v-model="customDiscountCode" v-if="!publicDiscountIsAuto" placeholder="کدتخفیف دستی را وارد کنید" style="width: 300px;display: block;"></el-input>
          <p class="text-danger" v-if="validation.customDiscountCode">{{ validation.customDiscountCode.msg }}</p>
        </div>

        <el-input v-model="discount_amount" placeholder="درصد تخفیف را وارد کنید" style="display: block;width: 300px;margin-bottom: 10px;"></el-input>
        <p class="text-danger" v-if="validation.discount_amount">{{ validation.discount_amount.msg }}</p>

        <date-picker
            v-model="discount_expire_date"
            placeholder="تاریخ انقضای کد را مشخص کنید"
            format="X"
            displayFormat="jYYYY/jMM/jDD"
            style="display: block;width: 300px!important;margin-bottom: 10px;"/>
        <p class="text-danger" v-if="validation.discount_expire_date">{{ validation.discount_expire_date.msg }}</p>

        <el-select
            v-model="menuTypeId"
            filterable
            placeholder="منو را انتخاب کنید"
            style="width: 300px;margin-bottom: 20px;">
          <el-option
              v-for="item in menuTypes"
              :key="item._id"
              :value="item._id"
              :label="item.name"/>
        </el-select>
        <p class="text-danger" v-if="validation.menuTypeId">{{ validation.menuTypeId.msg }}</p>
        <br>
        <el-button type="success" @click="addDiscount">ایجاد کد تخفیف</el-button>
      </CCardBody>
    </CCard>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <i class="fal fa-bars"></i>
          <span>{{ list_title }}</span>
        </slot>
      </CCardHeader>
      <CCardBody>
        <el-table
            :data="discounts.docs"
            style="width: 100%">
          <el-table-column
              type="index"
              label="#">
          </el-table-column>

          <el-table-column
              prop="discount_code"
              label="کد تخفیف"
              width="">
          </el-table-column>

          <el-table-column
              label="درصد تخفیف"
              width="">
            <template slot-scope="scope">
              <span class="text-success">{{ scope.row.discount_amount + '%' }}</span>
            </template>
          </el-table-column>

          <el-table-column
              label="تاریخ انقضا"
              width="">
            <template slot-scope="scope">
              {{ jDate(scope.row.discount_expire_date) }}
            </template>
          </el-table-column>

          <el-table-column
              label="در دسترس برای"
              width="">
            <template slot-scope="scope">
              <span v-if="scope.row.isPublic" class="text-success">برای همه</span>
              <span v-else>{{ scope.row.discount_user_id.first_name + ' ' + scope.row.discount_user_id.last_name }}</span>
            </template>
          </el-table-column>

          <el-table-column
              label="حذف"
              width="75"
              align="center">
            <template slot-scope="scope">
              <CButton color="danger" variant="outline" :key="scope.row._id + Math.random()" @click="deleteUser(scope.row._id)">
                <i class="far fa-trash-alt"></i>
              </CButton>
            </template>
          </el-table-column>

        </el-table>
      </CCardBody>
    </CCard>
    <CCard class="col" v-if="discounts.totalDocs>20">
      <CRow alignHorizontal="center" style="padding : 10px">
        <el-pagination :hide-on-single-page="true" layout="prev, pager, next" :page-size="discounts.limit"
                       @current-change="handleCurrentChange" :current-page.sync="discounts.page" :total="discounts.totalDocs">
        </el-pagination>
      </CRow>
    </CCard>
  </div>
</template>

<script>
import moment from 'moment-jalaali'

export default {
  data() {
    return {
      title: 'لیست کدهای تخفیف',
      list_title: 'لیست',
      // base data
      discounts: null,
      users: null,
      menuTypes: null,
      // discount details
      discount_user_id: '',
      discount_expire_date: '',
      menuTypeId: '',
      discount_amount: '',
      customDiscountCode: '',
      newDiscountIsPublic: true,
      publicDiscountIsAuto: true,
      loading: false,
      // validation
      validation: {}
    }
  },
  watch: {
    pageQuery(newPage, oldPage) {
      this.$nuxt.refresh();
    },
    newDiscountIsPublic(newVal, oldVal) {
      this.validation = {}
    },
    publicDiscountIsAuto(newVal, oldVal) {
      this.validation = {}
    }
  },
  computed: {
    pageQuery() {
      return this.$route.query.page;
    }
  },
  methods: {
    handleCurrentChange(page) {
      // if (!_.isEmpty(this.search)) {
      //   this.handleSearch(page);
      // } else {
      this.$router.push({
        name: "admin-branch-discounts",
        query: {
          page: page
        }
      });
      // }
    },
    addDiscount() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.validation = {}
      const data = {
        discount_user_id: this.discount_user_id,
        discount_expire_date: this.discount_expire_date,
        discount_amount: this.discount_amount,
        menuTypeId: this.menuTypeId,
        customDiscountCode: this.customDiscountCode,
        newDiscountIsPublic: this.newDiscountIsPublic,
        publicDiscountIsAuto: this.publicDiscountIsAuto,
        branchId: this.$route.params.branch
      }
      this.$axios.post('/api/admin/discountCode', data)
          .then(res => {
            loading.close()
            this.$alert('', 'موفق', {
              type: 'success',
              message: `کد تخفیف: ${res.data.discount_code}`
            })
            this.discount_user_id = ''
            this.discount_expire_date = ''
            this.discount_amount = ''
            this.menuTypeId = ''
            this.customDiscountCode = ''
            this.$nuxt.refresh()
          })
          .catch(err => {
            loading.close()
            if (err.response.status === 422) return this.validation = err.response.data.validation
            else if (err.response.status === 500) error({
              status: 500,
              message: err.response.data.message,
            });
            else console.log(err)
          })
    },
    deleteUser(id) {
      this.$confirm('کد تخفیف حذف شود؟', 'هشدار', {
        confirmButtonText: 'بله',
        cancelButtonText: 'لغو',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete(`/api/admin/discountCode/${id}`)
            .then(res => {
              this.$message({
                type: 'success',
                message: 'کد تخفیف با موفقیت حذف شد'
              })
              this.discounts.docs = this.discounts.docs.filter(item => item._id !== id)
            })
            .catch(err => {
              if (err.response.status === 401) {
                return this.$message({
                  type: 'error',
                  message: 'لطفا دوباره وارد سیستم شوید.'
                })
              }
              console.log(err.response.data)
            })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: 'عملیات لغو شد'
        })
      })
    },
    jDate(date) {
      return moment(date, 'X').format('jYYYY/jMM/jDD')
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  layout: 'admin',
  async asyncData({$axios, query, error, params}) {
    try {
      const users = await $axios.get(`/api/admin/users/getAll/${params.branch}`)
      const menuTypes = await $axios.get(`/api/public/menuTypes/getAll/${params.branch}`)
      const discounts = await $axios.get(`/api/admin/discountCodes/${params.branch}?page=${query.page || 1}`)
      return {
        users: users.data,
        discounts: discounts.data,
        menuTypes: menuTypes.data
      }
    } catch (e) {
      if (e?.response?.status === 401) {
        error({
          status: 401,
          message: 'شما اجازه دسترسی به این صفحه را ندارید لطفا دوباره وارد شوید'
        })
      } else {
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات بوجود آمده است",
        });
      }
    }
  }
}
</script>


<style lang="scss">
.el-button:focus {
  outline-color: #39f !important;
}
</style>
