<template>
  <v-container fluid class="body-color">
    <!-- ****** EDIT  Assignment ****** -->
    <v-dialog v-model="editAssignmentDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Assignment</label>
            <v-icon size="24" class="right" @click="editAssignmentDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-form ref="formEditAssignment" v-model="validEditAssignment" lazy-validation>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Title:</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-text-field v-model="editedItem.title" type="text" :rules="titleRules" required></v-text-field>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Description:</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-text-field
                  v-model="editedItem.description"
                  type="text"
                  :rules="deadlineRules"
                  required
                ></v-text-field>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Deadline:</label>
              </v-flex>
              <v-flex xs8 class="pt-4 subheading">
                <v-menu
                  ref="menu1"
                  :close-on-content-click="false"
                  v-model="menu1"
                  :nudge-right="40"
                  :return-value.sync="menu1"
                  lazy
                  transition="scale-transition"
                  offset-y
                  full-width
                  min-width="290px"
                >
                  <v-text-field
                    slot="activator"
                    v-model="editedItem.deadline"
                    label="Select Date"
                    :rules="deadlineRules"
                    append-icon="event"
                    required
                  ></v-text-field>
                  <v-date-picker v-model="editedItem.date" @input="menu1 = false"></v-date-picker>
                </v-menu>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Class:</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-select
                  :items="classList"
                  item-text="classNum"
                  item-value="_id"
                  :rules="classRules"
                  v-model="editedItem.classId"
                  @change="getSections(addAssignment.classId)"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Section:</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-select
                  :items="addSection"
                  item-text="name"
                  item-value="_id"
                  v-model="editedItem.sectionId"
                  :rules="sectionRules"
                  @change="getClassSubject(addAssignment.classId)"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Subject</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-select
                  :items="subjectList.subjects"
                  v-model="editedItem.subjectName"
                  item-text="subjectName"
                  item-value="_id"
                  :rules="subjectRules"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right hidden-xs-only hidden-sm-only">Uplaod File:</label>
                <label class="right hidden-lg-only hidden-md-only hidden-xl-only">File :</label>
              </v-flex>
              <v-flex xs8 sm8 class="ml-3">
                <v-text-field
                  label="Select File"
                  @click="pickFile"
                  v-model="imageName"
                  append-icon="attach_file"
                ></v-text-field>
              </v-flex>
            </v-layout>
            <v-flex xs12 sm12>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn round dark @click="save" :loading="editLoading" class="add-button">Save</v-btn>
              </v-card-actions>
            </v-flex>
          </v-form>
        </v-container>
      </v-card>
    </v-dialog>

    <!-- ****** VIEW PROFIL NOTICE BOARD ******  -->
    <v-dialog v-model="viewAssignmentDialog" max-width="500px">
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Attendence</label>
            <v-icon size="24" class="right" @click="viewAssignmentDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex>
                <v-layout>
                  <v-flex xs6 sm4>
                    <h5 class="right my-1">
                      <b>Title:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm8 xs6>
                    <h5 class="my-1">{{ editedItem.title }}</h5>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs6 sm4>
                    <h5 class="right my-1">
                      <b>Description:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm8 xs6>
                    <h5 class="my-1">{{ editedItem.description }}</h5>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs6 sm4>
                    <h5 class="right my-1">
                      <b>Deadline:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm8 xs6>
                    <h5 class="my-1">{{ dates(editedItem.deadline) }}</h5>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- ****** EXISTING ASSIGNMENT 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="addAssignmentDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-flex xs1 class="hidden-sm-only hidden-xs-only">
        <v-btn round class="open-dialog-button" dark @click="addAssignmentDialog = true">
          <v-icon class="white--text pr-1" size="20">add</v-icon>Add Assignment
        </v-btn>
      </v-flex>
      <v-spacer></v-spacer>
      <v-flex lg2 md2 xs12 v-show="show">
        <v-select
          :items="classList"
          label="Select Your Class"
          v-model="addAssignment.classId"
          item-text="classNum"
          item-value="_id"
          name="Select Class"
          :rules="classRules"
          @change="getAssignmentList()"
          class="pl-2"
          required
        ></v-select>
      </v-flex>
      <v-card-title class="body-1" v-show="show">
        <v-btn icon flat @click="displaySearch">
          <v-avatar size="27">
            <img src="/static/icon/search.png" alt="icon" />
          </v-avatar>
        </v-btn>
      </v-card-title>
      <v-flex xs9 sm9 md2 lg2 xl2 v-show="showSearch">
        <v-layout>
          <v-text-field
            v-model="search"
            label="Search"
            prepend-inner-icon="search"
            color="primary"
            style="transition: 0.8s cubic-bezier(0.25, 0.8, 0.25, 1); !important"
          ></v-text-field>
          <v-icon @click="closeSearch" color="error">close</v-icon>
        </v-layout>
      </v-flex>
    </v-toolbar>
    <v-data-table
      :headers="headers"
      :items="assignmentData"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr">
          <td class="td-row td">{{ props.index + 1 }}</td>
          <td class="text-xs-center td td-row">{{ props.item.title }}</td>
          <td class="text-xs-center td td-row">{{ props.item.description }}</td>
          <td class="text-xs-center td td-row">{{ props.item.deadline }}</td>
          <td class="text-xs-center td td-row">{{ props.item.sectionId.name }}</td>
          <td
            class="text-xs-center td td-row"
            v-if="role != 'ADMIN' "
          >{{ props.item.teacherId.name }}</td>
          <td
            class="text-xs-center td td-row"
            v-if="role != 'TEACHER' "
          >{{ props.item.schoolId .name }}</td>
          <td class="text-xs-center td td-row">
            <v-btn
              class="add-button"
              @click="generatePDF2Canvas(props.item)"
              :loading="loadingPdf"
              dark
            >{{ props.item.fileType }}</v-btn>
          </td>
          <td class="text-xs-center td td-row">
            <span>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:25px; height:25px; "
                  class="mr-3"
                  @click="profile(props.item)"
                  src="/static/icon/view.png"
                />
                <span>View</span>
              </v-tooltip>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:18px; "
                  class="mr-3"
                  @click="editItem(props.item)"
                  src="/static/icon/edit.png"
                />
                <span>Edit</span>
              </v-tooltip>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:20px; "
                  class="mr-3"
                  @click="deleteItem(props.item)"
                  src="/static/icon/delete.png"
                />
                <span>Delete</span>
              </v-tooltip>
            </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 MULTIPLE Subject ****** -->
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ text }}</v-snackbar>
    <v-dialog v-model="addAssignmentDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Assignment</label>
            <v-icon size="24" class="right" @click="addAssignmentDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid fill-height>
          <v-layout align-center>
            <v-flex xs12>
              <v-form ref="form" v-model="valid" lazy-validation>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Title :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-3">
                    <v-text-field
                      name="name"
                      type="text"
                      label="Select Title"
                      :rules="titleRules"
                      v-model="addAssignment.title"
                      required
                    ></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Description :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-3">
                    <v-text-field
                      name="name"
                      type="text"
                      label="Select Description"
                      :rules="descriptionRules"
                      v-model="addAssignment.description"
                      required
                    ></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Deadline :</label>
                  </v-flex>
                  <v-flex xs8 sm7 class="ml-3">
                    <v-menu
                      ref="menu2"
                      :close-on-content-click="false"
                      v-model="menu2"
                      :nudge-right="40"
                      :return-value.sync="addAssignment.date"
                      lazy
                      transition="scale-transition"
                      offset-y
                      full-width
                      min-width="290px"
                    >
                      <v-text-field
                        slot="activator"
                        v-model="addAssignment.deadline"
                        :rules="deadlineRules"
                        label="Select Date"
                        append-icon="event"
                        readonly
                      ></v-text-field>
                      <v-date-picker
                        v-model="addAssignment.deadline"
                        @input="$refs.menu2.save(addAssignment.date)"
                      ></v-date-picker>
                    </v-menu>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Class :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-3">
                    <v-select
                      :items="classList"
                      label="Select Class"
                      item-text="classNum"
                      item-value="_id"
                      v-model="addAssignment.classId"
                      name="Select Class"
                      :rules="classRules"
                      @change="getSections(addAssignment.classId)"
                      class="pl-2"
                      required
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Section :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-3">
                    <v-select
                      :items="addSection"
                      label="Select Section"
                      item-text="name"
                      item-value="_id"
                      v-model="addAssignment.sectionId"
                      name="Select Section"
                      :rules="sectionRules"
                      @change="getClassSubject(addAssignment.classId)"
                      class="px-2"
                      required
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs3 sm4 class="pt-4 subheading">
                    <label class="right">Subject :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-2">
                    <v-select
                      :items="subjectList.subjects"
                      label="Select your subject"
                      v-model="addAssignment.subjectName"
                      item-text="subjectName"
                      item-value="_id"
                      :rules="subjectRules"
                      required
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 class="pt-4 subheading">
                    <label class="right hidden-xs-only hidden-sm-only">Uplaod File:</label>
                    <label class="right hidden-lg-only hidden-md-only hidden-xl-only">File:</label>
                  </v-flex>
                  <v-flex xs8 class="ml-3">
                    <v-text-field
                      label="Select File"
                      @click="pickFile"
                      v-model="imageName"
                      append-icon="attach_file"
                    ></v-text-field>
                    <input
                      type="file"
                      style="display:none"
                      ref="image"
                      accept="image/*"
                      @change="onFilePicked"
                    />
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs12 sm12>
                    <v-card-actions>
                      <v-spacer></v-spacer>
                      <v-btn
                        @click="submit"
                        round
                        dark
                        :loading="loading"
                        class="add-button"
                      >Add Assignment</v-btn>
                    </v-card-actions>
                  </v-flex>
                </v-layout>
              </v-form>
            </v-flex>
          </v-layout>
        </v-container>
      </v-card>
    </v-dialog>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
  </v-container>
