<template>
  <v-container fluid class="body-color">
    <!-- ****** EDIT  Syllabus ****** -->
    <v-dialog v-model="editSyllabusDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Syllabus</label>
            <v-icon size="24" class="right" @click="editSyllabusDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-form ref="formEditSyllabus" v-model="validEditSyllabus" 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 v-model="editedItem.title"></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"></v-text-field>
              </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"
                  v-model="editedItem.classId"
                  label="Select Class"
                  item-text="classNum"
                  item-value="_id"
                  name="Select Class"
                  @change="getSections(addSyllabus.classId)"
                  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="editedItem.sectionId"
                  name="Select Section"
                  class="px-2"
                  required
                ></v-select>
              </v-flex>
            </v-layout> -->
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">File:</label>
              </v-flex>
              <v-flex xs8 sm6 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"
                >Update Syllabus</v-btn>
              </v-card-actions>
            </v-flex>
          </v-form>
        </v-container>
      </v-card>
    </v-dialog>

    <!-- ****** VIEW PROFIL NOTICE BOARD ******  -->

    <!-- <v-dialog v-model="viewSubjectDialog" max-width="600px">
      <v-toolbar flat class="card-style pa-3" dark>
        <v-spacer></v-spacer>
        <v-toolbar-title>
          <h3>Subject</h3>
        </v-toolbar-title>
        <v-spacer></v-spacer>
        <v-icon @click="close1">close</v-icon>
      </v-toolbar>
      <v-card>
        <v-card-text>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex>
                <v-layout>
                  <v-flex xs7 sm6>
                    <h5 class="right my-1">
                      <b>Subject Name:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm6 xs5>
                    <h5 class="my-1">{{ editedItem.subjectName }}</h5>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>-->

    <!-- ****** EXISTING SYLLABUS 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="addSyllabusDialog = 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="addSyllabusDialog = true">
          <v-icon class="white--text pr-1" size="20">add</v-icon>Add Syllabus
        </v-btn>
      </v-flex>
      <v-spacer></v-spacer>
      <v-flex lg2 md2 xs12 v-show="show">
        <v-select
          :items="classList"
          label="Select Class"
          v-model="addSyllabus.classId"
          item-text="classNum"
          item-value="_id"
          name="Select Class"
          :rules="classRules"
          @change="getSyallabusList"
          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="syllabusList"
      :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">{{ dates(props.item.created) }}</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">
            <!-- <a href="" @click="generatePDF2Canvas">{{ props.item.documentUrl}}</a> -->
            <!-- <a href="" target="" @click="generatePDF2Canvas">{{ props.item.fileType }}</a> -->
            <v-btn
              class="right add-button"
              :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: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 SYLLABUS ****** -->
    <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="addSyllabusDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Syllabus</label>
            <v-icon size="24" class="right" @click="addSyllabusDialog = 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
                      v-model="addSyllabus.title"
                      name="name"
                      type="text"
                      label="Add Title"
                      :rules="titleRules"
                      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
                      v-model="addSyllabus.description"
                      name="name"
                      type="text"
                      label="Add Description"
                      :rules="descriptionRules"
                      required
                    ></v-text-field>
                  </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"
                      v-model="addSyllabus.classId"
                      label="Select Class"
                      item-text="classNum"
                      item-value="_id"
                      name="Select Class"
                      @change="getSections(addSyllabus.classId)"
                      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="addSyllabus.sectionId"
                      name="Select Section"
                      class="px-2"
                      required
                    ></v-select>
                  </v-flex>
                </v-layout> -->
                <v-layout>
                  <v-flex xs4 class="pt-4 subheading">
                    <label class="right">File:</label>
                  </v-flex>
                  <v-flex xs8 sm6 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 Syllabus</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";

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    color: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    editLoading: false,
    date: null,
    search: "",
    editSyllabusDialog: false,
    valid: true,
    validEditSyllabus: true,
    addSyllabusDialog: false,
    loadingPdf: false,

    pagination: {
      rowsPerPage: 10
    },
    token: "",
    upload: "",
    titleRules: [v => !!v || " Title is required"],
    descriptionRules: [v => !!v || " Description is required"],
    classRules: [v => !!v || " Class Name is required"],
    fileRules: [v => !!v || " File is required"],
    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: "Date",
        value: "created",
        sortable: false,
        align: "center"
      },
      {
        text: "Uploader",
        value: "upload",
        sortable: false,
        align: "center"
      },
      {
        text: "File",
        value: "documentUrl",
        sortable: false,
        align: "center"
      },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    syllabusList: [],
    classList: [],
    addSection: [],
    editedIndex: -1,
    addSyllabus: {},

    editedItem: {
      subjectName: ""
    },
    imageData: {},
    imageName: "",
    imageUrl: "",
    imageFile: ""
  }),

  methods: {
    pickFile() {
      this.$refs.image.click();
    },
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    editItem(item) {
      this.editedIndex = this.syllabusList;
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
      this.editSyllabusDialog = true;
    },
    download(item) {
      this.editedIndex = this.syllabusList;
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
    },
    deleteItem(item) {
      let deleteSyallabus = {
        syallabusId: item._id
      };
      http()
        .delete(
          "/deleteSyallabus",
          confirm("Are you sure you want to delete this?") && {
            params: deleteSyallabus
          }
        )
        .then(response => {
          this.getSyallabusList();
          this.snackbar = true;
          this.color = "green";
          this.text = "Successfully delete Existing Syllabus";
        })
        .catch(error => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    close() {
      this.editSyllabusDialog = false;
    },

    submit() {
      // var addSyllabus = {
      //   classId: this.addSyllabus.classId,
      //   title: this.addSyllabus.title,
      //   description: this.addSyllabus.description,
      //   upload: this.addSyllabus.upload,
      //   fileType: this.addSyllabus.fileType
      // };
      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(/,/);
          this.addSyllabus.upload = imageUrl;
          this.addSyllabus.fileType = detectMimeType(imageUrl);
        }
        http()
          .post("/createSyallabus", this.addSyllabus)
          .then(response => {
            this.getSyallabusList();
            this.snackbar = true;
            this.text = "Syllabus added successfully";
            this.clear();
            this.color = "green";
            this.addSyllabusDialog = false;
          })
          .catch(error => {
            // console.log(error);
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "error";
          });
      }
    },
    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 = "";
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      if (this.$refs.formEditSyllabus.validate()) {
        let syllabusData = {
          syallabusId: this.editedItem._id,
          classId: this.editedItem.classId._id,
          // sectionId: this.editedItem.sectionId,
          title: this.editedItem.title,
          description: this.editedItem.description,
          upload: this.editedItem.upload,
          fileType: this.editedItem.fileType
        };
        this.editLoading = true;
        var signatures = {
          JVBERi0: "other",
          iVBORw0KGgo: "image",
          UEsDBBQ: "other",
          "/": "image",
          AAABAA: "image",
          IywiV2hhdC: "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(/,/);
          syllabusData.upload = imageUrl;
          syllabusData.fileType = detectMimeType(imageUrl);
        }
        http()
          .put("/updateSyallabus", syllabusData)
          .then(response => {
            this.snackbar = true;
            this.text = "Successfully Edit Existing Syllabus";
            this.color = "green";
            this.editLoading = false;
            this.editSyllabusDialog = false;
            http()
              .get(
                "/getSyallabusList",
                { params: { classId: this.addSyllabus.classId } },
                {
                  headers: { Authorization: "Bearer " + this.token }
                }
              )
              .then(response => {
                this.syllabusList = response.data.data;
                this.getSyallabusList();
                this.snackbar = true;
                this.color = "green";
                this.close();
              })
              .catch(err => {
                console.log("err====>", err);
                this.text = error.response.data.message;
                this.color = "error";
              });
          })
          .catch(error => {
            this.editLoading = false;
          });
      }
    },
    getSyallabusList() {
      this.showLoader = true;
      http()
        .get(
          "/getSyallabusList",
          { params: { classId: this.addSyllabus.classId } },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.syllabusList = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          this.showLoader = false;
        });
    },
    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;
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },

    // async generatePDF2Canvas() {
    //   this.loadingPdf = true;
    //   const el = this.$refs.printMe;
    //   // add option type to get the image version
    //   // if not provided the promise will return
    //   // the canvas.
    //   const options = {
    //     type: "dataURL"
    //   };
    //   this.output = await this.$html2canvas(el, options);
    //   if (this.output) {
    //     this.loadingPdf = false;
    //   }
    //   let doc = new jsPDF();
    //   doc.addImage(this.output,"JPEG", "JVBERi0","iVBORw0KGgo","UEsDBBQ","/","AAABAA","IywiV2hhdC","bmFtZSxl", 5, 10, 200, 280); 
    //   doc.save("File.pdf");
    // }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.role = this.$store.state.role;
    this.getClass();
  }
};
</script>