<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton size="sm" color="success" :to="{ name: 'admin-occasion-details', params: { details: '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.term"></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">
                    <date-picker range clearable format="YYYY-MM-DD" display-format="jMMMM jD"
                                 v-model="search.date"></date-picker>
                  </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.publish" clearable style="width : 100%" placeholder="">
                      <el-option :key="true" label="نمایش داده شود" :value="true">
                      </el-option>
                      <el-option :key="false" 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 filterable clearable style="width : 100%" v-model="search.status"
                               placeholder="">
                      <el-option :key="true" label="کامل" :value="true">
                      </el-option>
                      <el-option :key="false" 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>
        <slot></slot>
      </CCardHeader>
      <CCardBody>
        <el-table v-loading="loading" :data="occasion.docs" :default-sort="{ prop: 'date', order: 'descending' }"
                  style="width: 100%">
          <el-table-column type="index" label="#"></el-table-column>

          <el-table-column label="عنوان">
            <template slot-scope="scope">
              <span class="title">
                <el-popover placement="top-end" trigger="hover" :content="scope.row.title">
                  <i v-if="scope.row.title.length > 25" class="el-icon-info" slot="reference"></i>
                </el-popover>
                {{ scope.row.title }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="کاربر">
            <template slot-scope="scope">
              <span v-if="!$auth.user.permissions.includes('superAdmin')">{{
                  scope.row._creator.firstName + " " + scope.row._creator.lastName
                }}</span>
              <nuxt-link v-else :to="{
                  name: 'admin-users-profile',
                  params: { profile: scope.row._creator._id },
                }"><span style="color: blue;">{{
                  scope.row._creator.firstName +
                  " " +
                  scope.row._creator.lastName
                }}</span></nuxt-link>
            </template>
          </el-table-column>

          <el-table-column label="وضعیت نمایش" width="">
            <template slot-scope="scope">
              <el-tag :type="scope.row.publish ? 'primary' : 'danger'">{{
                  scope.row.publish ? "نمایش داده شود" : "نمایش داده نشود"
                }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="وضعیت مناسبت" width="">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status ? 'primary' : 'danger'">{{
                  scope.row.status ? "کامل" : "ناقص"
                }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="تاریخ شروع" width="">
            <template slot-scope="scope">
              <span>{{ jDate(scope.row.startDate) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="تاریخ پایان" width="">
            <template slot-scope="scope">
              <span>{{ jDate(scope.row.endDate) }}</span>
            </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="deleteOccasion(scope.row._id)">
                <i class="far fa-trash-alt"></i>
              </CButton>
              <CButton color="success" variant="outline" :key="scope.row._id" :to="{
                  name: 'admin-occasion-details',
                  params: { details: scope.row._id },
                }">
                <i class="far fa-eye"></i>
              </CButton>
            </template>
          </el-table-column>
        </el-table>
      </CCardBody>
    </CCard>
    <CCard class="col" v-if="occasion.totalDocs>5">
      <CRow alignHorizontal="center" style="padding : 10px">
        <el-pagination :hide-on-single-page="true" layout="prev, pager, next" :page-size="occasion.limit"
                       @current-change="handleCurrentChange" :current-page.sync="occasion.page"
                       :total="occasion.totalDocs">
        </el-pagination>
      </CRow>
    </CCard>
  </div>
</template>

<script>
import moment from "moment-jalaali";

export default {
  data() {
    return {
      title: "لیست مناسبت ها",
      list_title: "لیست",
      occasion: null,
      search: {},
      loading: false
    };
  },
  computed: {
    pageQuery() {
      return this.$route.query.page;
    }
  },
  watch: {
    pageQuery(newPage, oldPage) {
      this.$nuxt.refresh();
    }
  },
  methods: {
    jDate(date) {
      return moment(date).format("jYYYY/jMM/jDD");
    },
    deleteOccasion(id) {
      this.$confirm("پرونده خبری حذف شود؟", "اخطار", {
        confirmButtonText: "بله",
        cancelButtonText: "لغو",
        type: "warning",
      })
          .then(async () => {
            this.$axios
                .delete(`/api/admin/occasion/${id}`)
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: "پرونده خبری با موفقیت حذف شد",
                  });
                  this.$nuxt.refresh();
                })
                .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,
                    });
                  }
                  if (err.response.status === 422) {
                    return this.$message({
                      type: "error",
                      message: err.response.data.message,
                    });
                  }
                  console.log(err.response.data);
                });
          })
          .catch(() => {
            this.$message({
              type: "warning",
              message: "عملیات لغو شد",
            });
          });
    },
    handleCurrentChange(page) {
      this.handleSearch(page);
    },
    handleSearch(page) {
      this.loading = true;

      const data = {
        term: this.search.term,
        status: this.search.status,
        publish: this.search.publish,
        date: this.search.date
      }

      this.$axios.post(`/api/admin/occasion/search?page=${page || 1}`, data, this.axiosConfig)
          .then((result) => {
            this.occasion = 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, error, query}) {
    try {
      const occasion = await $axios.get(`/api/admin/occasion?page=${query.page || 1}`);

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