<template>
  <div v-if="loading">
    <div class="q-pa-md q-py-lg">
      <q-skeleton height="40px" square style="width: 200px;" />
    </div>
    <div class="row">
      <div class="col-12 col-md-12 col-sm-12 col-xs-12">
        <div class="q-ma-md q-pa-md q-py-lg bg-grey-3">
          <q-skeleton height="40px" square />
        </div>
        <div class="q-ma-md q-pa-md q-py-lg bg-grey-3">
          <q-skeleton height="auto" square style="width: 100%;">
            <div class="q-pa-md">
              <q-markup-table>
                <thead>
                  <tr>
                    <th class="text-left" style="width: 15px">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                    <th class="text-right">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                    <th class="text-right" style="width: 20px">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                    <th class="text-right">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                    <th class="text-right">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                    <th class="text-right">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                    <th class="text-center" style="width: 50px">
                      <q-skeleton animation="blink" type="text" />
                    </th>
                  </tr>
                </thead>

                <tbody>
                  <tr v-for="n in 5" :key="n">
                    <td class="text-left">
                      <q-skeleton animation="blink" type="text" width="15px" />
                    </td>
                    <td class="text-right">
                      <q-skeleton animation="blink" type="text" width="50px" />
                    </td>
                    <td class="text-right">
                      <q-skeleton animation="blink" type="text" width="20px" />
                    </td>
                    <td class="text-right">
                      <q-skeleton animation="blink" type="text" width="50px" />
                    </td>
                    <td class="text-right">
                      <q-skeleton animation="blink" type="text" width="60px" />
                    </td>
                    <td class="text-right">
                      <q-skeleton animation="blink" type="text" width="50px" />
                    </td>
                    <td class="text-center">
                      <q-skeleton animation="blink" type="text" width="50px" />
                    </td>
                  </tr>
                </tbody>
              </q-markup-table>
            </div>
            <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-pa-xl flex flex-center">
              <q-skeleton type="rect" width="200px" />
            </div>
          </q-skeleton>
        </div>
      </div>
    </div>
  </div>
  <transition appear enter-active-class="animated slideInRight" leave-active-class="hidden" v-else>
    <div class="q-pa-sm">
      <div class="text-h5 q-pb-md">Tests</div>
      <div class="row flex flex-center">
        <div class="col-12 col-md-12">
          <div class="q-pa-mdd">
            <q-card class="my-card">
              <q-card-section>
                <q-select
                  outlined
                  v-model="selectedQbankId"
                  :options="qBankOptions"
                  label="Select Qbank"
                  emit-value
                  map-options
                  @input="fetchQbankTests($event)"
                >
                  <template v-slot:option="scope">
                    <q-item
                      v-bind="scope.itemProps"
                      v-on="scope.itemEvents"
                      class="justify-between"
                    >
                      <q-item-section>
                        <q-item-label v-html="scope.opt.label" />
                      </q-item-section>
                      <q-item-section avatar>
                        <div class="text-blue-8">( {{scope.opt.qCount}} Question)</div>
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </q-card-section>
              <q-card-section>
                <div class="text-body1">
                  Showing All Tests
                  <span v-if="qBanks.length>0">
                    For
                    <span style="font-weight:bold;" v-html="activeQbankName">'</span>
                  </span>
                </div>
              </q-card-section>
              <q-card-section class="q-ma-md">
                <q-markup-table>
                  <thead>
                    <tr>
                      <th class="text-left text-uppercase">s.no</th>
                      <th class="text-left text-uppercase">date</th>
                      <th class="text-center text-uppercase">total questions</th>
                      <th class="text-left text-uppercase">topics</th>
                      <th class="text-center text-uppercase">score</th>
                      <th class="text-center text-uppercase">STATUS</th>
                      <th class="text-center text-uppercase">ACTION</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item,index) in qbankTests" :key="item.id">
                      <td class="text-left">{{serialNo+index+1}}</td>
                      <td class="text-left">{{item.created_at}}</td>
                      <td class="text-center">{{item.questionLimit}}</td>
                      <td class="text-left text-blue-6">
                        <p v-if="item.topics.length==1">{{item.topics[0].topic.name}}</p>
                        <q-tooltip
                          content-class="bg-white text-subtitle1 text-grey-8 shadow-8"
                          anchor="top middle"
                          self="top middle"
                          v-else
                        >
                          <div class="text-bold">Multiple</div>
                          <ul>
                            <li v-for="t in item.topics" :key="t.id">{{t.topic.name}}</li>
                          </ul>
                        </q-tooltip>
                      </td>
                      <td class="text-center" v-html="testScore(item)"></td>
                      <td class="text-center">
                        <q-badge class="q-pa-xs" :color="testStatus(item)">{{item.status}}</q-badge>
                      </td>
                      <td class="text-center">
                        <a
                          @click="startTest(item)"
                          class="no-underline text-blue-5 cursor-pointer q-pa-xs"
                          v-if="isTestNotStarted(item)"
                        >{{getTestActionText(item)}}</a>
                        <a
                          @click="resumeTest(item)"
                          class="no-underline text-blue-5 cursor-pointer q-pa-xs"
                          v-else-if="isTestInProgress(item)"
                        >{{getTestActionText(item)}}</a>
                        <p v-else class="analysis-review-btn">
                          <a
                            @click="navigateToAnalysis(item.id)"
                            class="no-underline text-blue-5 cursor-pointer q-pa-xs"
                          >Analysis</a>
                          <a
                            @click="reviewTest(item)"
                            class="no-underline text-blue-5 cursor-pointer q-pa-xs"
                          >Review</a>
                        </p>
                      </td>
                    </tr>
                    <!-- <q-separator style="width:0%" inset /> -->
                  </tbody>
                </q-markup-table>
                <div class="q-pa-lg flex flex-center">
                  <q-pagination
                    v-model="currentPage"
                    :max="totalPages"
                    input
                    input-class="text-orange-10"
                  />
                </div>
              </q-card-section>
            </q-card>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import { skeleton } from "../../mixins/SkeletonMixin.js";
