<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <!--      <CButton size="sm" color="success" :to="{name: 'admin-foods-food',params:{food: 'new'}}" class="mr-auto">افزودن</CButton>-->
    </CustomSubHeader>
    <CCard v-if="hasPermission('super-admin')">
      <CCardBody>
        <CRow>
          <CCol col="12" sm="6">
            <CCallout color="info">
              <small class="text-muted">تعداد مشتری ها</small><br>
              <strong class="h4">{{ customers.length }}</strong>
            </CCallout>
          </CCol>
          <CCol col="12" sm="6">
            <CCallout color="danger">
              <small class="text-muted">تعداد سفارشات</small><br>
              <strong class="h4">{{ orders.length }}</strong>
            </CCallout>
          </CCol>
        </CRow>
      </CCardBody>
    </CCard>
    <CCol v-if="hasPermission('super-admin')">
      <CRow>
        <CCol sm="6">
          <CCard>
            <CCardHeader>
              <strong>
                <span>تعداد مشتریان بر اساس شغل</span>
              </strong>
            </CCardHeader>
            <CCardBody>
              <canvas id="myChart" width="400" height="400"></canvas>
            </CCardBody>
          </CCard>
        </CCol>
      </CRow>
    </CCol>
    <CCard v-if="hasPermission('super-admin')">
      <CCardHeader>
        <strong>
          <span>لیست تخفیف های ویژه امروز مورخ: </span>
          <span>{{ jDate(Date.now()) }}</span>
        </strong>
      </CCardHeader>
      <CCardBody>
        <el-table
            :data="offFoods"
            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 class="text-success" v-if="scope.row.price">{{ scope.row.price.toLocaleString() + ' ريال ' }}</span>
              <span class="text-danger" v-else>بدون قیمت</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 class="text-success" v-if="scope.row.stock">{{ scope.row.stock }}</span>
              <span class="text-danger" v-else>اتمام موجودی</span>
            </template>
          </el-table-column>

          <el-table-column
              label="درصد تخفیف"
              width="">
            <template slot-scope="scope">
              <span class="text-success" v-if="scope.row.static_discount">{{ scope.row.static_discount + '%' }}</span>
            </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="75"
              align="center">
            <template slot-scope="scope">
              <CButton color="success" variant="outline" :key="scope.row._id" :to="{name: 'admin-foods-food',params: {food: scope.row._id}}">
                <i class="far fa-eye"></i>
              </CButton>
            </template>
          </el-table-column>

        </el-table>
      </CCardBody>
    </CCard>
  </div>
</template>

<script>
import moment from "moment-jalaali"
import login from "@/pages/admin/login";

export default {
  data() {
    return {
      title: 'داشبورد',
      list_title: 'لیست',
      foodCategories: null,
      foods: null,
      idToken: '',
      permissionGranted: false,
      customers : null,
      orders : null
    }
  },
  computed: {
    offFoods() {
      return this.foods.filter(item => item.static_discount)
    },
    branchId(){
      return this.$store?.state?.admin?.branchId
    }
  },
  methods: {
    jDate(date) {
      return moment(date).format("jYYYY/jMM/jDD")
    },
    getFoodCategoryName(id) {
      return this.foodCategories.filter(item => item._id === id)[0].name
    },
    hasPermission(permission) {
      if (this.$auth.loggedIn) return this.$auth.user.permissions.includes(permission)
      else return false
    },
  },
  head() {
    return {
      title: this.title
    }
  },
  async mounted() {
    await Notification.requestPermission()
    const typePermission = await Notification.permission
    this.permissionGranted = typePermission === 'granted'

    const getAdmin = this.$auth.$state.user

    if (typePermission === 'granted') {
      if (getAdmin) {
        this.idToken = await this.$fire.messaging.getToken()

        await this.$axios.post('/api/admin/addFcmToken', {
          fcmToken: this.idToken
        })
      }
    }


   if (this.hasPermission('super-admin')){
     const counts = {};
     this.customers.forEach(function (x) { counts[x.job] = (counts[x.job] || 0) + 1; });
     let keys = Object.keys(counts).map(item => item === 'undefined' ? 'نامشخص' : item);
     let values = Object.values(counts).map(item => item === 'undefined' ? 'نامشخص' : item);

     const CHART_COLORS = {
       red: 'rgb(255, 99, 132)',
       orange: 'rgb(255, 159, 64)',
       yellow: 'rgb(255, 205, 86)',
       green: 'rgb(75, 192, 192)',
       blue: 'rgb(54, 162, 235)',
       purple: 'rgb(153, 102, 255)',
       grey: 'rgb(201, 203, 207)'
     };

     const ctx = document.getElementById('myChart');
     const myChart = new Chart(ctx, {
       type: 'pie',
       data: {
         labels: keys,
         datasets: [{
           // label: '# of Votes',
           data: values,
           backgroundColor: Object.values(CHART_COLORS),
           borderWidth: 1
         }]
       },
       options: {
         responsive: true,
         scales: {
           y: {
             beginAtZero: true
           }
         }
       }
     });
   }
  },
  layout: 'admin',
  async asyncData({$axios, error , redirect , route}) {
    try {
      const branchId = route?.params?.branch
      const requests = [
        $axios.get(`/api/public/foodCategories/getAll/${branchId}`),
        $axios.get(`/api/public/foods/getAll/${branchId}`,{progress: false}),
        $axios.get(`/api/admin/users/forReport/${branchId}`,{progress: false}),
        $axios.get(`/api/admin/order/forReport/${branchId}`,{progress: false})
      ];

      const fetch = await Promise.all(requests);

      const [foodCategories, foods, customers, orders] = fetch;

      return {
        foodCategories: foodCategories.data,
        foods: foods.data,
        customers: customers.data,
        orders: orders.data
      }
    } catch (e) {
      if (e?.response?.status === 401) {
        redirect('/admin/login')
      } else {
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات بوجود آمده است",
        });
      }
    }
  }
}
</script>
