<template>
  <div v-if="loading">
    <div>
      <div class="q-pa-md q-py-lg">
        <q-skeleton height="40px" square style="width: 250px;" />
      </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="120px" square style="width: 100%;">
              <q-separator class="q-ma-md" inset />
              <div class="row justify-around">
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
              </div>
            </q-skeleton>
          </div>
          <div class="q-ma-md q-pa-md q-py-lg bg-grey-3">
            <q-skeleton height="120px" square style="width: 100%;">
              <q-separator class="q-ma-md" inset />
              <div class="row justify-around">
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
                <q-skeleton type="QBtn" />
              </div>
            </q-skeleton>
          </div>
          <div class="q-ma-md q-pa-md q-py-lg bg-grey-3">
            <q-skeleton height="120px" square style="width: 100%;">
              <div class="q-ma-sm">
                <q-skeleton type="text" style="width: 30%;" />
              </div>
              <q-separator class="q-ma-md" inset />
              <div class="q-ma-sm">
                <q-skeleton type="rect" style="width: 70%;" />
              </div>
            </q-skeleton>
          </div>
          <div class="q-ma-md q-pa-md q-py-lg bg-grey-3">
            <q-skeleton height="160px" square style="width: 100%;">
              <div class="q-ma-sm row">
                <q-skeleton type="rect" style="width: 20%;" />
                <q-skeleton type="QRadio" class="q-mx-md" />
              </div>
              <q-separator class="q-ma-md" inset />
              <div class="q-ma-sm row q-mx-lg">
                <q-skeleton type="QToggle" />
                <q-skeleton type="QToggle" class="q-mx-xl" />
              </div>
            </q-skeleton>
          </div>
          <div class="q-ma-md q-pa-md q-py-lg bg-grey-3">
            <q-skeleton height="250px" square style="width: 100%;">
              <div class="q-ma-sm">
                <q-skeleton type="rect" class="q-mx-md" style="width: 30%;" />
              </div>
              <q-separator class="q-ma-md" inset />
              <div class="q-ma-sm row q-mx-lg">
                <q-skeleton type="QInput" style="width: 40%;" />
              </div>
              <div class="q-ma-lg q-py-md">
                <q-skeleton type="QBtn" />
              </div>
            </q-skeleton>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="q-pa-sm" v-else-if="!loading">
    <div class="text-h5 q-pb-md">Create New Test</div>
    <div class="row">
      <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-my-md">
        <q-card class="my-card">
          <q-card-section>
            <q-select
              outlined
              v-model="newTestForm.qbank_id"
              :options="qBankOptions"
              label="Select Qbank"
              emit-value
              map-options
              @input="handleCheckedQbankChange($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>
      </div>
    </div>
    <div v-if="topics.length>0">
      <div class="row">
        <div class="text-h5 text-grey-8">Filters</div>
        <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-my-md">
          <q-card>
            <div class="text-body1 text-grey-8 text-bold q-pa-md">Difficulty Level</div>
            <q-separator inset />
            <q-card-section class="q-gutter-lg flex justify-between">
              <q-btn :disable="difficultyQuestionsCount.all==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.difficulty"
                  :val="0"
                  :disable="difficultyQuestionsCount.all==0"
                />
                <q-badge color="primary" floating>{{difficultyQuestionsCount.all}}</q-badge>All
              </q-btn>
              <q-btn :disable="difficultyQuestionsCount.easy==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.difficulty"
                  :val="1"
                  :disable="difficultyQuestionsCount.easy==0"
                />
                <q-badge color="primary" floating>{{difficultyQuestionsCount.easy}}</q-badge>Easy
              </q-btn>
              <q-btn :disable="difficultyQuestionsCount.medium==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.difficulty"
                  :val="2"
                  :disable="difficultyQuestionsCount.medium==0"
                />
                <q-badge color="primary" floating>{{difficultyQuestionsCount.medium}}</q-badge>Medium
              </q-btn>
              <q-btn :disable="difficultyQuestionsCount.hard==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.difficulty"
                  :val="3"
                  :disable="difficultyQuestionsCount.hard==0"
                />
                <q-badge color="primary" floating>{{difficultyQuestionsCount.hard}}</q-badge>Hard
              </q-btn>
            </q-card-section>
          </q-card>
        </div>
        <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-my-sm">
          <q-card>
            <div class="text-body1 text-grey-8 text-bold q-pa-md">
              Question Mode
              <q-icon size="md" name="help">
                <q-tooltip
                  content-class="bg-white text-subtitle1 text-grey-8 shadow-8"
                  anchor="top middle"
                  self="top middle"
                >
                  <!-- <img src="statics/tooltipQ.png" alt="tooltip" /> -->
                  <q-list bordered separator>
                    <q-item>
                      <q-item-section>
                        <q-item-label>All</q-item-label>
                        <q-item-label caption>Select questions from all the above combination</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Used</q-item-label>
                        <q-item-label caption>Select questions from already attempted pool</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Marked</q-item-label>
                        <q-item-label caption>Select questions that were previously marked</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Incorrect</q-item-label>
                        <q-item-label caption>Select questions that were answered incorrectly</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Unused</q-item-label>
                        <q-item-label caption>Select questions from new/unseen questions</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-tooltip>
              </q-icon>
            </div>
            <q-separator inset />
            <q-card-section class="q-gutter-lg flex justify-between">
              <q-btn :disable="difficultyQuestionsCount.all==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.questionMode"
                  :val="0"
                  :disable="difficultyQuestionsCount.all==0"
                />
                <q-badge color="primary" floating>{{testQuestionModesData.all}}</q-badge>All
              </q-btn>
              <q-btn :disable="testQuestionModesData.used.length==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.questionMode"
                  :val="1"
                  :disable="testQuestionModesData.used.length==0"
                />
                <q-badge color="primary" floating>{{testQuestionModesData.used.length}}</q-badge>Used
              </q-btn>
              <q-btn :disable="unUsedQsCount==0" outline color="primary">
                <q-radio v-model="newTestForm.questionMode" :val="2" :disable="unUsedQsCount==0" />
                <q-badge color="primary" floating>{{unUsedQsCount}}</q-badge>Unused
              </q-btn>
              <q-btn :disable="testQuestionModesData.incorrect.length==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.questionMode"
                  :val="3"
                  :disable="testQuestionModesData.incorrect.length==0"
                />
                <q-badge color="primary" floating>{{testQuestionModesData.incorrect.length}}</q-badge>Incorrect
              </q-btn>
              <q-btn :disable="testQuestionModesData.favourite.length==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.questionMode"
                  :val="4"
                  :disable="testQuestionModesData.favourite.length==0"
                />
                <q-badge color="primary" floating>{{testQuestionModesData.favourite.length}}</q-badge>Favourite
              </q-btn>
              <q-btn :disable="testQuestionModesData.flagged.length==0" outline color="primary">
                <q-radio
                  v-model="newTestForm.questionMode"
                  :val="5"
                  :disable="testQuestionModesData.flagged.length==0"
                />
                <q-badge color="primary" floating>{{testQuestionModesData.flagged.length}}</q-badge>Flagged
              </q-btn>
            </q-card-section>
          </q-card>
        </div>
      </div>
      <div class="row">
        <div class="text-h5 text-grey-8">Topics</div>
        <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-my-md">
          <q-list>
            <q-card v-for="(t, index) in topics" :key="index">
              <q-expansion-item
                default-opened
                group="somegroup"
                header-class="text-grey-9"
                expand-icon-class="text-grey-9"
              >
                <template v-slot:header>
                  <q-item-section class="text-body1 text-grey-8">
                    <q-checkbox
                      v-model="selected[index].isSelected"
                      :disable="isQbankSubscriptionTrial"
                      :class="selected[index].anyChildSelected ? 'q-checkbox__inner--indet' :''"
                      @input="handleTopicSelectionChange($event,index)"
                    >{{ t.topic.name }} ({{ t.totalQuestions }})</q-checkbox>
                  </q-item-section>
                </template>

                <q-separator inset />
                <div class="text-body1 text-grey-8 q-pa-lg">
                  <div
                    class="inline-block"
                    v-for="(subtopic, ind) in t.subtopics"
                    :key="subtopic.subtopic_id"
                  >
                    <q-checkbox
                      :disable="isQbankSubscriptionTrial && subtopic.free_question_count==0"
                      v-model="selected[index].selectedSubtopics[ind].isSelected"
                      @input="handleSubtopicSelectionChange($event,index,ind)"
                    >{{subtopic.name}} ({{subtopic.question_count}})</q-checkbox>
                    <q-badge
                      v-if="subtopic.free_question_count>0 && isQbankSubscriptionTrial"
                    >Free ({{subtopic.free_question_count}})</q-badge>
                  </div>
                  <div v-if="t.subtopics.length==0" class="text-center">sorry! no subtopics found...</div>
                </div>
                <q-card-section class="q-gutter-lg flex justify-between"></q-card-section>
              </q-expansion-item>
            </q-card>
          </q-list>
        </div>
      </div>
      <div class="row">
        <div class="text-h5 text-grey-8">Advaance Options</div>
        <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-my-md">
          <q-card>
            <div class="text-body1 text-grey-8 text-bold q-pa-md">
              Test Mode
              <q-icon size="md" name="help">
                <q-tooltip
                  content-class="bg-white text-subtitle1 text-grey-8 shadow-8"
                  anchor="top middle"
                  self="top middle"
                >
                  <q-list bordered separator>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Tutor</q-item-label>
                        <q-item-label caption>
                          After you answer the question, it shows the correct answer
                          <br />&amp; its details explanation.
                        </q-item-label>
                      </q-item-section>
                      <q-item-section side top>
                        <q-toggle class="text-caption" dense v-model="on" label="Tutor" left-label />
                        <q-toggle
                          class="text-caption"
                          dense
                          v-model="off"
                          label="Timed"
                          left-label
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Timed</q-item-label>
                        <q-item-label caption>Applied a time limit on the test.</q-item-label>
                      </q-item-section>
                      <q-item-section side top>
                        <q-toggle
                          class="text-caption"
                          dense
                          v-model="off"
                          label="Tutor"
                          left-label
                        />
                        <q-toggle class="text-caption" dense v-model="on" label="Timed" left-label />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Untimed</q-item-label>
                        <q-item-label caption>Applied no time limit on the test.</q-item-label>
                      </q-item-section>
                      <q-item-section side top>
                        <q-toggle
                          class="text-caption"
                          dense
                          v-model="off"
                          label="Tutor"
                          left-label
                        />
                        <q-toggle
                          class="text-caption"
                          dense
                          v-model="off"
                          label="Timed"
                          left-label
                        />
                      </q-item-section>
                    </q-item>
                    <q-item>
                      <q-item-section>
                        <q-item-label>Timed Tutor</q-item-label>
                        <q-item-label caption>Combine both the mode function together.</q-item-label>
                      </q-item-section>
                      <q-item-section side top>
                        <q-toggle class="text-caption" dense v-model="on" label="Tutor" left-label />
                        <q-toggle class="text-caption" dense v-model="on" label="Timed" left-label />
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-tooltip>
              </q-icon>
            </div>
            <q-separator inset />
            <q-card-section class="q-gutter-lg">
              <q-toggle class="text-caption" v-model="newTestForm.tutor" label="Tutor" />
              <q-toggle class="text-caption" v-model="newTestForm.timed" label="Timed" />
            </q-card-section>
          </q-card>
        </div>
        <div class="col-12 col-md-12 col-sm-12 col-xs-12 q-my-md">
          <q-card>
            <div class="text-body1 text-grey-8 text-bold q-pa-md">Number of questions</div>
            <q-card-section class="q-gutter-lg">
              <q-input
                dense
                outlined
                v-model.number="newTestForm.testQCount"
                type="number"
                style="max-width: 200px"
                placeholder="Minimum 10 MCQ's Allowed!"
              />

              <p class="m-t-10" v-if="isQbankSubscriptionTrial">Maximum 20 MCQ's Allowed!</p>
              <p class="m-t-10" v-else>Maximum 500 MCQ's Allowed!</p>

              <q-btn color="primary" @click="createTest">Create Test</q-btn>
              <div v-if="isQbankSubscriptionTrial">
                Do you want to exceed question limit?
                <a href="#" class="text-bold">Subscribe Now</a> &amp; get
                <b>upto 500 questions limit</b> in single test.
              </div>
            </q-card-section>
          </q-card>
        </div>
        <q-dialog v-model="dialogVisible" persistent transition-show="scale" transition-hide="scale">
          <q-card class="bg-red text-white" style="width: 600px">
            <q-card-section>
              <div class="text-h6">Error!</div>
            </q-card-section>

            <q-card-section class="q-pa-md bg-white text-grey-8">
              {{errorMsg}}
            </q-card-section>

            <q-card-actions align="right" class="bg-white text-teal">
              <q-btn color="primary" label="OK" v-close-popup />
            </q-card-actions>
          </q-card>
        </q-dialog>
      </div>
    </div>
    <div v-else>
      <p class="text-center">sorry this Qbank has no topics yet...</p>
    </div>
  </div>
