<template>
  <div v-if="loading">
    <!-- <q-spinner-hourglass color="primary" size="4em" class="absolute-center" /> -->
    <div class>
      <div class="q-pa-xs">
        <q-skeleton height="60px" square />
      </div>
      <div class="row">
        <div class="col-3 col-md-3 col-sm-12 col-xs-12 desktop-only">
          <div class="q-pa-none bg-grey-3" style="height: 730px;">
            <div class="q-pa-xs">
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
              <q-skeleton type="text" />
            </div>
          </div>
        </div>
        <div class="col-9 col-md-9 col-sm-12 col-xs-12">
          <div class="q-px-md flex justify-between row">
            <q-skeleton type="text" width="100px" />
            <q-skeleton type="text" width="100px" />
          </div>
          <div class="q-px-md">
            <q-skeleton type="text" />
            <q-skeleton type="text" />
            <q-skeleton type="text" />
            <q-skeleton type="text" />
            <q-skeleton type="text" />
          </div>
          <div class="q-pa-xl">
            <q-skeleton height="250px" width="400px;" square />
          </div>
          <div class="q-px-xl desktop-only">
            <q-skeleton height="150px" width="300px" square />
          </div>
          <div class="q-px-xl q-py-md desktop-only">
            <q-skeleton type="QBtn" />
          </div>
        </div>
      </div>
      <div class="q-pb-md fixed-bottom">
        <q-skeleton height="60px" square />
      </div>
    </div>
  </div>
  <div class="q-pa-md" v-else>
    <q-layout view="hHh Lpr lff" class="shadow-2 rounded-borders">
      <q-header elevated>
        <top-bar
          :isTestInReviewMode="isTestInReviewMode"
          :test="test"
          :currentQuestion="currentQuestion"
          :questions="questions"
          @toogleReportDialog="toogleReportDialog"
          @redirectDashboard="redirectDashboard"
          @updateQuestion="updateQuestion"
          @updateTestStatus="updateTestStatus"
        />
      </q-header>
      <q-footer elevated>
        <bottom-bar
          :questions="questions"
          :test="test"
          @updateTestStatus="updateTestStatus"
          ref="bottomComponent"
        />
      </q-footer>
      <side-bar :questions="questions" :test="test" />
      <q-page-container class="q-mb-xl">
        <div class="row q-px-md bg-white z-top">
          <div class="col-12 justify-between row">
            <div class="q-pt-md q-id-container" :style="'font-size:'+test.fontSize+';'">
               <span id="qid">
                 
                </span>
              <span class="text-bold">{{ currentQuestion.question.id }}</span>
            </div>
            <q-space />
            <div class="q-pt-none">
              <q-checkbox
                left-label
                v-model="questions[test.currentQuestionIndex].isFavorited"
                @input="markQuestion()"
                :style="'font-size:'+test.fontSize+';'"
                id="mark-favourite"
              />
            </div>
          </div>
        </div>
        <q-page class="q-px-md">
          <p
            :style="'font-size:'+test.fontSize+';'"
            v-html="currentQuestion.question.question"
            thumbnails
          ></p>
          <div class="q-pa-lg q-images-container" v-if="hasImage">
            <div class="q-carousel q-panel-parent q-carousel--without-padding">
              <viewer :images="currentQuestionActiveImage">
                <div class="img-lg">
                  <img
                    v-for="(image, index) in currentQuestionImages"
                    :key="index"
                    :src="`${storageUrl}question/l/${image.image}`"
                    :style="index==0 ? '' : 'display:none;'"
                  />
                </div>
              </viewer>
              <div
                class="q-carousel__control q-carousel__navigation no-wrap absolute flex q-carousel__navigation--thumbnails q-carousel__navigation--bottom"
              >
                <div class="q-carousel__navigation-inner flex no-wrap justify-center">
                  <img
                    v-for="(image, index) in currentQuestionImagesThumbnails"
                    :key="index"
                    :src="`${storageUrl}question/m/${image.image}`"
                    class="q-carousel__thumbnail q-carousel__thumbnail--inactive"
                    @click="changeImage(index)"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="q-pa-lg ans-box column" :style="'font-size:'+test.fontSize+';'">
            <ol type="A">
              <li
                v-for="(ans, index) in currentQuestion.question.ques_choise"
                :key="index"
                 :style="'font-size:'+test.fontSize+';'"
              >
                <div>
                <q-radio
                  @input="answerChanged($event)"
                  v-model="questions[test.currentQuestionIndex].selectedAnswer"
                  :val="ans.id"
                  :disable="questions[test.currentQuestionIndex].isSubmit || test.isPaused || test.isTestExpired || test.isTestEnd"
                  :color="ansState(ans.correct,true)"
                ></q-radio>
                <span v-html="ans.answer"></span>
                <q-icon
                  :name="ansState(ans.correct)"
                  :style="'font-size:'+test.fontSize+';padding-left:20px;'"
                />
                </div>
              </li>
            </ol>
            <div
              class="text-center"
              v-if="(!questions[test.currentQuestionIndex].isSubmit && !test.isPaused && !test.isTestExpired && !test.isTestEnd) || isQsSubmitInProgress"
            >
              <q-btn
                :loading="isQsSubmitInProgress"
                label="Submit"
                color="primary"
                :style="'font-size:'+test.fontSize+';width:160px;'"
                @click="submitAnswer"
              >
                <template v-slot:loading>
                  <q-spinner-hourglass class="on-left" />Submitting...
                </template>
              </q-btn>
            </div>
          </div>

          <div class="q-py-md" v-if="isAnswerAllowedToShow || test.isTutor">
            <div class="q-gutter-y-md maxWidth">
              <q-card>
                <q-tabs
                  v-model="activeTab"
                  dense
                  class="text-grey"
                  active-color="primary"
                  indicator-color="primary"
                  align="justify"
                  narrow-indicator
                >
                  <q-tab
                    name="answer"
                    label="Answer"
                    :style="'font-size:'+test.fontSize+';'"
                    v-if="isAnswerAllowedToShow"
                  />
                  <q-tab
                    name="explanation"
                    label="Explanation"
                    :style="'font-size:'+test.fontSize+';'"
                    v-if="test.isTutor"
                  />
                </q-tabs>

                <q-separator />

                <q-tab-panels v-model="activeTab" animated>
                  <q-tab-panel name="answer">
                    <div class="text-center" v-html="ansComment"></div>
                    <div class="text-h6">Correct Answer:</div>
                    {{rightAnswer}}
                    <div class="text-h6">Your Answer:</div>
                    {{selectedAnswer}}
                  </q-tab-panel>

                  <q-tab-panel name="explanation" v-if="test.isTutor">
                    <div class="text-h6">Question Explanation:</div>
                    
                    <div class="q-pa-lg q-images-container" v-if="hasExplanationImage">
                      <div class="q-carousel q-panel-parent q-carousel--without-padding">
                        <viewer :images="currentQuestionExplanationImages">
                          <div class="img-lg">
                            <img
                              v-for="(image, index) in currentQuestionExplanationImages"
                              :key="index"
                              :src="`${storageUrl}question/l/${image.image}`"
                              :style="index==0 ? '' : 'display:none;'"
                            />
                          </div>
                        </viewer>
                        <div
                          class="q-carousel__control q-carousel__navigation no-wrap absolute flex q-carousel__navigation--thumbnails q-carousel__navigation--bottom"
                        >
                          <div class="q-carousel__navigation-inner flex no-wrap justify-center">
                            <img
                              v-for="(image, index) in currentQuestionExplanationImagesThumbnails"
                              :key="index"
                              :src="`${storageUrl}question/m/${image.image}`"
                              class="q-carousel__thumbnail q-carousel__thumbnail--inactive"
                              @click="changeExpImage(index)"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                    <p
                      :style="'font-size:'+test.fontSize+';'"
                      v-html="currentQuestion.question.explaination"
                    ></p>
                  </q-tab-panel>
                </q-tab-panels>
              </q-card>
            </div>
          </div>
        </q-page>

        <q-page-sticky position="bottom-right" :offset="[10, 60]" class="report-us">
          <q-fab color="dark" label-position="left" label="Report" @click="toogleReportDialog"></q-fab>
        </q-page-sticky>

        <q-dialog v-model="reportDialogVisible">
          <q-card style="width: 95%" class="q-px-sm q-pb-md">
            <q-card-section class="text-h6 text-center">
              <q-icon name="flag" />Report Error
            </q-card-section>

            <q-item dense>
              <div class="q-pa-sm" style="min-width: 100%;">
                <q-form ref="reportError" @submit="reportQuestionError" class="q-gutter-md">
                  <q-input
                    clearable
                    ref="subject"
                    type="text"
                    v-model="errorReport.title"
                    label="* Subject"
                    placeholder="Name the issue"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type something']"
                  />

                  <q-input
                    clearable
                    ref="description"
                    type="textarea"
                    v-model="errorReport.description"
                    label="* Description"
                    lazy-rules
                    :rules="[val => val !== null && val !== '' || 'Please type your description']"
                  />
                  <q-item dense class="flex-center">
                    <q-btn
                      :loading="isReportRequestInProgress"
                      type="submit"
                      color="primary"
                      class="full-width"
                      label="Submit"
                    >
                      <template v-slot:loading>
                        <q-spinner-hourglass class="on-left" />Submitting...
                      </template>
                    </q-btn>

                    <q-btn
                      class="q-ma-sm"
                      color="negative"
                      text-color="white"
                      label="Cancel"
                      v-close-popup
                    />
                  </q-item>
                </q-form>
              </div>
            </q-item>
          </q-card>
        </q-dialog>
      </q-page-container>
    </q-layout>
  </div>
