<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton size="sm" color="success" :to="{ name: 'admin-slider-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 class="col">
            <CRow>
              <el-input v-model="search" size="medium" placeholder="جستجو" />
            </CRow>
          </CCol>
        </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 :data="filteredSlider" :default-sort="{ prop: 'date', order: 'descending' }" style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>

          <el-table-column
              label="عکس اسلایدر"
              width="">
            <template slot-scope="scope">
              <img height="130px" :src="scope.row.cover || '/img/avatar.png'" :alt="scope.row.icon">
            </template>
          </el-table-column>

          <el-table-column label="تیتر" width="180px">
            <template slot-scope="scope">
              <span style="height: 0px; display: ruby-base;">
                <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">
            <el-tag class="flagType" style="width: 80px;
text-align: center;">{{scope.row.modelType === 'ostandari' ? 'استانداری' : 'ستاد انتخابات'}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="تاریخ ایجاد" width="">
            <template slot-scope="scope">
              <span>{{ jDate(scope.row.created_at) }}</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="deleteSlider(scope.row._id)">
                <i class="far fa-trash-alt"></i>
              </CButton>
              <CButton color="success" variant="outline" :key="scope.row._id" :to="{
                  name: 'admin-slider-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="!search && slider.length>10">
      <CRow alignHorizontal="center" style="padding : 10px">
        <el-pagination :hide-on-single-page="true" layout="prev, pager, next" :page-size="10"
          :current-page.sync="curentPage" :total="slider.length">
        </el-pagination>
      </CRow>
    </CCard>
  </div>
</template>

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

  export default {
    data() {
      return {
        title: "لیست اسلایدر",
        list_title: "لیست",
        slider: null,
        search: "",
        curentPage: 1,
        skip: 0
      };
    },
    computed: {
      filteredSlider() {
        if (this.search) {
          return this.slider.filter(
            (data) =>
            data.title.toLowerCase().includes(this.search.toLowerCase())
          );
        } else {
          return this.slider.slice((this.curentPage - 1) * 10, this.curentPage * 10);
        }
      },
    },
    methods: {
      jDate(date) {
        return moment(date).format("jYYYY/jMM/jDD");
      },
      deleteSlider(id) {
        this.$confirm("اسلایدر حذف شود؟", "هشدار", {
            confirmButtonText: "بله",
            cancelButtonText: "لغو",
            type: "warning",
          })
          .then(async () => {
            this.$axios
              .delete(`/api/admin/slider/${id}`)
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "اسلایدر با موفقیت حذف شد",
                });
                this.slider = this.slider.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,
                  });
                }
                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: "عملیات لغو شد",
            });
          });
      },
    },
    head() {
      return {
        title: this.title,
      };
    },
    layout: "admin",
    async asyncData({
      $axios,
      error
    }) {
      try {
        const slider = await $axios.get(`/api/admin/slider`);
        return {
          slider: slider.data,
        };
      } catch (e) {
        if(e?.response?.status === 401){
        error({
        status: 401,
        message: 'شما اجازه دسترسی به این صفحه را ندارید'
        })
      }else{
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات بوجود آمده است",
        });
      }
      }
    },
  };
</script>