import { loader } from "../../mixins/LoaderMixin.js";
export default {
  mixins: [skeleton, loader],
  data() {
    return {
      showFilter: false,
      tests: [],
      qBanks: [],
      qBankOptions: [],
      selectedQbankId: 0,
      currentPage: 1,
      pageSize: 5,
      baseTestUrl: `/get-all-tests`,
      totalItems: 0,
      totalPages: 0,
    };
  },
  mounted() {
    this.getQbanks();
  },
  computed: {
    qbankTests: function () {
      let data = [...this.tests];
      this.totalItems = data.length;
      this.totalPages = Math.ceil(this.totalItems / this.pageSize);
      let startIndex = (this.currentPage - 1) * this.pageSize;
      let endIndex = Math.min(startIndex + this.pageSize, this.totalItems);

      return data.slice(startIndex, endIndex);
    },
    serialNo() {
      return (this.currentPage - 1) * this.pageSize;
    },
    activeQbankName() {
      let item = this.qBanks.find((e) => {
        return e.qbank.id == this.selectedQbankId;
      });
      if (item) {
        return `<span>${item.qbank.name} </span><span class="text-primary">(${item.subscription_history[0].subscription_type})</span>`;
      } else {
        return "NA";
      }
    },
  },
  methods: {
    getQbanks: function () {
      let t = this;
      axios
        .get("/get-user-subscribed-qbanks-list")
        .then((response) => {
          console.log(response.data);
          t.qBanks = response.data;
          t.qBanks.forEach((e) => {
            t.qBankOptions.push({
              label: t.qbankName(e),
              value: e.qbank.id,
              qCount: e.qbank.qbank_question_info.all_count,
            });
          });
          if (t.qBanks.length > 0) {
            t.selectedQbankId = t.qBanks[0].qbank.id;
          }
          t.fetchQbankTests(t.selectedQbankId);
        })
        .catch((e) => {
          this.hideSkeletonLoader();
        });
    },
    qbankName(item) {
      return (
        item.qbank.name +
        "   (  " +
        item.subscription_history[0].subscription_type +
        "  )"
      );
    },
    fetchQbankTests: function (qbank_id) {
      this.showSkeletonLoader();
      axios
        .get(this.baseTestUrl + `/${qbank_id}`)
        .then((response) => {
          this.tests = response.data;
          this.tests.forEach((e) => {
            e["topics"] = this.topics(e);
          });
          this.totalItems = this.tests.length;
          this.hideSkeletonLoader();
        })
        .catch((e) => {
          this.hideSkeletonLoader();
        });
    },
    testScore: function (item) {
      let total = item.data_test.length;
      let corrects = item.data_test.filter((e) => {
        return e.isAnswerCorrect == true;
      });
      let result = Math.round((corrects.length / total) * 100);
      return result + "%";
    },
    isTestNotStarted(item) {
      return item.status == "Not Started";
    },
    isTestInProgress(item) {
      return item.status == "Running" || item.status == "Paused";
    },
    getTestActionText(item, step = null) {
      switch (item.status) {
        case "Not Started":
          return "Start Test";
        case "End":
          return "positive";
        case "Expired":
          return "warning";
        case "Running":
          return "Go To Test";
        case "Paused":
          return "Resume";
        default:
          return "secondary";
      }
    },
    isTestComplete(item) {
      return item.isEnd || item.isExpired;
    },
    testStatus: function (item) {
      switch (item.status) {
        case "Not Started":
          return "primary";
        case "End":
          return "positive";
        case "Expired":
          return "warning";
        case "Running":
          return "info";
        default:
          return "secondary";
      }
    },
    startTest(item) {
      this.$router.push({
        name: "qbank-test-app",
        params: {
          test_id: item.id,
        },
      });
    },
    resumeTest(item) {
      this.startLoader("Processing.Please Hang on...");
      axios
        .put(`/update-qbank-test-status/${item.id}`, {
          data: { status: "Running" },
        })
        .then((response) => {
          this.stopLoader();
          this.$router.push({
            name: "qbank-test-app",
            params: {
              test_id: item.id,
            },
          });
        })
        .catch((e) => {
          this.stopLoader();
          this.$q.notify({
            message: "Request Failed",
            type: "error-notify",
            caption: "Sorry!! Test Resume Failed...",
          });
        });
    },
    reviewTest(item) {
      this.$router.push({
        name: "qbank-test-app",
        params: {
          test_id: item.id,
        },
      });
    },
    navigateToAnalysis(id) {
      this.$router.push({
        name: "app-test-analysis",
        params: {
          id: id,
        },
      });
    },
    topics(item) {
      let unique = [];
      let topics = [];
      item.data_test.forEach((element) => {
        if (!unique.includes(element.topic_id)) {
          unique.push(element.topic_id);
          topics.push(element);
        }
      });

      return topics;
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
  },
};
</script>

<style lang="css" scoped>
.hide {
  display: none;
}

.show {
  display: inline;
}
.click-fx {
  background: grey;
}
.click-fx:hover {
  background: #1976d2 !important;
}
.hoverable {
  transition: all 0.5s ease;
  border: 1px solid #dddddd;
  border-radius: 5px !important;
}

.hoverable:hover {
  /* filter: grayscale(100%); */

  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2), 0 2px 2px rgba(0, 0, 0, 0.14),
    0 3px 1px -2px rgba(0, 0, 0, 0.12);
  /* border-radius: 5px; */
  vertical-align: top;
  background: #fff;
  position: relative;
  transition: all 0.5s ease;
}

.circle {
  border-radius: 50%;
}

a {
  text-decoration: none;
  color: #04b1ed;
  font-weight: 400;
}

@media only screen and (min-width: 0px) and (max-width: 900px) {
  .hide {
    display: inline;
  }

  .show {
    display: none;
  }
}

@media only screen and (min-width: 899px) and (max-width: 1280px) {
}
</style>
