<template>
  <v-container fluid class="body-color">
    <!-- ****** EXISTING MARK TABLE ****** -->
    <v-toolbar color="transparent" flat>
      <v-btn
        fab
        dark
        class="open-dialog-button hidden-xl-only hidden-md-only hidden-lg-only"
        small
        @click="addMarkDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addMarkDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Mark
      </v-btn>
      <v-layout class="hidden-sm-only hidden-xs-only">
        <v-flex md3 lg2 class="ml-2">
          <v-select
            v-model="getMark.classId"
            label="Select your class"
            type="text"
            :items="classList"
            item-text="classNum"
            item-value="_id"
            @change="getSections(getMark.classId)"
            required
          ></v-select>
        </v-flex>
        <v-flex md3 lg2 class="ml-2">
          <v-select
            :items="addSection"
            label="Select your Section"
            v-model="getMark.sectionId"
            item-text="name"
            item-value="_id"
            name="Select Section"
            required
          ></v-select>
        </v-flex>
        <v-spacer></v-spacer>
        <v-btn
          @click="getStudents"
          round
          dark
          :loading="loading"
          class="right open-dialog-button mt-2"
        >Mark</v-btn>
      </v-layout>
      <v-spacer class="hidden-lg-only hidden-xl-only hidden-md-only"></v-spacer>
      <v-card-title class="body-1" v-show="show">
        <v-btn icon large flat @click="displaySearch">
          <v-avatar size="27">
            <img src="/static/icon/dashboard icons-49.png" alt="icon" />
          </v-avatar>
        </v-btn>
      </v-card-title>
      <v-flex xs8 sm8 md3 lg2 v-show="showSearch">
        <v-layout>
          <v-text-field v-model="search" label="Search" prepend-inner-icon="search" color="primary"></v-text-field>
          <v-icon @click="closeSearch" color="error">close</v-icon>
        </v-layout>
      </v-flex>
    </v-toolbar>
    <v-card flat class="elevation-0 transparent hidden-lg-only hidden-xl-only hidden-md-only">
      <v-flex xs12 sm12 lg12>
        <v-layout wrap>
          <v-flex xs12 sm12 lg3>
            <v-layout>
              <v-flex xs3 sm6 lg2 class="subheading mt-4">
                <label class="right">Class:</label>
              </v-flex>
              <v-flex xs12 sm12 lg8 class="ml-2">
                <v-select
                  v-model="getMark.classId"
                  label="Select your class"
                  type="text"
                  :items="classList"
                  item-text="classNum"
                  item-value="_id"
                  @change="getSections(getMark.classId)"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
          </v-flex>
          <v-flex xs12 sm12 lg3>
            <v-layout>
              <v-flex xs3 sm6 lg2 class="subheading mt-4">
                <label class="right">Section:</label>
              </v-flex>
              <v-flex xs12 sm12 lg8 class="ml-2">
                <v-select
                  :items="addSection"
                  label="Select your Section"
                  v-model="getMark.sectionId"
                  item-text="name"
                  item-value="_id"
                  name="Select Section"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
          </v-flex>
          <v-flex xs12 sm12 lg6>
            <v-btn
              @click="getStudents"
              round
              dark
              :loading="loading"
              class="right mt-3 open-dialog-button"
            >Mark</v-btn>
          </v-flex>
        </v-layout>
      </v-flex>
    </v-card>
    <v-data-table
      :headers="headers"
      :items="getStudentsList"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr">
          <td class="td td-row">{{ props.index + 1}}</td>
          <td class="td td-row text-xs-center">
            <v-avatar size="40">
              <img :src="props.item.profilePicUrl" v-if="props.item.profilePicUrl" />
              <img src="/static/icon/user.png" v-else-if="!props.item.profilePicUrl" />
            </v-avatar>
          </td>
          <td class="td td-row text-xs-center">{{ props.item.name}}</td>
          <td class="td td-row text-xs-center">{{ props.item.rollNo }}</td>
          <td class="td td-row text-xs-center">{{ props.item.email }}</td>
          <td class="td td-row text-xs-center">
            <span>
              <router-link :to="{ name:'view Mark',params: { markId:props.item._id } }">
                <v-tooltip top>
                  <img
                    slot="activator"
                    style="cursor:pointer; width:25px; height:25px; "
                    src="/static/icon/dashboard icons-47.png"
                  />
                  <span>View</span>
                </v-tooltip>
              </router-link>
            </span>
          </td>
        </tr>
      </template>
      <v-alert
        slot="no-results"
        :value="true"
        color="error"
        icon="warning"
      >Your search for "{{ search }}" found no results.</v-alert>
    </v-data-table>
    <!-- ****** ADD  Mark Schedule ****** -->
    <v-dialog v-model="addMarkDialog" max-width>
      <v-card flat class>
        <v-layout class="pa-3 card-style white--text">
          <v-flex xs12>
            <label class="title text-xs-center">Add Mark</label>
            <v-icon size="24" class="right white--text" @click="addMarkDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-form ref="form" v-model="valid" lazy-validation>
          <v-container fluid>
            <v-flex xs12 sm12 lg12>
              <v-layout wrap>
                <v-flex xs12 sm12 lg10>
                  <v-layout wrap>
                    <v-flex xs12 sm12 lg3>
                      <v-flex xs3 sm2 lg2 class="subheading">
                        <label>Exam:</label>
                      </v-flex>
                      <v-flex xs12 sm12 lg10>
                        <v-select
                          label="Select your Exam Name"
                          :items="examList"
                          v-model="addMark.examId"
                          :rules="examRules"
                          item-text="examName"
                          item-value="_id"
                        ></v-select>
                      </v-flex>
                    </v-flex>
                    <v-flex xs12 sm12 lg3>
                      <v-flex xs3 sm6 lg2 class="subheading">
                        <label>Class:</label>
                      </v-flex>
                      <v-flex xs12 sm12 lg10 class>
                        <v-select
                          v-model="addMark.classId"
                          label="Select your class"
                          type="text"
                          :items="classList"
                          item-text="classNum"
                          item-value="_id"
                          :rules="classRules"
                          @change="getSections(addMark.classId)"
                          required
                        ></v-select>
                      </v-flex>
                    </v-flex>
                    <v-flex xs12 sm12 lg3>
                      <v-flex xs3 sm6 lg2 class="subheading">
                        <label>Section:</label>
                      </v-flex>
                      <v-flex xs12 sm12 lg10 class>
                        <v-select
                          :items="addSection"
                          label="Select your Section"
                          v-model="addMark.sectionId"
                          item-text="name"
                          item-value="_id"
                          name="Select Section"
                          :rules="sectionRules"
                          required
                        ></v-select>
                      </v-flex>
                    </v-flex>
                    <v-flex xs12 sm12 lg3>
                      <v-flex xs3 sm6 lg2 class="subheading">
                        <label>Subject:</label>
                      </v-flex>
                      <v-flex xs12 sm12 lg10 class>
                        <v-select
                          :items="subjects"
                          label="Select your Subject"
                          v-model="addMark.subjectId"
                          item-text="subjectName"
                          item-value="_id"
                          name="Select Section"
                          :rules="subjectRules"
                          required
                        ></v-select>
                      </v-flex>
                    </v-flex>
                  </v-layout>
                </v-flex>
                <v-flex xs12 sm12 lg2>
                  <v-flex xs12 sm12 lg12>
                    <v-btn
                      @click="findStudents"
                      round
                      dark
                      :loading="loading"
                      class="right mt-4 open-dialog-button"
                    >Mark</v-btn>
                  </v-flex>
                </v-flex>
              </v-layout>
            </v-flex>
            <!-- ****** ADD  MARK TABLE DATA ****** -->
            <v-card class="mt-4 elevation-0 body-color">
              <v-data-table
                :headers="headerOfMark"
                :items="getStudentData"
                :pagination.sync="pagination"
                :search="search"
                class="body-color"
              >
                <template slot="items" slot-scope="props">
                  <tr class="tr">
                    <td class="td td-row">{{ props.index + 1}}</td>
                    <td class="text-xs-center td td-row">
                      <v-avatar size="40">
                        <img :src="props.item.profilePicUrl" v-if="props.item.profilePicUrl" />
                        <img src="/static/icon/user.png" v-else-if="!props.item.profilePicUrl" />
                      </v-avatar>
                    </td>
                    <td class="text-xs-center td td-row">{{ props.item.name}}</td>
                    <td class="text-xs-center td td-row">{{ props.item.rollNo }}</td>
                    <td
                      class="text-xs-center markTable td td-row"
                      v-for="(marks, index) in props.item.marksObtained"
                      :key="'A'+ index"
                    >
                      <v-text-field v-model="marks.marksScored"></v-text-field>
                    </td>
                  </tr>
                </template>
                <v-alert
                  slot="no-results"
                  :value="true"
                  color="error"
                  icon="warning"
                >Your search for "{{ search }}" found no results.</v-alert>
              </v-data-table>
            </v-card>
            <v-layout class="mt-2">
              <v-flex xs12 sm12>
                <v-layout>
                  <v-flex xs12>
                    <v-btn
                      @click="submit"
                      round
                      dark
                      :loading="loading"
                      class="right add-button"
                    >Add Mark</v-btn>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-form>
      </v-card>
    </v-dialog>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ text }}</v-snackbar>
  </v-container>