</template>

<script>
import {loader} from '../../mixins/LoaderMixin.js'
import {skeleton} from '../../mixins/SkeletonMixin.js'
export default {
  mixins:[loader,skeleton],
  data() {
    return {
      newTestForm: {
        qbank_id: "",
        difficulty: 0,
        questionMode: 0,
        testQCount: 10,
        tutor: true,
        timed: true
      },
      qBanks: [],
      qBankOptions: [],
      qBankData: [],
      activeName: "1",
      activeMode: "1",
      topics: [],
      subtopics: [],
      selectedSubtopics: [],
      checkboxTopics: [],
      indeterminate: false,
      isDemo: true,
      selectedQbank: [],
      selected: [],
      algo: {
        avlQCount: 0,
        lQCount: 0,
        totalSubtopics: 0,
        perHeadQ: 0
      },
      dialogVisible: false,
      errorMsg: "",
      difficultyQuestionsCount: {
        all: 0,
        easy: 0,
        medium: 0,
        hard: 0
      },
      testQuestionModesData: {
        all: 0,
        used: [],
        favourite: [],
        flagged: [],
        incorrect: [],
        unAttempted: []
      },
      qModeAllDiffCounts: {
        all: 0,
        used: [],
        favourite: [],
        flagged: [],
        incorrect: []
      },
      difftopicsData: [],
      on: true,
      off: false
    };
  },
  computed: {
    isQbankSubscriptionTrial() {
      let q = this.qBanks.find(e => {
        return e.qbank.id == this.newTestForm.qbank_id;
      });
      if (q) {
        return q.subscription_history[0].subscription_type == "Free Trial";
      }
      return false;
    },
    isTestQuestionsSatisfying() {
      return this.newTestForm.testQCount <= this.algo.avlQCount;
    },
    noOfQuestionsStatus() {
      let status = {
        valid: true,
        msg: ""
      };
      if( typeof this.newTestForm.testQCount !== 'number' ){
        status.valid = false;
        status.msg = "minimum 10 questions are requried to continue";
        return status;
      }
      if (this.isQbankSubscriptionTrial) {
        if (parseInt(this.newTestForm.testQCount) > 20) {
          status.valid = false;
          status.msg = "In trial subscription maximum 20 questions are allowed";
        } else if (parseInt(this.newTestForm.testQCount) < 10) {
          status.valid = false;
          status.msg = "minimum 10 questions are requried to continue";
        }
      } else {
        if (parseInt(this.newTestForm.testQCount) > 500) {
          status.valid = false;
          status.msg = "maximum 500 questions are allowed";
        } else if (parseInt(this.newTestForm.testQCount) < 10) {
          status.valid = false;
          status.msg = "minimum 10 questions are requried to continue";
        }
      }
      return status;
    },
    unUsedQsCount() {
      return (
        this.testQuestionModesData.all - this.testQuestionModesData.used.length
      );
    }
  },
  mounted() {
    this.getQbanks();
   
  },
  methods: {
    applyDifficultyFilter(difficulty_id) {
      this.showSkeletonLoader();
      let data = [];
      let diffQuestions = [];
      this.qBankData.forEach(e => {
        let topicQuestions = [];
        let allQs = [];
        let easyQs = [];
        let mediumQs = [];
        let hardQs = [];
        e.qbank_test_subtopic.forEach(el => {
          let paid_easy = JSON.parse(el.paid_easy);
          let paid_medium = JSON.parse(el.paid_medium);
          let paid_hard = JSON.parse(el.paid_hard);
          let paid = [];
          paid = paid.concat(paid_easy);
          paid = paid.concat(paid_medium);
          paid = paid.concat(paid_hard);

          let demo_easy = JSON.parse(el.demo_easy);
          let demo_medium = JSON.parse(el.demo_medium);
          let demo_hard = JSON.parse(el.demo_hard);
          let free = [];
          free = free.concat(demo_easy);
          free = free.concat(demo_medium);
          free = free.concat(demo_hard);

          easyQs.push({
            id: el.id,
            qbank_test_topic_id: el.qbank_test_topic_id,
            topic_id: el.topic_id,
            subtopic_id: el.subtopic_id,
            subtopic: el.subtopic,
            paid: paid_easy,
            demo: demo_easy
          });
          mediumQs.push({
            id: el.id,
            qbank_test_topic_id: el.qbank_test_topic_id,
            topic_id: el.topic_id,
            subtopic_id: el.subtopic_id,
            subtopic: el.subtopic,
            paid: paid_medium,
            demo: demo_medium
          });
          hardQs.push({
            id: el.id,
            qbank_test_topic_id: el.qbank_test_topic_id,
            topic_id: el.topic_id,
            subtopic_id: el.subtopic_id,
            subtopic: el.subtopic,
            paid: paid_hard,
            demo: demo_hard
          });

          allQs.push({
            id: el.id,
            qbank_test_topic_id: el.qbank_test_topic_id,
            topic_id: el.topic_id,
            subtopic_id: el.subtopic_id,
            subtopic: el.subtopic,
            paid: paid,
            demo: free
          });
        });
        switch (difficulty_id) {
          case 0:
            topicQuestions = allQs;
            break;
          case 1:
            topicQuestions = easyQs;
            break;
          case 2:
            topicQuestions = mediumQs;
            break;
          case 3:
            topicQuestions = hardQs;
        }
        diffQuestions = diffQuestions.concat(topicQuestions);
        if (topicQuestions.length > 0) {
          let topic = {
            id: e.id,
            qbank_id: e.qbank_id,
            qbank_test_subtopic: topicQuestions,
            topic: e.topic,
            topic_id: e.topic_id
          };
          data.push(topic);
        }
      });
      switch (difficulty_id) {
        case 0:
          this.testQuestionModesData.all = this.qModeAllDiffCounts.all;
          this.testQuestionModesData.used = this.qModeAllDiffCounts.used;
          this.testQuestionModesData.favourite = this.qModeAllDiffCounts.favourite;
          this.testQuestionModesData.flagged = this.qModeAllDiffCounts.flagged;
          this.testQuestionModesData.incorrect = this.qModeAllDiffCounts.incorrect;
          break;
        case 1:
          this.testQuestionModesData.all = this.difficultyQuestionsCount.easy;
          break;
        case 2:
          this.testQuestionModesData.all = this.difficultyQuestionsCount.medium;
          break;
        case 3:
          this.testQuestionModesData.all = this.difficultyQuestionsCount.hard;
      }
      if (difficulty_id !== 0) {
        this.testQuestionModesData.used = this.extractQuestionsForQModeFilter(
          diffQuestions,
          this.qModeAllDiffCounts.used
        );
        this.testQuestionModesData.favourite = this.extractQuestionsForQModeFilter(
          diffQuestions,
          this.qModeAllDiffCounts.favourite
        );
        this.testQuestionModesData.flagged = this.extractQuestionsForQModeFilter(
          diffQuestions,
          this.qModeAllDiffCounts.flagged
        );
        this.testQuestionModesData.incorrect = this.extractQuestionsForQModeFilter(
          diffQuestions,
          this.qModeAllDiffCounts.incorrect
        );
      }
      this.difftopicsData = [...data];
      this.filterData(data);
      this.newTestForm.questionMode = 0;
      this.hideSkeletonLoader();
    },
    extractQuestionsForQModeFilter(diffQuestions = [], QmodeQuestions = []) {
      let data = [];
      QmodeQuestions.forEach(el => {
        diffQuestions.forEach(e => {
          if (e.paid.includes(el)) {
            data.push(el);
          } else if (e.demo.includes(el)) {
            data.push(el);
          }
        });
      });
      return data;
    },
    filterQuestionsForQMode(
      diffQuestions = [],
      QmodeQuestions = [],
      conditon = null
    ) {
      let data = [];
      let allQs = JSON.parse(JSON.stringify(diffQuestions));
      let uniqueSubtopics = [];
      if (QmodeQuestions.length == 0) {
        return allQs;
      }

      if (conditon) {
        QmodeQuestions.forEach(el => {
          allQs.forEach(e => {
            e.paid = e.paid.filter(d => {
              return el != d;
            });
            e.demo = e.demo.filter(d => {
              return el != d;
            });
            if (!uniqueSubtopics.includes(e.id)) {
              data.push({
                id: e.id,
                qbank_test_topic_id: e.qbank_test_topic_id,
                topic_id: e.topic_id,
                subtopic_id: e.subtopic_id,
                subtopic: e.subtopic,
                paid: e.paid,
                demo: e.demo
              });
              uniqueSubtopics.push(e.id);
            } else {
              let ind = data.findIndex(d => {
                return d.id == e.id;
              });

              data[ind].paid = e.paid;
              data[ind].demo = e.demo;
            }
          });
        });
      } else {
        QmodeQuestions.forEach(el => {
          allQs.forEach(e => {
            if (e.paid.includes(el)) {
              if (!uniqueSubtopics.includes(e.id)) {
                data.push({
                  id: e.id,
                  qbank_test_topic_id: e.qbank_test_topic_id,
                  topic_id: e.topic_id,
                  subtopic_id: e.subtopic_id,
                  subtopic: e.subtopic,
                  paid: [el],
                  demo: []
                });
                uniqueSubtopics.push(e.id);
              } else {
                let ind = data.findIndex(d => {
                  return d.id == e.id;
                });

                data[ind].paid.push(el);
              }
            } else if (e.demo.includes(el)) {
              if (!uniqueSubtopics.includes(e.id)) {
                data.push({
                  id: e.id,
                  qbank_test_topic_id: e.qbank_test_topic_id,
                  topic_id: e.topic_id,
                  subtopic_id: e.subtopic_id,
                  subtopic: e.subtopic,
                  paid: [],
                  demo: [el]
                });
                uniqueSubtopics.push(e.id);
              } else {
                let index = data.findIndex(d => {
                  return d.id == e.id;
                });
                data[index].demo.push(el);
              }
            }
          });
        });
      }

      return data;
    },
    applyQuestionModeFilter(mode) {
      this.showSkeletonLoader();
      let data = [];
      this.difftopicsData.forEach(e => {
        let topicQuestions = [];
        switch (mode) {
          case 0:
            topicQuestions = e.qbank_test_subtopic;
            break;
          case 1:
            topicQuestions = this.filterQuestionsForQMode(
              e.qbank_test_subtopic,
              this.qModeAllDiffCounts.used
            );
            break;
          case 2:
            topicQuestions = this.filterQuestionsForQMode(
              e.qbank_test_subtopic,
              this.qModeAllDiffCounts.used,
              "!="
            );
            break;
          case 3:
            topicQuestions = this.filterQuestionsForQMode(
              e.qbank_test_subtopic,
              this.qModeAllDiffCounts.incorrect
            );
            break;
          case 4:
            topicQuestions = this.filterQuestionsForQMode(
              e.qbank_test_subtopic,
              this.qModeAllDiffCounts.favourite
            );
            break;
          case 5:
            topicQuestions = this.filterQuestionsForQMode(
              e.qbank_test_subtopic,
              this.qModeAllDiffCounts.flagged
            );
            break;
        }
        console.log("topic q ", topicQuestions);
        if (topicQuestions.length > 0) {
          let topic = {
            id: e.id,
            qbank_id: e.qbank_id,
            qbank_test_subtopic: topicQuestions,
            topic: e.topic,
            topic_id: e.topic_id
          };
          data.push(topic);
        }
      });
      console.log(data);

      this.filterData(data);
      this.hideSkeletonLoader();
    },
    filterData(data) {
      let t = this;
      this.newTestForm.testQCount = 20 ;
      this.algo.avlQCount = 0;
      t.selected = [];
      t.topics = [];
      let topicsData = [];
      data.forEach((val, index) => {
        console.log("topic... , ", val);
        let subtopics = [];
        let selectedSubtopics = [];
        let totalTopicQuestions = 0;
        val.qbank_test_subtopic.forEach(e => {
          
          let paid = e.paid;
          let free = e.demo;
          totalTopicQuestions += paid.length + free.length;
          let avlQs = paid.concat(free);
          let totalQsCount=avlQs.length;
          if (this.isQbankSubscriptionTrial) {
            avlQs = free;
          }
          if (totalQsCount > 0) {
            subtopics.push({
              question_count: totalQsCount,
              free_question_count: free.length,
              name: e.subtopic.name,
              subtopic_id: e.subtopic_id
            });
            selectedSubtopics.push({
              id: e.subtopic_id,
              topic_id: val.topic_id,
              isSelected: false,
              avl: avlQs.length,
              d: 0,
              l: 0,
              e: 0,
              questions: avlQs
            });
          }
        });
        if (totalTopicQuestions > 0) {
          topicsData.push({
            id: val.id,
            qbank_id: val.qbank_id,
            qbank_test_subtopic: val.qbank_test_subtopic,
            subtopics: subtopics,
            topic: val.topic,
            topic_id: val.topic_id,
            totalQuestions: totalTopicQuestions
          });
          t.selected.push({
            isSelected: false,
            id: val.topic_id,
            question_count: totalTopicQuestions,
            selectedSubtopics: selectedSubtopics,
            anyChildSelected: false
          });
        }
      });
      t.topics = [...topicsData];
    },
    qbankName(item) {
      return (
        item.qbank.name +
        "   (  " +
        item.subscription_history[0].subscription_type +
        "  )"
      );
    },
    getQbanks: function() {
      this.showSkeletonLoader();
      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.$route.query.id) {
            t.newTestForm.qbank_id = parseInt(t.$route.query.id, 10);
          } else if (t.qBanks.length > 0) {
            t.newTestForm.qbank_id = t.qBanks[0].qbank.id;
          }
          t.hideSkeletonLoader();
          if (t.qBanks.length > 0) {
            t.handleCheckedQbankChange(t.newTestForm.qbank_id);
          }
        })
        .catch(e => {
          t.hideSkeletonLoader();
        });
    },
    handleCheckedQbankChange: function(id) {
      this.showSkeletonLoader();
      let t = this;
      if (id) {
        this.newTestForm.testQCount = this.isQbankSubscriptionTrial ? 20 : 10;
        this.algo.avlQCount = 0;
        this.newTestForm.difficulty = 0;
        this.newTestForm.questionMode = 0;

        let url = `/get-qbank-topics-subtopics/${id}`;
        axios.get(url).then(response => {
          t.difficultyQuestionsCount.easy =
            response.data.qbank_question_info.easy_count;
          t.difficultyQuestionsCount.medium =
            response.data.qbank_question_info.medium_count;
          t.difficultyQuestionsCount.hard =
            response.data.qbank_question_info.hard_count;
          t.difficultyQuestionsCount.all =
            response.data.qbank_question_info.all_count;

          t.testQuestionModesData.all = t.difficultyQuestionsCount.all;
          t.testQuestionModesData.used = JSON.parse(
            response.data.qbank_test_question_modes.used
          );
          t.testQuestionModesData.favourite = JSON.parse(
            response.data.qbank_test_question_modes.favourite
          );
          t.testQuestionModesData.flagged = JSON.parse(
            response.data.qbank_test_question_modes.flagged
          );
          t.testQuestionModesData.incorrect = JSON.parse(
            response.data.qbank_test_question_modes.incorrect
          );
          t.testQuestionModesData.unAttempted = JSON.parse(
            response.data.qbank_test_question_modes.un_attempted
          );

          t.qModeAllDiffCounts.all = t.difficultyQuestionsCount.all;
          t.qModeAllDiffCounts.used = JSON.parse(
            response.data.qbank_test_question_modes.used
          );
          t.qModeAllDiffCounts.favourite = JSON.parse(
            response.data.qbank_test_question_modes.favourite
          );
          t.qModeAllDiffCounts.flagged = JSON.parse(
            response.data.qbank_test_question_modes.flagged
          );
          t.qModeAllDiffCounts.incorrect = JSON.parse(
            response.data.qbank_test_question_modes.incorrect
          );

          t.selected = [];
          t.topics = [];
          t.qBankData = response.data.qbank_test_topic;
          this.hideSkeletonLoader();
          t.applyDifficultyFilter(0);
        });
      } else {
        t.topics = [];
        t.hideSkeletonLoader();
      }
    },
    createTest() {
      this.startLoader("Creating test.Please Hang on...");
      if (!this.noOfQuestionsStatus.valid) {
        this.stopLoader();
        this.errorMsg = this.noOfQuestionsStatus.msg;
        this.dialogVisible = true;
        return;
      }
      if (!this.isTestQuestionsSatisfying) {
        this.stopLoader();
        this.errorMsg = "insufficient number of Questions selected";
        this.dialogVisible = true;
        return;
      }
      
      let data = this.applyAlgorithm();
      console.log(this.algo);

      let t = this;
      let examId = Math.ceil(Math.random() * 10000) + new Date().getTime(); //assign Exam Id
      let examObject = {
        info: "",
        data: [],
        exam: [],
        newQs: [],
        newUnAttempted: []
      };

      data.forEach((val, index) => {
        examObject.data.push({
          ques_id: val.question_id,
          isSubmit: false,
          selectedAnswer: ["0"],
          isFlagged: false,
          isFavorited: false,
          correctAnswer: "",
          questionNote: "",
          isUsed: false,
          timeConsume: 0,
          totalTime: 0,
          isNoteShow: false,
          isCalculatorShow: false,
          topic_id: val.topic_id,
          subtopic_id: val.subtopic_id
        });
        if (!this.testQuestionModesData.used.includes(val.question_id)) {
          examObject.newQs.push(val.question_id);
        }
        if (!this.testQuestionModesData.unAttempted.includes(val.question_id)) {
          examObject.newUnAttempted.push(val.question_id);
        }
      });
      //   return;
      //prepare exam information
      examObject.info = {
        status:'Not Started',
        exam_id: examId,
        totalTime: 0,
        remainingTime: 0,
        isOpenSideBar: false,
        fontSize: "16px",
        currentQuestionIndex: 0,
        isBlack: false,
        qbank_id: t.newTestForm.qbank_id,
        isTimed: t.newTestForm.timed ? true : false,
        isTutor: t.newTestForm.tutor,
        questionLimit: t.newTestForm.testQCount,
        isDemo: t.isQbankSubscriptionTrial
      };

      console.log(examObject);
      axios.post("/create-test", examObject).then(res => {
          this.stopLoader();
          this.$router.push({
            name: "qbank-test-app",
            params: {
              test_id: res.data.test_id
            }
          });
      })
      .catch(e=>{
        this.stopLoader();
        
      })
    },
    applyAlgorithm() {
      let subtopics = this.getSelectedSubTopics();
      this.algo.totalSubtopics = subtopics.length;
      this.algo.perHeadQ = Math.ceil(
        this.newTestForm.testQCount / this.algo.totalSubtopics
      );
      this.algo.lQCount = 0;

      subtopics.forEach((e, i) => {
        if (this.algo.perHeadQ <= e.avl) {
          subtopics[i].d = this.algo.perHeadQ;
          subtopics[i].e = e.avl - this.algo.perHeadQ;
          subtopics[i].l = 0;
        } else if (this.algo.perHeadQ > e.avl) {
          subtopics[i].d = this.algo.perHeadQ;
          subtopics[i].e = 0;
          subtopics[i].l = this.algo.perHeadQ - e.avl;
          this.algo.lQCount += this.algo.perHeadQ - e.avl;
        }
      });
      console.log("less " + this.algo.lQCount);
      for (let i = 0; i < subtopics.length; i++) {
        if (subtopics[i].e > 0 && this.algo.lQCount != 0) {
          if (this.algo.lQCount <= subtopics[i].e) {
            subtopics[i].e -= this.algo.lQCount;
            subtopics[i].d += this.algo.lQCount;
            this.algo.lQCount = 0;
          } else {
            subtopics[i].d += subtopics[i].e;
            this.algo.lQCount -= subtopics[i].e;
            subtopics[i].e = 0;
          }
        } else {
          subtopics[i].d -= subtopics[i].l;
          subtopics[i].l = 0;
        }
      }
      let questions = [];

      subtopics.forEach(e => {
        let ques = [...e.questions];
        let q = ques.slice(0, e.d);
        console.log("s : ", e);
        console.log("q length: ", q.length);
        q.forEach(el => {
          questions.push({
            topic_id: e.topic_id,
            subtopic_id: e.id,
            question_id: el
          });
        });
      });

      return questions.slice(0, this.newTestForm.testQCount);
    },
    getSelectedTopics() {
      return this.selected.filter(e => {
        return e.isSelected == true || e.anyChildSelected == true;
      });
    },
    getSelectedSubTopics() {
      let topics = [];
      topics = this.getSelectedTopics();
      let subtopics = [];
      topics.forEach(e => {
        if (e.anyChildSelected) {
          let s = e.selectedSubtopics.filter(el => {
            return el.isSelected == true;
          });
          s.forEach(ele => {
            subtopics.push(ele);
          });
        } else {
          e.selectedSubtopics.forEach(ele => {
            subtopics.push(ele);
          });
        }
      });
      return subtopics;
    },
    isAllSubtopicsChecked(index) {
      let checked = this.selected[index].selectedSubtopics.filter(e => {
        return e.isSelected == true;
      });
      return checked.length == this.selected[index].selectedSubtopics.length;
    },
    isAnySubtopicsChecked(index) {
      let checked = this.selected[index].selectedSubtopics.filter(e => {
        return e.isSelected == true;
      });
      return checked.length > 0;
    },
    handleSubtopicSelectionChange(checked, index, ind) {
      let q = this.selected[index].selectedSubtopics[ind].avl;
      if (checked) {
        this.algo.avlQCount = this.algo.avlQCount + q;
        if (this.isAllSubtopicsChecked(index)) {
          this.selected[index].isSelected = true;
          this.selected[index].anyChildSelected = false;
        } else {
          this.selected[index].anyChildSelected = true;
        }
      } else {
        this.algo.avlQCount = this.algo.avlQCount - q;
        this.selected[index].isSelected = false;
        if (this.isAnySubtopicsChecked(index)) {
          this.selected[index].anyChildSelected = true;
        } else {
          this.selected[index].anyChildSelected = false;
        }
      }
    },
    handleTopicSelectionChange(checked, index) {
      if (checked) {
        this.selected[index].selectedSubtopics.forEach((val, ind) => {
          this.selected[index].selectedSubtopics[ind].isSelected = true;
        });
        this.selected[index].anyChildSelected = false;
        this.algo.avlQCount =
          this.algo.avlQCount + this.selected[index].question_count;
      } else {
        this.selected[index].selectedSubtopics.forEach((val, ind) => {
          this.selected[index].selectedSubtopics[ind].isSelected = false;
        });
        this.algo.avlQCount =
          this.algo.avlQCount - this.selected[index].question_count;
      }
    },
    close() {
      this.dialogVisible = false;
    }
  },
  watch: {
    "newTestForm.difficulty": function(newVal, oldVal) {
      this.applyDifficultyFilter(newVal);
    },
    "newTestForm.questionMode": function(newVal, oldVal) {
      this.applyQuestionModeFilter(newVal);
    }
  }
};
</script>

<style lang="css" scoped>
.q-checkbox__inner--indet >>> .q-checkbox__inner {
  color: #1976d2;
}
.inline-block {
  display: inline-block !important;
}
.hide {
  display: none;
}

.show {
  display: inline;
}

.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>
