    <template>
  <v-app id="pages-dasboard">
    <v-tabs grow slider-color="gray">
      <v-tab
        ripple
        @click="activeTab('existing')"
        v-bind:class="{ active: isActive }"
        id="tab"
        class="subheading"
      >Existing Mark</v-tab>
      <v-tab
        ripple
        @click="activeTab('new')"
        v-bind:class="{ active: newActive }"
        id="tab1"
        User
        class="subheading"
      >Add Mark</v-tab>

      <!-- ****** Edit Mark ****** -->

      <v-tab-item>
        <v-snackbar
          :timeout="timeout"
          :top="y === 'top'"
          :right="x === 'right'"
          :vertical="mode === 'vertical'"
          v-model="snackbar"
          color="success"
        >{{ text }}</v-snackbar>

        <!-- ****** EXISTING MARK TABLE ****** -->

        <v-card flat>
          <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-4">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">
            <td class="text-xs-center">{{ props.index + 1}}</td>
            <td id="td" class="text-xs-center">
              <v-avatar>
                <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 id="td" class="text-xs-center">{{ props.item.name}}</td>
            <td id="td" class="text-xs-center">{{ props.item.rollNo }}</td>
            <td id="td" class="text-xs-center">{{ props.item.email }}</td>
            <td class="text-xs-center">
              <span>
                <router-link :to="{ name:'viewMark',params: { markId:props.item._id } }">
                  <v-tooltip top>
                    <img
                      slot="activator"
                      style="cursor:pointer; width:20px; height:18px; "
                      class="mr-5"
                      src="/static/icon/edit1.png"
                    />
                    <span>Edit</span>
                  </v-tooltip>
                </router-link>
              </span>
            </td>
          </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-tab-item>

      <!-- ****** ADD  Mark Schedule ****** -->

      <v-tab-item>
        <v-snackbar
          :timeout="timeout"
          :top="y === 'top'"
          :right="x === 'right'"
          :vertical="mode === 'vertical'"
          v-model="snackbar"
          :color="color"
        >{{ text }}</v-snackbar>
        <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"
                    >Mark</v-btn>
                  </v-flex>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-card class="mt-4">
              <v-data-table
                :headers="headerOfMark"
                :items="getStudentData"
                :pagination.sync="pagination"
                :search="search"
              >
                <template slot="items" slot-scope="props">
                  <td class="text-xs-center">{{ props.index + 1}}</td>
                  <td id="td" class="text-xs-center">
                    <v-avatar>
                      <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 id="td" class="text-xs-center">{{ props.item.name}}</td>
                  <td id="td" class="text-xs-center">{{ props.item.rollNo }}</td>
                  <td
                    id="td"
                    class="text-xs-center markTable"
                    v-for="(marks, index) in props.item.marksObtained"
                    :key="'A'+ index"
                  >
                    <v-text-field v-model="marks.marksScored"></v-text-field>
                  </td>
                </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 Mark</v-btn>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-form>
      </v-tab-item>
    </v-tabs>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
  </v-app>
</template>

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

export default {
  data: () => ({
    snackbar: false,
    date: null,
    color: "",
    y: "top",
    x: "right",
    mode: "",
    timeout: 10000,
    text: "",
    loading: false,
    search: "",
    showLoader: false,
    dialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    addSection: [],
    pagination: {
      rowsPerPage: 15
    },
    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: "justify-center",
        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: "justify-center",
        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: {
    activeTab(type) {
      switch (type) {
        case "existing":
          this.newActive = false;
          this.isActive = true;
          break;

        default:
          this.newActive = true;
          this.isActive = false;
          break;
      }
    },
    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 => {
          // 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);
          }
        });
    },
    clear() {
      this.$refs.form.reset();
    },
    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 => {
                console.log("err====>", error);
                this.showLoader = false;
              });
          })
          .catch(error => {
            console.log("err====>", 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.text = response.data.message;
            this.color = "green";
            this.loading = false;
            this.clear();
          })
          .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;
          // console.log("getSectionsList=====>", response.data.data);
        })
        .catch(error => {
          console.log("err====>", error);
          this.showLoader = false;
        });
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getClass();
    this.getExamList();
  },
  created() {
    this.$root.$on("app:search", search => {
      this.search = search;
    });
  },
  beforeDestroy() {
    // dont forget to remove the listener
    this.$root.$off("app:search");
  }
};
</script>
<style scoped>
.active {
  background-color: gray;
  color: white !important;
}
.activebtn {
  color: black !important;
}
.markTable {
  max-width: 80px !important;
}
</style>





