</template>

<script>
import TestAppService from "../../../services/TestAppService.js";
import { skeleton } from "../../../mixins/SkeletonMixin.js";
import { loader } from "../../../mixins/LoaderMixin.js";
import { mapGetters } from "vuex";
import ConfirmDialogVue from "../../../components/ConfirmDialog.vue";
import "viewerjs/dist/viewer.css";
export default {
  mixins: [skeleton, loader],
  props: ["test_id", "question_index"],
  data() {
    return {
      questions: [],
      px: 100,
      color: "#0059a8",
      height: "150px",
      width: "10px",
      showTextZoom: false,
      showReverse: false,
      test: {
        id: 0,
        qbankName: "",
        isTutor: false,
        isTimed: false,
        status: "Not Started",
        isTestExpired: false,
        isTestEnd: false,
        isDemo: true,
        isPaused: false,
        isOpenSideBar: false,
        isBlack: false,
        fontSize: "16px",
        currentQuestionIndex: 0,
        totalTime: {
          hours: 0,
          minutes: 0,
          seconds: 0
        },
        remainingTime: {
          hours: 0,
          minutes: 0,
          seconds: 0
        },
        isTestTimeInHours: false,
        attemptedQuestions: [],
        showDetailedExplantion: false
      },
      reportDialogVisible: false,
      activeTab: "explanation",
      errorReport: {
        question_id: "",
        test_id: "",
        title: "",
        description: "",
        type: 2,
        category: 1,
        department: 13,
        name: "",
        email: ""
      },
      isReportRequestInProgress: false,
      slide: 1,
      slide2: 1,
      isQsSubmitInProgress: false,
      redirectToDashboard: false
    };
  },
  components: {
    "bottom-bar": () => import("./Bottombar.vue"),
    "top-bar": () => import("./Topbar.vue"),
    "side-bar": () => import("./Sidebar.vue"),
    viewer: () => import("v-viewer/src/component.vue")
  },
  mounted() {
    let t = this;
    this.errorReport.name = this.authUser.fname + " " + this.authUser.lname;
    this.errorReport.email = this.authUser.email;
    axios
      .get(`/get-qbank-test-data/${t.test_id}`)
      .then(resp => {
        console.log(resp.data);
        t.prepareTest(resp.data);
      })
      .catch(e => {
        this.hideSkeletonLoader();
      });
  },
  computed: {
    currentQuestion: {
      get: function() {
        return this.questions[this.test.currentQuestionIndex];
      },
      set: function(val) {}
    },
    rightAnswer() {
      if (!this.currentQuestion) {
        return "";
      }
      let ans = this.currentQuestion.question.ques_choise.find(
        e => e.correct == 1
      );
      if (ans) {
        return ans.answer;
      }
      return "";
    },
    selectedAnswer() {
      if (!this.currentQuestion) {
        return "";
      }
      let ans = this.currentQuestion.question.ques_choise.find(
        e => e.id == this.currentQuestion.selectedAnswer
      );
      if (ans) {
        return ans.answer;
      }
      return "No Answer Selected";
    },
    ansComment() {
      if (!this.currentQuestion.selectedAnswer) {
        return `<span class="text-warning">No Answer Selected</span>`;
      }
      return this.currentQuestion.isAnswerCorrect
        ? `<span class="text-positive">Your Answer is Correct</span>`
        : '<span class="text-negative">Your Answer is Wrong</span>';
    },
    hasImage() {
      return this.currentQuestion.question.ques_image.length > 0;
    },
    currentQuestionActiveImage() {
      return [
        this.currentQuestion.question.ques_image[
          this.currentQuestion.qImageIndex
        ]
      ];
    },
    currentQuestionImages() {
      let images;
      images = [...this.currentQuestion.question.ques_image];
      let active = images[this.currentQuestion.qImageIndex];
      images.splice(this.currentQuestion.qImageIndex, 1);
      images.unshift(active);
      return images;
    },
    currentQuestionImagesThumbnails() {
      return this.currentQuestion.question.ques_image;
    },
    hasExplanationImage() {
      return this.currentQuestion.question.ques_explain_images.length > 0;
    },
    currentQuestionExplanationImages() {
      let images;
      images = [...this.currentQuestion.question.ques_explain_images];
      let active = images[this.currentQuestion.qExpImageIndex];
      images.splice(this.currentQuestion.qExpImageIndex, 1);
      images.unshift(active);
      return images;
    },
    currentQuestionExplanationImagesThumbnails(){
       return this.currentQuestion.question.ques_explain_images;
    },
    isAnswerAllowedToShow() {
      return (
        this.questions[this.test.currentQuestionIndex].isSubmit ||
        this.test.isTestEnd ||
        this.test.isTestExpired
      );
    },
    heightState() {
      return this.test.showDetailedExplantion
        ? {
            maxHeight: "100%",
            fontSize: this.test.fontSize,
            padding: "10px"
          }
        : {
            maxHeight: "100px",
            fontSize: this.test.fontSize,
            padding: "10px"
          };
    },
    isTimeLeft() {
      if (this.test.isTimed) {
        if (this.test.remainingTime.hours > 0) {
          return true;
        }
        if (this.test.remainingTime.minutes > 0) {
          return true;
        }
        if (this.test.remainingTime.seconds > 0) {
          return true;
        }
        return false;
      }
      return false;
    },
    isTestInReviewMode() {
      return this.test.isTestExpired || this.test.isTestEnd;
    },
    ...mapGetters("auth", ["isLoggedIn", "authUser"])
  },
  methods: {
    prepareTest: function(record) {
      let t = this;
      t.questions = [];
      t.test.status = record.status;
      t.test.isTutor = record.isTutor == 0 ? false : true;
      t.test.isTimed = record.isTimed == 0 ? false : true;
      t.test.isDemo = record.isDemo == 0 ? false : true;
      t.test.isBlack = record.isBlack == 0 ? false : true;
      t.test.isOpenSideBar = record.isOpenSideBar == 0 ? false : true;
      t.test.fontSize = record.fontSize;
      record.data_test.forEach(val => {
        let correctAns = "";

        if (val.isSubmit != 0) {
          correctAns = val.correctAnswer;
        } else {
          correctAns = val.question.ques_choise.find(e => {
            return e.correct == 1;
          }).id;
        }
        if (val.selectedAnswer || val.isSubmit) {
          t.test.attemptedQuestions.push(val.question_id);
        }

        t.questions.push({
          ques_id: val.question_id,
          question: val.question,
          isSubmit: val.isSubmit == 0 ? false : true,
          selectedAnswer: val.selectedAnswer
            ? parseInt(val.selectedAnswer, 10)
            : "",
          isAnswerCorrect: val.isAnswerCorrect == 0 ? false : true,
          isFlagged: val.isFlagged == 0 ? false : true,
          isFavorited: val.isFavorited == 0 ? false : true,
          correctAnswer: correctAns,
          questionNote: val.questionNote,
          isUsed: val.isUsed == 0 ? false : true,
          timeConsume: 0,
          totalTime: 0,
          isNoteShow: val.isNoteShow == 0 ? false : true,
          isCalculatorShow: val.isCalculatorShow == 0 ? false : true,
          topic_id: val.topic_id,
          topic: val.topic,
          subtopic_id: val.subtopic_id,
          subtopic: val.subtopic,
          testId: val.id,
          qImageIndex: 0,
          qExpImageIndex:0
        });
      });
      t.test.id = record.id;
      t.test.qbankName = record.qbank.name;
      t.test.currentQuestionIndex = parseInt(
        t.question_index != undefined
          ? t.question_index
          : record.currentQuestionIndex,
        10
      );

      if (this.test.isTimed) {
        let totalTime = record.totalTime;
        totalTime = totalTime.split(":");
        this.test.totalTime.hours = parseInt(totalTime[0], 10);
        this.test.totalTime.minutes = parseInt(totalTime[1], 10);
        this.test.totalTime.seconds = parseInt(totalTime[2], 10);
        if (
          this.test.totalTime.hours == 0 &&
          this.test.totalTime.minutes == 0 &&
          this.test.totalTime.seconds == 0
        ) {
          this.calculateTestTime();
        } else {
          let remainingTime = record.remainingTime;
          remainingTime = remainingTime.split(":");
          this.test.remainingTime.hours = parseInt(remainingTime[0], 10);
          this.test.remainingTime.minutes = parseInt(remainingTime[1], 10);
          this.test.remainingTime.seconds = parseInt(remainingTime[2], 10);
          if (this.test.remainingTime.hours > 0) {
            this.test.isTestTimeInHours = true;
          }
        }
      }
      if (t.test.isBlack) {
        document.body.style.background = "black";
        document.body.style.color = "white";
      } else {
        document.body.style.background = "white";
        document.body.style.color = "black";
      }
      this.updateResultantTestStatus();
    },
    updateResultantTestStatus: function() {
      switch (this.test.status) {
        case "Not Started":
          this.updateTestStatus("Running");
        case "Running":
          if (this.test.isTimed) {
            if (this.isTimeLeft) {
              this.updateTestStatus("Running");
            } else {
              this.updateTestStatus("Expired");
            }
          } else {
            this.updateTestStatus("Running");
          }
        default:
          this.hideSkeletonLoader();
      }
    },
    setTestStatusFlags: function() {
      this.test.isPaused = this.test.status == "Paused";
      this.test.isTestEnd = this.test.status == "End";
      this.test.isTestExpired = this.test.status == "Expired";
    },
    calculateTestTime: function() {
      let t = this;
      let minutes = 0;

      for (var prop in t.questions) {
        minutes += t.questions[prop].question.ques_time.duration;
      }
      let hours = minutes / 60;
      let m = 0;
      if (hours > 0) {
        this.test.totalTime.hours = Math.floor(hours);
        this.test.totalTime.minutes = Math.round(
          (hours - this.test.totalTime.hours) * 60
        );
      }

      this.test.remainingTime.hours = this.test.totalTime.hours;
      this.test.remainingTime.minutes = this.test.totalTime.minutes;
      this.test.remainingTime.seconds = 0;
      console.log(this.test.totalTime.hours);
      console.log(this.test.totalTime.minutes);
      if (this.test.totalTime.hours > 0) {
        this.test.isTestTimeInHours = true;
      }
    },
    updateTestTotalTime() {
      let data = {
        totalTime: `${this.test.totalTime.hours}:${this.test.totalTime.minutes}:${this.test.totalTime.seconds}`,
        remainingTime: `${this.test.remainingTime.hours}:${this.test.remainingTime.minutes}:${this.test.remainingTime.seconds}`
      };
      TestAppService.updateTestInfo(
        `/update-qbank-test-total-time/${this.test.id}`,
        data
      )
        .then(res => {})
        .catch(e => {});
    },
    updateTestRemainingTime() {
      let data = {
        remainingTime: `${this.test.remainingTime.hours}:${this.test.remainingTime.minutes}:${this.test.remainingTime.seconds}`,
        currentQuestionIndex: this.test.currentQuestionIndex
      };
      TestAppService.updateTestInfo(
        `/update-qbank-test-remaining-time/${this.test.id}`,
        data
      )
        .then(res => {})
        .catch(e => {});
    },
    resumeTest() {
      if (this.isTimeLeft) {
        this.$refs.bottomComponent.resumeTimer();
      } else {
        this.test.isPaused = false;
      }
    },
    pauseTest() {
      if (this.isTimeLeft) {
        this.$refs.bottomComponent.pauseTimer();
      } else {
        this.test.isPaused = false;
      }
    },
    imgUrl(image, type = "question") {
      return `background-image: url('${storageUrl}${type}/l/${image.image}')`;
    },
    ansState(isCorrect, returnColor = false) {
      isCorrect = parseInt(isCorrect, 10);
      let icon = "fas fa-times-circle";
      let color = "red";
      if (isCorrect) {
        icon = "fas fa-check-circle";
        color = "green";
      }
      if (
        this.questions[this.test.currentQuestionIndex].isSubmit ||
        this.test.isTestExpired ||
        this.test.isTestEnd
      ) {
        return returnColor ? color : icon;
      }
      return "";
    },
    toogleReportDialog() {
      this.reportDialogVisible = !this.reportDialogVisible;
    },
    updateQuestion: function(msgData = null, state = []) {
      TestAppService.updateTestQuestionInfo(
        `/update-qbank-test-questioin-info/${this.test.id}`,
        this.questions[this.test.currentQuestionIndex]
      )
        .then(res => {
          if (msgData) {
            this.$q.notify({
              message: msgData.title,
              type: "success-notify",
              caption: msgData.msg
            });
          }
        })
        .catch(e => {
          if (msgData) {
            this.$q.notify({
              message: "Failed",
              type: "error-notify",
              caption: "Sorry Request Failed..."
            });
            for (const i in state) {
              this.questions[this.test.currentQuestionIndex][state[i].key] =
                state[i].value;
            }
          }
        });
    },
    updateNote: function() {
      this.updateQuestion();
    },
    changeImage: function(index) {
      this.currentQuestion.qImageIndex = index;
    },
    changeExpImage: function(index) {
     this.currentQuestion.qExpImageIndex = index;
    },

    toogleExplanationState() {
      if (this.test.showDetailedExplantion) {
        this.test.showDetailedExplantion = false;
        this.resumeTest();
      } else {
        this.test.showDetailedExplantion = true;
        this.pauseTest();
      }
    },
    reverseBlack: function() {
      this.test.isBlack = true;
      document.body.style.background = "black";
      document.body.style.color = "white";
    },
    reverseWhite: function() {
      this.test.isBlack = false;
      document.body.style.background = "white";
      document.body.style.color = "black";
    },
    resetFontSize: function() {
      let fontSize = "16px";
      this.test.fontSize = fontSize;
    },
    resizeFonts: function(multiplier) {
      this.test.fontSize =
        parseFloat(this.test.fontSize) + multiplier * 0.9 + "px";
    },
    markQuestion: function() {
      let t = this;
      if (t.isTestInReviewMode) {
        if (this.questions[this.test.currentQuestionIndex].isFavorited) {
          this.questions[this.test.currentQuestionIndex].isFavorited = false;
        } else {
          this.questions[this.test.currentQuestionIndex].isFavorited = true;
        }
        this.$q.notify({
          type: "error-notify",
          message: `Sorry`,
          caption: "You can not use this feature in Review Mode.",
          icon: "fas fa-times-circle"
        });
        return;
      } else {
        let isFavorited = t.questions[t.test.currentQuestionIndex].isFavorited;
        let text = "";

        if (isFavorited) {
          text =
            "Question (" +
            t.questions[t.test.currentQuestionIndex].ques_id +
            ") has been marked as Favorite !";
        } else {
          text =
            "Question (" +
            t.questions[t.test.currentQuestionIndex].ques_id +
            ") has been removed from Favorite !";
        }
        this.updateQuestion({ title: "Success", msg: text }, [
          { key: "isFavorited", value: !isFavorited }
        ]);
      }
    },
    submitAnswer: function() {
      this.isQsSubmitInProgress = true;
      let t = this;
      if (t.test.isTestEnd || t.test.isTestExpired) {
        this.$q.notify({
          message: "Review Mode",
          type: "error-notify",
          caption: "Sorry, You can not submit answers in review mode."
        });
        this.isQsSubmitInProgress = false;
        return;
      } else {
        let answer = t.currentQuestion.question.ques_choise;
        for (let i in answer) {
          if (answer[i].correct == 1) {
            t.questions[t.test.currentQuestionIndex].correctAnswer =
              answer[i].id;
          }
        }
        let msg =
          "Question (" +
          t.questions[t.test.currentQuestionIndex].ques_id +
          ") has been submited!";
        let found = t.test.attemptedQuestions.find(el => {
          return el == t.questions[t.test.currentQuestionIndex].ques_id;
        });

        if (!found) {
          t.test.attemptedQuestions.push(
            t.questions[t.test.currentQuestionIndex].ques_id
          );
        }
        t.questions[t.test.currentQuestionIndex].isSubmit = true;
        t.questions[t.test.currentQuestionIndex].isUsed = true;
        TestAppService.updateTestQuestionInfo(
          `/update-qbank-test-questioin-info/${this.test.id}`,
          this.questions[this.test.currentQuestionIndex]
        )
          .then(res => {
            this.$q.notify({
              message: "Submitted",
              type: "success-notify",
              caption: msg
            });
            this.isQsSubmitInProgress = false;
          })
          .catch(e => {
            t.questions[t.test.currentQuestionIndex].isSubmit = false;
            t.questions[t.test.currentQuestionIndex].isUsed = false;
            this.$q.notify({
              message: "Submition Failed",
              type: "error-notify",
              caption: "Sorry Question Submition Failed..."
            });
            this.isQsSubmitInProgress = false;
          });
        this.activeTab = "answer";
      }
    },
    jumpQuestion: function() {
      if (!this.test.isTestEnd && !this.test.isTestExpired) {
        this.updateTestRemainingTime();
      }

      if (this.test.showDetailedExplantion) {
        this.resumeTest();
        this.test.showDetailedExplantion = false;
      }
      if (this.isAnswerAllowedToShow) {
        this.activeTab = "answer";
      } else {
        this.activeTab = "explanation";
      }
    },
    answerChanged: function(value) {
      let t = this;
      if (value) {
        t.questions[t.test.currentQuestionIndex].selectedAnswer = value;
        t.questions[t.test.currentQuestionIndex].isAnswerCorrect =
          t.questions[t.test.currentQuestionIndex].correctAnswer == value;
      } else {
        t.questions[t.test.currentQuestionIndex].selectedAnswer = "";
      }
      if (t.questions[t.test.currentQuestionIndex].selectedAnswer) {
        let found = t.test.attemptedQuestions.find(el => {
          return el == t.questions[t.test.currentQuestionIndex].ques_id;
        });

        if (!found) {
          t.test.attemptedQuestions.push(
            t.questions[t.test.currentQuestionIndex].ques_id
          );
        }
      }
      this.updateQuestion();
    },

    updateTestStatus(status) {
      this.startLoader("Processing.Please Hang on...");
      let data = {
        status: status,
        remainingTime: `${this.test.remainingTime.hours}:${this.test.remainingTime.minutes}:${this.test.remainingTime.seconds}`,
        currentQuestionIndex: this.test.currentQuestionIndex
      };
      if (this.test.status == "Not Started") {
        data.totalTime = `${this.test.totalTime.hours}:${this.test.totalTime.minutes}:${this.test.totalTime.seconds}`;
      }
      TestAppService.updateTestStatus(
        `/update-qbank-test-status/${this.test.id}`,
        {
          data
        }
      )
        .then(response => {
          switch (status) {
            case "End":
              if (this.test.status != "End") {
                this.$router.push({
                  name: "app-test-analysis",
                  params: {
                    id: this.test.id
                  }
                });
              }
              break;
          }
          this.test.status = status;
          this.stopLoader();
          this.hideSkeletonLoader();
          if (this.redirectToDashboard) {
            this.$router.push({
              name: "qbank-welcome"
            });
          }
        })
        .catch(e => {
          this.hideSkeletonLoader();
          this.stopLoader();
        });
    },
    reportQuestionError() {
      this.$refs.reportError.validate().then(success => {
        if (success) {
          this.errorReport.question_id = this.currentQuestion.ques_id;
          this.errorReport.test_id = this.test.id;
          this.isReportRequestInProgress = true;
          TestAppService.reportQuestion(`/report-issue`, this.errorReport)
            .then(response => {
              this.isReportRequestInProgress = false;
              this.$q.notify({
                message: "Submitted",
                type: "success-notify",
                caption: "Error Reported Successfully!!"
              });
              this.toogleReportDialog();
            })
            .catch(e => {
              this.isReportRequestInProgress = false;
              this.$q.notify({
                message: "Failed",
                type: "error-notify",
                caption: "Sorry!! Request Failed.Please try again later."
              });
            });
        } else {
        }
      });
    },
    redirectDashboard(val) {
      this.redirectToDashboard = val;
    }
  },
  watch: {
    currentQuestion: function() {
      if (!this.isLoggedIn) {
        this.$router.push({
          name: "login"
        });
      }
    },
    "test.currentQuestionIndex": function(e) {
      this.jumpQuestion();
    },
    "test.attemptedQuestions": function(e) {
      if (
        this.questions.length == this.test.attemptedQuestions.length &&
        !this.test.isTestExpired &&
        !this.test.isTestEnd
      ) {
        let t = this;
        setTimeout(e => {
          if (this.test.status == "Running") {
            this.$q
              .dialog({
                component: ConfirmDialogVue,
                parent: this,
                titleText: "Questions Alert",
                msgText:
                  "You have attempted all questions.Would you like to end the test?",
                cancel: true,
                persistent: true
              })
              .onOk(() => {
                this.updateTestStatus("End");
              })
              .onCancel(() => {
                // console.log('>>>> Cancel')
              })
              .onDismiss(() => {});
          }
        }, 2000);
      }
    },
    "test.status": function(e) {
      this.setTestStatusFlags();
    }
  }
};
</script>