</template>

<script>
import http from "@/Services/http.js";
import Util from "@/util";
import moment from "moment";
import jsPDF from "jspdf";
import { saveAs } from "file-saver";


export default {
  data: () => ({
    snackbar: false,
    role: "",
    menu1: false,
    menu2: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    color: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    editLoading: false,
    date: null,
    search: "",
    viewAssignmentDialog: false,
    editAssignmentDialog: false,
    valid: true,
    validEditAssignment: true,
    addAssignmentDialog: false,

    pagination: {
      rowsPerPage: 10
    },
    token: "",
    headers: [
      {
        text: "No",
        align: "",
        sortable: false,
        value: "No"
      },
      {
        text: "Title",
        value: "title",
        sortable: false,
        align: "center"
      },
      {
        text: "Description",
        value: "description",
        sortable: false,
        align: "center"
      },
      {
        text: "Deadline",
        value: "deadline",
        sortable: false,
        align: "center"
      },
      {
        text: "Section",
        value: "name",
        sortable: false,
        align: "center"
      },
      {
        text: "Uploader",
        value: "name",
        sortable: false,
        align: "center"
      },
      {
        text: "File",
        value: "file",
        sortable: false,
        align: "center"
      },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],

    showPdfData: false,
    loadingPdf: false,
    hideData: true,

    assignmentData: [],
    subjectList: [],
    classList: [],
    addSection: [],
    editedIndex: -1,
    addSubject: {},

    editedItem: {
      title: "",
      description: "",
      deadline: "",
      classId: "",
      sectionId: "",
      subjectName: "",
      fileType: ""
    },
    addAssignment: {},

    imageData: {},
    imageName: "",
    imageUrl: "",
    imageFile: "",

    titleRules: [v => !!v || " Title is required"],
    descriptionRules: [v => !!v || " Description is required"],
    deadlineRules: [v => !!v || " Deadline is required"],
    classRules: [v => !!v || "Class is required"],
    sectionRules: [v => !!v || "Section is required"],
    subjectRules: [v => !!v || "Student is required"],
    fileRules: [v => !!v || "File is required"]
  }),
  methods: {
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    pickFile() {
      this.$refs.image.click();
    },
    editItem(item) {
      this.editedIndex = this.assignmentData;
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
      this.editAssignmentDialog = true;
    },
    profile(item) {
      this.editedIndex = this.assignmentData;
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
      this.viewAssignmentDialog = true;
    },
    deleteItem(item) {
      let deleteAssignment = {
        assignmentId: item._id
      };
      http()
        .delete(
          "/deleteAssignment",
          confirm("Are you sure you want to delete this?") && {
            params: deleteAssignment
          },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.getAssignmentList();
          this.snackbar = true;
          this.text = "Successfully delete Existing Assignment";
          this.color = "green";
        })
        .catch(error => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    close() {
      this.editAssignmentDialog = false;
    },
    close1() {
      this.viewAssignmentDialog = false;
    },
    submit() {
      var addAssignment = {
        title: this.addAssignment.title,
        description: this.addAssignment.description,
        deadline: this.addAssignment.deadline,
        classId: this.addAssignment.classId,
        sectionId: this.addAssignment.sectionId,
        subjectName: this.addAssignment.subjectName,
        file: this.addAssignment.imageName
      };
      var signatures = {
        JVBERi0: "other",
        iVBORw0KGgo: "image",
        UEsDBBQ: "other",
        "/": "image",
        AAABAA: "image",
        IywiV2hhdC: "other",
        bmFtZSxl: "other"
      };
      function detectMimeType(b64) {
        for (var s in signatures) {
          if (b64.indexOf(s) === 0) {
            return signatures[s];
          }
        }
      }
      if (this.$refs.form.validate()) {
        if (this.imageUrl) {
          var str = this.imageUrl;
          const [baseUrl, imageUrl] = str.split(/,/);
          addAssignment.upload = imageUrl;
          addAssignment.fileType = detectMimeType(imageUrl);
        }
        console.log("data===>", addAssignment);
        http()
          .post("/createAssignment", addAssignment)
          .then(response => {
            this.snackbar = true;
            this.text = "Syllabus added successfully";
            this.clear();
            this.color = "green";
            this.addAssignmentDialog = false;
            this.getAssignmentList();
          })
          .catch(error => {
            // console.log(error);
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "red";
          });
      }
    },
    getAssignmentList() {
      this.showLoader = true;
      http()
        .get(
          "/getAssignmentList",
          {
            params: { classId: this.addAssignment.classId }
          },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.assignmentData = 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);
          }
        });
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      if (this.$refs.formEditAssignment.validate()) {
        let editAssignment = {
          assignmentId: this.editedItem._id,
          title: this.addAssignment.title,
          description: this.addAssignment.description,
          deadline: this.addAssignment.deadline,
          classId: this.addAssignment.classId,
          sectionId: this.addAssignment.sectionId,
          subjectName: this.addAssignment.subjectName,
          file: this.addAssignment.imageName
        };
        this.editLoading = true;
        var signatures = {
          JVBERi0: "other",
          iVBORw0KGgo: "image",
          UEsDBBQ: "other",
          "/": "image",
          AAABAA: "image",
          IywiV2hhdC: "other",
          bmFtZSxl: "other"
        };
        function detectMimeType(b64) {
          for (var s in signatures) {
            if (b64.indexOf(s) === 0) {
              return signatures[s];
            }
          }
        }
        if (this.imageUrl) {
          var str = this.imageUrl;
          const [baseUrl, imageUrl] = str.split(/,/);
          editAssignment.upload = imageUrl;
          editAssignment.fileType = detectMimeType(imageUrl);
        }
        http()
          .put("/updateAssignment", editAssignment)
          .then(response => {
            this.snackbar = true;
            this.text = "Successfully Edit Existing Assignment";
            this.color = "green";
            this.editLoading = false;
            this.editAssignmentDialog = false;
            this.getAssignmentList();
          })
          .catch(error => {
            this.editLoading = false;
            // console.log(error);
          });
      }
    },
    getClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.classList = response.data.data;
        })
        .catch(error => {
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    getSections(_id) {
      var token = this.$store.state.token;
      this.showLoader = true;
      http()
        .get(
          "/getSectionsList",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + token }
          }
        )
        .then(response => {
          this.addSection = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          this.showLoader = false;
        });
    },
    getClassSubject(_id) {
      this.showLoader = true;
      //   this.classId = this.classId;
      http()
        .get(
          "/getParticularClass",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.subjectList = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          this.showLoader = false;
        });
    },
    onFilePicked(e) {
      const files = e.target.files;
      this.upload = e.target.files[0];
      if (files[0] !== undefined) {
        this.imageName = files[0].name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.imageUrl = fr.result;
          this.imageFile = files[0]; // this is an image file that can be sent to server...
          this.imageData.imageUrl = URL.createObjectURL(this.imageFile);
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },

    async generatePDF2Canvas(item) {
      var dataType = "";
      var type = "";
      if (item.fileType == "image") {
        dataType = "file.jpg";
      } else if (item.fileType == "other") {
        dataType = "file.pdf";
        type = "application/pdf";
      }
      var FileSaver = require("file-saver");
      FileSaver.saveAs(item.file, "image.jpg");
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.role = this.$store.state.role;
    this.getClass();
  }
};
</script>