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

    <CCard>
      <CCardHeader>
        <slot name="header">
          <i class="fal fa-filter"></i>
          <span style="color:#000">فیلتر</span>
        </slot>
      </CCardHeader>
      <CCardBody>
        <CRow>
          <CCol md="6">
            <CRow style="flex-direction : column;">
              <CCol class="mt-3">
                <CRow style="align-items: baseline;">
                  <CCol col="md-3" class="mb-2">
                    <span>نام</span>
                  </CCol>
                  <CCol col="md-9">
                    <el-input style="width : 100%" placeholder="" v-model="search.name"></el-input>
                  </CCol>
                </CRow>
              </CCol>
              <CCol class="mt-3">
                <CRow style="align-items: baseline;">
                  <CCol col="md-3" class="mb-2">
                    <span>دسته بندی</span>
                  </CCol>
                  <CCol col="md-9">
                    <el-select filterable clearable style="width : 100%" v-model="search.category"
                               placeholder="">
                      <el-option
                          v-for="item in foodCategories"
                          :key="item._id"
                          :value="item._id"
                          :label="item.name"/>
                    </el-select>
                  </CCol>
                </CRow>
              </CCol>
            </CRow>
          </CCol>

          <CCol md="6">
            <CRow style="flex-direction : column;">
              <CCol class="mt-3">
                <CRow style="align-items: baseline;">
                  <CCol col="md-3" class="mb-2">
                    <span>فروش به صورت عادی</span>
                  </CCol>
                  <CCol col="md-9">
                    <el-select v-model="search.sale" clearable style="width : 100%">
                      <el-option :key="1" label="بله" :value="true"></el-option>
                      <el-option :key="2" label="خیر" :value="false"></el-option>
                    </el-select>
                  </CCol>
                </CRow>
              </CCol>
              <CCol class="mt-3">
                <CRow style="align-items: baseline;">
                  <CCol col="md-3" class="mb-2">
                    <span>فروش در باشگاه مشتریان</span>
                  </CCol>
                  <CCol col="md-9">
                    <el-select v-model="search.club" clearable style="width : 100%">
                      <el-option :key="1" label="بله" :value="true"></el-option>
                      <el-option :key="2" label="خیر" :value="false"></el-option>
                    </el-select>
                  </CCol>
                </CRow>
              </CCol>
            </CRow>
          </CCol>
        </CRow>
        <CRow>
          <el-button :loading="loading" @click="handleSearch" size="small"
                     style="width: auto;margin: 25px auto auto auto;" type="primary"
                     icon="el-icon-search">
            جست و جو
          </el-button>
        </CRow>
      </CCardBody>
    </CCard>

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

          <el-table-column
              label="عکس"
              width="">
            <template slot-scope="scope">
              <img v-if="scope.row.image" :src="scope.row.image" alt="" style="width: 100px;">
              <i v-else class="fal fa-image-polaroid" style="font-size: 115px;"></i>
            </template>
          </el-table-column>

          <el-table-column
              prop="name"
              label="نام"
              width="">
          </el-table-column>

          <el-table-column
              label="قیمت"
              width="">
            <template slot-scope="scope">
              <span v-if="scope.row.price">{{ scope.row.price.toLocaleString() + ' ريال ' }}</span>
              <span v-else class="text-danger">بدون قیمت</span>
            </template>
          </el-table-column>


          <el-table-column
              label="قیمت با تخفیف"
              width="">
            <template slot-scope="scope">
              <span v-if="scope.row.static_discount">{{ (scope.row.price - (scope.row.price / 100) * scope.row.static_discount).toLocaleString() + ' ريال ' }}</span>
              <span v-else class="text-danger">{{ scope.row.price.toLocaleString() + ' ريال ' }}</span>
            </template>
          </el-table-column>

          <el-table-column
              label="تعداد موجود"
              width="">
            <template slot-scope="scope">
              <span v-if="scope.row.stock" class="text-success">{{ scope.row.stock }}</span>
              <span v-else class="text-danger">اتمام موجودی</span>
            </template>
          </el-table-column>

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

          <el-table-column
              label="امتیاز مشتریان"
              width="">
            <template slot-scope="scope">
              <span>{{ scope.row.rate }}</span>
              <i class="fas fa-star" style="color: goldenrod;"></i>
            </template>
          </el-table-column>

          <el-table-column
              label="دسته بندی"
              width="">
            <template slot-scope="scope">
              {{ getFoodCategoryName(scope.row.category) }}
            </template>
          </el-table-column>

          <el-table-column
              label="ویرایش"
              width="110"
              align="center">
            <template slot-scope="scope">
              <CButton color="danger" variant="outline" :key="scope.row._id + Math.random()" @click="remove(scope.row._id)">
                <i class="far fa-trash-alt"></i>
              </CButton>
              <CButton color="success" variant="outline" :key="scope.row._id" :to="{name: 'admin-branch-foods-food',params:
               {food: scope.row._id}}">
                <i class="far fa-eye"></i>
              </CButton>
            </template>
          </el-table-column>

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

