<template>
  <div>
    <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="sessions" 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"
                >
                </el-popover>
                {{
                  scope.row?.user?.firstName + " " + scope?.row?.user?.lastName
                }}
              </span>
            </template>
          </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"
                >
                </el-popover>
                {{ scope.row?.user?.mobileNumber }}
              </span>
            </template>
          </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"
                >
                </el-popover>
                {{ scope.row?.ip }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="تاریخ ورود" width="">
            <template slot-scope="scope">
              <span>{{ scope.row.LastLogin }}</span>
            </template>
          </el-table-column>
        </el-table>
      </CCardBody>
    </CCard>
    <CCard class="col">
      <CRow alignHorizontal="center" style="padding: 10px">
        <el-pagination
          :hide-on-single-page="true"
          layout="prev, pager, next"
          page-size="10"
          @current-change="change_page"
          :current-page.sync="elections.page"
          :total="length"
        >
        </el-pagination>
      </CRow>
    </CCard>
  </div>
</template>

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

export default {
  data() {
    return {
      title: "لیست انتخابات",
      list_title: "لیست",
      elections: null,
      search: {},
      parent: null,
      loading: false,
      sessions: [],
      length: null,
      page: 1,
    };
  },
  computed: {
    pageQuery() {
      return this.$route.query.page;
    },
  },

  watch: {
    pageQuery(newPage, oldPage) {
      this.$nuxt.refresh();
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    jDate(date) {
      return moment(date).format("jYYYY/jMM/jDD");
    },
    async change_page(value) {
      this.page = value;
      this.getData();
    },
    async getData() {
      try {
        const response = await this.$axios.get(
          `/api/admin/logs?page=${this.page}&limit=10`
        );
        // const data = await response.json(); // if you want to parse JSON response
        console.log(response, "res");
        this.sessions = response?.data?.logs;
        this.length = response?.data?.totalLogs;
      } catch (error) {
        console.error("Failed to fetch data:", error);
      }
    },
    deletePoll(id) {
      this.$confirm("انتخابات حذف شود؟", "اخطار", {
        confirmButtonText: "بله",
        cancelButtonText: "لغو",
        type: "warning",
      })
        .then(async () => {
          this.$axios
            .delete(`/api/admin/election/${id}`)
            .then((res) => {
              this.$message({
                type: "success",
                message: "انتخابات با موفقیت حذف شد",
              });
              this.elections.docs = this.elections.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,
                });
              }
              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,
        catId: this.search.catId,
        showInHome: this.search.showInHome,
      };

      this.$axios
        .post(`/api/admin/election/search?page=${page}`, data, this.axiosConfig)
        .then((result) => {
          this.elections = 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 }) {
    try {
      const requests = [
        $axios.get(`/api/admin/election?page=${query.page}`),
        $axios.get("/api/admin/category/getParent"),
      ];

      const fetch = await Promise.all(requests);

      let [elections, parents] = fetch;

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