<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
    </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-input style="width : 100%" placeholder="" v-model="search.email"></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-input style="width : 100%" placeholder="" v-model="search.terms"></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.read" clearable style="width : 100%">
                      <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-input style="width : 100%" placeholder="" v-model="search.phoneNumber"></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-input style="width : 100%" placeholder="" v-model="search.nationalCode"></el-input>
                  </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="meeting.docs" :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">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>

          <el-table-column label="ایمیل" width="">
            <template slot-scope="scope">
              <span>{{ scope.row.email }}</span>
            </template>
          </el-table-column>

          <el-table-column label="وضعیت پیام" width="">
            <template slot-scope="scope">
              <el-tag :type="scope.row.read ? 'success' : 'danger'">
                {{ scope.row.read ? 'خوانده شده' : 'خوانده نشده' }}
              </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-meeting-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="meeting.totalDocs>5">
      <CRow alignHorizontal="center" style="padding : 10px">
        <el-pagination :hide-on-single-page="true" layout="prev, pager, next" :page-size="meeting.limit"
          @current-change="handleCurrentChange" :current-page.sync="meeting.page" :total="meeting.totalDocs">
        </el-pagination>
      </CRow>
    </CCard>
  </div>
</template>

<script>
  import moment from "moment-jalaali";
  const _ = require('lodash');

  export default {
    data() {
      return {
        title: "لیست پیام",
        list_title: "لیست",
        meeting: 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");
      },
      openDialog(data) {
        this.showNews = !this.showNews;
        this.newsDetails = data;
      },
      handleCurrentChange(page) {
        if (!_.isEmpty(this.search)) {
          this.handleSearch(page);
        } else {
          this.$router.push({
            name: "admin-meeting",
            params : {type : this.$route.params},
            query: {
              page: page
            }
          });
        }
      },
      handleSearch(page) {
        this.loading = true;

        const data = {
          name: this.search.name,
          email: this.search.email,
          terms: this.search.terms,
          phoneNumber: this.search.phoneNumber,
          read: this.search.read,
          nationalCode: this.search.nationalCode,
          date: this.search.date
        }

        this.$axios.post(`/api/admin/meeting/search?page=${page}`, data, this.axiosConfig)
          .then((result) => {
            this.meeting = 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)
          })
      },
      deleteSlider(id) {
        this.$confirm("پیام حذف شود؟", "هشدار", {
            confirmButtonText: "بله",
            cancelButtonText: "لغو",
            type: "warning",
          })
          .then(async () => {
            this.$axios
              .delete(`/api/admin/meeting/${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: "عملیات لغو شد",
            });
          });
      },
    },
    head() {
      return {
        title: this.title,
      };
    },
    layout: "admin",
    async asyncData({
      $axios,
      params,
      query,
      error
    }) {
      try {
        const meeting = await $axios.get(`/api/admin/meeting?page=${query.page}`);
        return {
          meeting: meeting.data,
        };
      } catch (e) {
        if(e?.response?.status === 401){
        error({
        status: 401,
        message: 'شما اجازه دسترسی به این صفحه را ندارید'
        })
      }else{
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات بوجود آمده است",
        });
      }
      }
    },
  };
</script>