<style lang="css" scoped>
.b-red {
  border: 1px solid red;
}

.b-blu {
  border: 1px solid blue;
}

.ans-box {
  border: 1px solid #d1d1d1;
  border-radius: 5px;
  margin: 10px 0;
  max-width: 90%;
  width: 90%;
}
.q-images-container {
  margin: 10px 0;
  max-width: 90%;
  padding-left: 0px;
  padding-right: 0px;
  padding-bottom: 0px;
}
.q-images-container > div {
  height: auto !important;
}
.img-lg {
  display: flex;
  justify-content: center;
  align-items: center;
}
.img-lg > img {
  width: 50%;
  height: auto;
}

.maxWidth {
  max-width: 90%;
}
.report-us {
  display: block;
}
.my-image {
  width: 100%;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
}
.sidebar-main-container .q-drawer {
  bottom: 50px !important;
}
#qid::after{
    content: "Question ID:";
}
#mark-favourite::after{
    content: "Mark Question as Favourite:";
}

@media only screen and (min-width: 0px) and (max-width: 900px) {
  .q-id-container {
    font-size: 14px;
    padding-top: 10px;
  }
  #qid::after{
    content: "Q-ID:";
  }
  #mark-favourite::after{
    content: "Mark as Favourite:";
  }
  p,
  ol li {
    font-size: 140%;
  }
  .ans-box {
    max-width: 100vw;
  }
  .q-images-container {
    max-width: 100vw;
  }
  .img-lg > img {
    width: 100%;
    height: auto;
  }
  .maxWidth {
    max-width: 100%;
  }
  .report-us {
    display: none;
  }
  .ans-box {
    max-width: 100%;
    width: 100%;
    padding:0px;
  }
}
</style>