</template>

<script>
import http from "@/Services/http.js";
import moment from "moment";

export default {
  data: () => ({
    show: true,
    showSearch: false,
    snackbar: false,
    date: null,
    color: "",
    y: "top",
    x: "right",
    mode: "",
    timeout: 10000,
    text: "",
    loading: false,
    search: "",
    show: true,
    showSearch: false,
    showLoader: false,
    dialog: false,
    dialog1: false,
    valid: true,

    addMarkDialog: false,
    addSection: [],
    pagination: {
      rowsPerPage: 10
    },
    classRules: [v => !!v || "Class is required"],
    sectionRules: [v => !!v || "section is required"],
    subjectRules: [v => !!v || "Subject is required"],
    examRules: [v => !!v || "Exam is required"],

    headerOfMark: [
      {
        align: "",
        text: "No",
        sortable: false,
        value: "No"
      },
      {
        text: "Profile Pic",
        vaue: "profilePicUrl",
        sortable: false,
        align: "center"
      },
      {
        text: "Name",
        vaue: "name",
        sortable: false,
        align: "center"
      },
      {
        text: "Roll No.",
        value: "rollNo",
        sortable: false,
        align: "center"
      }
    ],
    headers: [
      {
        align: "",
        text: "No",
        sortable: false,
        value: "No"
      },
      {
        text: "Profile Pic",
        vaue: "profilePicUrl",
        sortable: false,
        align: "center"
      },
      {
        text: "Name",
        vaue: "name",
        sortable: false,
        align: "center"
      },
      {
        text: "Roll No.",
        value: "rollNo",
        sortable: false,
        align: "center"
      },
      {
        text: "Email",
        value: "email",
        sortable: false,
        align: "center"
      },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    classList: [],
    examList: [],
    subjects: [],
    addMark: {},
    getMark: {},
    getScheduleData: {},
    markData: [],
    getStudentData: [],
    getStudentsList: [],
    token: ""
  }),
  methods: {
    getClass() {
      this.showLoader = true;
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.classList = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          // console.log("err====>", err);
          this.showLoader = false;
        });
    },
    getSections(_id) {
      this.showLoader = true;
      for (let i = 0; i < this.classList.length; i++) {
        if (_id == this.classList[i]._id) {
          this.subjects = this.classList[i].subjects;
        }
      }
      http()
        .get(
          "/getSectionsList",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.addSection = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          this.showLoader = false;
          // console.log("err====>", err);
        });
    },
    getExamList() {
      this.showLoader = true;
      this.loadingSearch = true;
      http()
        .get("/getExamsList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.examList = response.data.data;
          this.showLoader = false;
          this.loadingSearch = false;
        })
        .catch(error => {
          // console.log("err====>", err);
          this.showLoader = false;
          this.loadingSearch = false;
          this.snackbar = true;
          this.text = error.response.data.message;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
            this.$store.dispatch("Role", null);
          }
        });
    },
    findStudents() {
      this.getStudentData = [];
      if (this.$refs.form.validate()) {
        this.showLoader = true;
        http()
          .get("/getStudentWithClass", {
            params: {
              classId: this.addMark.classId,
              sectionId: this.addMark.sectionId
            }
          })
          .then(response => {
            this.getStudentData = response.data.data;
            this.showLoader = false;
            this.showLoader = true;
            http()
              .get("/getMarkDistributionsList", {
                params: this.addMark
              })
              .then(response => {
                this.showLoader = false;
                this.headerOfMark.length = 4;
                for (var i = 0; i < response.data.data.length; i++) {
                  this.headerOfMark.push({
                    text:
                      response.data.data[i].distributionType +
                      " (" +
                      response.data.data[i].markValue +
                      ")",
                    sortable: false,
                    align: "center"
                  });
                }
                for (var n = 0; n < this.getStudentData.length; n++) {
                  this.getStudentData[n].marksObtained = [];
                  for (var j = 0; j < response.data.data.length; j++) {
                    this.getStudentData[n].marksObtained.push({
                      markDistributionId: response.data.data[j]._id,
                      marksScored: 0
                    });
                  }
                }
              })
              .catch(error => {
                this.showLoader = false;
              });
          })
          .catch(error => {
            this.showLoader = false;
          });
      }
    },
    submit() {
      for (var j = 0; j < this.getStudentData.length; j++) {
        let data = {
          examId: this.addMark.examId,
          classId: this.addMark.classId,
          sectionId: this.addMark.sectionId,
          subjectId: this.addMark.subjectId,
          studentId: this.getStudentData[j]._id,
          studentsMarks: this.getStudentData[j].marksObtained
        };
        http()
          .post("/createMark", data)
          .then(response => {
            this.getStudentData = [];
            this.snackbar = true;
            this.addMarkDialog = false;
            this.text = response.data.message;
            this.color = "green";
            this.loading = false;
          })
          .catch(error => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "red";
          });
      }
    },
    getStudents() {
      this.showLoader = true;
      http()
        .get("/getStudentWithClass", {
          params: {
            classId: this.getMark.classId,
            sectionId: this.getMark.sectionId
          }
        })
        .then(response => {
          this.getStudentsList = response.data.data;
          this.showLoader = false;
        })
        .catch(error => {
          console.log("err====>", error);
          this.showLoader = false;
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getClass();
    this.getExamList();
  }
};
</script>
<style scoped>
.markTable {
  max-width: 80px !important;
}
</style>





