<script>
const _ = require('lodash');
export default {
  data() {
    return {
      title: 'لیست غذاها',
      list_title: 'لیست',
      foodCategories: null,
      foods: null,
      loading : false,
      search: {},
    }
  },
  computed: {
    pageQuery() {
      return this.$route.query.page;
    }
  },
  watch: {
    pageQuery(newPage, oldPage) {
      this.$nuxt.refresh();
    }
  },
  methods: {
    handleCurrentChange(page) {
      if (!_.isEmpty(this.search)) {
        this.handleSearch(page);
      } else {
      this.$router.push({
        name: "admin-branch-foods",
        query: {
          page: page
        }
      });
      }
    },
    getFoodCategoryName(id) {
      return this.foodCategories.filter(item => item._id === id)[0].name
    },
    remove(id) {
      this.$confirm('این مورد حذف شود؟', 'هشدار', {
        confirmButtonText: 'بله',
        cancelButtonText: 'لغو',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete(`/api/admin/food/${id}`)
            .then(res => {
              this.$message({
                type: 'success',
                message: 'غذا با موفقیت حذف شد'
              })
              this.foods.docs = this.foods.docs.filter(item => item._id !== id)
            })
            .catch(err => {
              if (err.response.status === 401) {
                return this.$message({
                  type: 'error',
                  message: 'لطفا دوباره وارد سیستم شوید.'
                })
              }
              if (err.response.status === 403) {
                return this.$message({
                  type: 'error',
                  message: err.response.data.message
                })
              } else console.log(err.response.data)
            })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: 'عملیات لغو شد'
        })
      })
    },
    handleSearch(page) {
      this.loading = true;

      const data = {
        club: this.search.club,
        sale: this.search.sale,
        name: this.search.name,
        category: this.search.category,
        branchId: this.$route?.params?.branch
      }

      this.$axios.post(`/api/admin/food/search?page=${page}`, data, this.axiosConfig)
          .then((result) => {
            this.foods = result.data;
            this.loading = false;
          })
          .catch(err => {
            this.loading = false;
            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)
          })
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  layout: 'admin',
  async asyncData({$axios, query, error, params}) {
    try {
      const foodCategories = await $axios.get(`/api/public/foodCategories/getAll/${params.branch}`)
      const foods = await $axios.get(`/api/admin/food/getAll/${params.branch}?page=${query.page || 1}`)
      return {
        foodCategories: foodCategories.data,
        foods: foods.data
      }
    } catch (e) {
      if (e?.response?.status === 401) {
        error({
          status: 401,
          message: 'شما اجازه دسترسی به این صفحه را ندارید لطفا دوباره وارد شوید'
        })
      } else {
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات بوجود آمده است",
        });
      }
    }
  }
}
</script>
