<template>
  <v-container fluid grid-list-md>
    <v-card flat>
      <v-toolbar class="card-styles" dark flat>
        <v-spacer></v-spacer>
        <v-toolbar-title>Import</v-toolbar-title>
        <v-spacer></v-spacer>
      </v-toolbar>
      <v-container fluid>
        <v-layout>
          <v-flex xs12>
            <v-layout wrap>
              <v-flex xs6 sm5 lg2 class="pt-4">
                <label class="title right">Add Teacher:</label>
              </v-flex>
              <v-flex xs12 sm6 lg3>
                <v-text-field v-model="teacherFileName" placeholder="Choose file" :disabled="true"></v-text-field>
                <input
                  type="file"
                  style="display: none"
                  ref="file"
                  @change="convertFile"
                  id="fileInput"
                />
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="open-dialog-button" round dark block @click="pickFile">
                  <v-icon small class="pr-1">refresh</v-icon>Upload
                </v-btn>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn
                  class="add-button"
                  round
                  dark
                  block
                  @click="importTeacher()"
                  :loading="loading"
                >import</v-btn>
              </v-flex>
              <v-flex xs12 sm4 lg2 class="mt-1">
                <download-csv :data="teacherData">
                  <v-btn class="blue lighten-2" dark block round>
                    <v-icon small class="pr-1">archive</v-icon>sample download
                  </v-btn>
                </download-csv>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-layout>
        <v-layout>
          <v-flex xs12>
            <v-layout wrap>
              <v-flex xs6 sm5 lg2 class="pt-4">
                <label class="title right">Add Parent:</label>
              </v-flex>
              <v-flex xs12 sm6 lg3>
                <v-text-field v-model="parentFileName" placeholder="Choose file" :disabled="true"></v-text-field>
                <input
                  type="file"
                  style="display: none"
                  ref="parentfile"
                  @change="parentFile"
                  id="parentInput"
                />
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="open-dialog-button" round dark block @click="pickParentFile">
                  <v-icon small class="pr-1">refresh</v-icon>Upload
                </v-btn>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1" @click="importParent" :loading="parentLoading">
                <v-btn class="add-button" round dark block>import</v-btn>
              </v-flex>
              <v-flex xs12 sm4 lg2 class="mt-1">
                <download-csv :data="parentData">
                  <v-btn class="blue lighten-2" dark block round>
                    <v-icon small class="pr-1">archive</v-icon>sample download
                  </v-btn>
                </download-csv>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-layout>
        <v-layout>
          <v-flex xs12>
            <v-layout wrap>
              <v-flex xs6 sm5 lg2 class="pt-4">
                <label class="title right">Add User:</label>
              </v-flex>
              <v-flex xs12 sm6 lg3>
                <v-text-field placeholder="Choose file" v-model="userFileName" :disabled="true"></v-text-field>
                <input
                  type="file"
                  style="display: none"
                  ref="userfile"
                  @change="userFile"
                  id="userInput"
                />
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="open-dialog-button" round dark block @click="pickUserFile">
                  <v-icon small class="pr-1">refresh</v-icon>Upload
                </v-btn>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn
                  class="add-button"
                  round
                  dark
                  block
                  @click="importUser"
                  :loading="userLoading"
                >import</v-btn>
              </v-flex>
              <v-flex xs12 sm4 lg2 class="mt-1">
                <download-csv :data="userData">
                  <v-btn class="blue lighten-2" dark block round>
                    <v-icon small class="pr-1">archive</v-icon>sample download
                  </v-btn>
                </download-csv>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-layout>
        <v-layout>
          <v-flex xs12>
            <v-layout wrap>
              <v-flex xs6 sm5 lg2 class="pt-4">
                <label class="title right">Add Book:</label>
              </v-flex>
              <v-flex xs12 sm6 lg3>
                <v-text-field placeholder="Choose file" v-model="bookFileName" :disabled="true"></v-text-field>
                <input
                  type="file"
                  style="display: none"
                  ref="bookfile"
                  @change="bookFile"
                  id="bookInput"
                />
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="open-dialog-button" round dark block @click="pickBookFile">
                  <v-icon small class="pr-1">refresh</v-icon>Upload
                </v-btn>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn
                  class="add-button"
                  round
                  dark
                  block
                  @click="importBook"
                  :loading="BookLoading"
                >import</v-btn>
              </v-flex>
              <v-flex xs12 sm4 lg2 class="mt-1">
                <download-csv :data="bookData">
                  <v-btn class="blue lighten-2" dark block round>
                    <v-icon small class="pr-1">archive</v-icon>sample download
                  </v-btn>
                </download-csv>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-layout>
        <v-layout>
          <v-flex xs12>
            <v-layout wrap>
              <v-flex xs6 sm5 lg2 class="pt-4">
                <label class="title right">Add Student:</label>
              </v-flex>
              <v-flex xs12 sm6 lg3>
                <v-text-field placeholder="Choose file" v-model="bookStudentName" :disabled="true"></v-text-field>
                <input
                  type="file"
                  style="display: none"
                  ref="studentfile"
                  @change="studentFile"
                  id="studentInput"
                />
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="open-dialog-button" round dark block @click="pickStudentFile">
                  <v-icon small class="pr-1">refresh</v-icon>Upload
                </v-btn>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn
                  class="add-button"
                  round
                  dark
                  block
                  @click="importStudent()"
                  :loading="studentLoading"
                >import</v-btn>
              </v-flex>
              <v-flex xs12 sm4 lg2 class="mt-1">
                <download-csv :data="studentData">
                  <v-btn class="blue lighten-2" round dark block>
                    <v-icon small class="pr-1">archive</v-icon>sample download
                  </v-btn>
                </download-csv>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-layout>
        <!-- <v-layout>
          <v-flex xs12>
            <v-layout wrap>
              <v-flex xs9 sm5 lg2 class="pt-4">
                <label class="title right">Students & Parents:</label>
              </v-flex>
              <v-flex xs12 sm6 lg3>
                <v-text-field placeholder="Choose file" :disabled="true"></v-text-field>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="grey" dark block>
                  <v-icon small class="pr-1">refresh</v-icon>Upload
                </v-btn>
              </v-flex>
              <v-flex xs6 sm4 lg2 class="mt-1">
                <v-btn class="grey" dark block>import</v-btn>
              </v-flex>
              <v-flex xs12 sm4 lg2 class="mt-1">
                <v-btn class="blue lighten-2" dark block>
                  <v-icon small class="pr-1">archive</v-icon>sample download
                </v-btn>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-layout>-->
      </v-container>
    </v-card>
    <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";
import teacherData from "@/script/teachers.js";
import studentData from "@/script/students.js";
import parentData from "@/script/parents.js";
import userData from "@/script/users.js";
import bookData from "@/script/books.js";
import XLSX from "xlsx";

export default {
  data: () => ({
    loading: false,
    parentLoading: false,
    userLoading: false,
    BookLoading: false,
    studentLoading: false,
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    color: "",
    teacherData: [],
    studentData: [],
    parentData: [],
    userData: [],
    bookData: [],
    teacherFileJson: [],
    parentFileJson: [],
    userFileJson: [],
    bookFileJson: [],
    studentFileJson: [],
    teacherFileName: "",
    parentFileName: "",
    userFileName: "",
    bookFileName: "",
    bookStudentName: "",
    token: "",
    fileData: {},
    teacherDetail: {},
    userDetail: {},
  }),
  methods: {
    pickFile() {
      this.$refs.file.click();
    },
    pickParentFile() {
      this.$refs.parentfile.click();
    },
    pickUserFile() {
      this.$refs.userfile.click();
    },
    pickBookFile() {
      this.$refs.bookfile.click();
    },
    pickStudentFile() {
      this.$refs.studentfile.click();
    },
    convertFile(e) {
      var form_data = new FormData();
      form_data.append("upload", e.target.files[0]);

      this.teacherDetail = form_data;

      const input = document.getElementById("fileInput");
      this.teacherFileName = input.files[0].name;

      // const reader = new FileReader();
      // console.log("reader", reader);
      // reader.onload = () => {
      //   let text = reader.result;
      //   //convert text to json here
      //   console.log("text", text);
      //   var json = this.csvJSON(text);
      // };
      // reader.readAsText(input.files[0]);
      // var files = e.target.files,
      //   f = files[0];
      // var reader = new FileReader();
      // let array = [];
      // let _this = this;
      // reader.onload = function(e) {
      //   var data = new Uint8Array(e.target.result);
      //   var workbook = XLSX.read(data, { type: "array" });
      //   let sheetName = workbook.SheetNames[0];
      //   // /* DO SOMETHING WITH workbook HERE */
      //   let worksheet = workbook.Sheets[sheetName];
      //   array = XLSX.utils.sheet_to_json(worksheet);
      //   _this.teacherFileJson = array;
      // };
      // reader.readAsArrayBuffer(f);
    },
    parentFile(e) {
      const input = document.getElementById("parentInput");
      this.parentFileName = input.files[0].name;
      //   console.log("this.parentFileName", this.parentFileName);
      var files = e.target.files,
        f = files[0];
      var reader = new FileReader();
      let array = [];
      let _this = this;
      reader.onload = function (e) {
        var data = new Uint8Array(e.target.result);
        var workbook = XLSX.read(data, { type: "array" });
        let sheetName = workbook.SheetNames[0];
        // /* DO SOMETHING WITH workbook HERE */
        let worksheet = workbook.Sheets[sheetName];
        array = XLSX.utils.sheet_to_json(worksheet);
        _this.parentFileJson = array;
      };
      reader.readAsArrayBuffer(f);
    },
    userFile(e) {
      var form_data = new FormData();
      form_data.append("upload", e.target.files[0]);

      this.userDetail = form_data;

      const input = document.getElementById("userInput");
      this.userFileName = input.files[0].name;

      // var files = e.target.files,
      //   f = files[0];
      // var reader = new FileReader();
      // let array = [];
      // let _this = this;
      // reader.onload = function(e) {
      //   var data = new Uint8Array(e.target.result);
      //   var workbook = XLSX.read(data, { type: "array" });
      //   let sheetName = workbook.SheetNames[0];
      //   // /* DO SOMETHING WITH workbook HERE */
      //   let worksheet = workbook.Sheets[sheetName];
      //   array = XLSX.utils.sheet_to_json(worksheet);
      //   _this.userFileJson = array;
      // };
      // reader.readAsArrayBuffer(f);
    },
    bookFile(e) {
      const input = document.getElementById("bookInput");
      this.bookFileName = input.files[0].name;
      //   console.log("this.bookFileName", this.bookFileName);
      var files = e.target.files,
        f = files[0];
      //   console.log("this.bookFileName", files);
      var reader = new FileReader();
      let array = [];
      let _this = this;
      reader.onload = function (e) {
        var data = new Uint8Array(e.target.result);
        // console.log("data", data);
        var workbook = XLSX.read(data, { type: "array" });
        let sheetName = workbook.SheetNames[0];
        // /* DO SOMETHING WITH workbook HERE */
        let worksheet = workbook.Sheets[sheetName];
        array = XLSX.utils.sheet_to_json(worksheet);
        _this.bookFileJson = array;
        // console.log("this.bookFileJson ", _this.bookFileJson);
      };
      reader.readAsArrayBuffer(f);
    },
    // csvJSON(csv) {
    //   var lines = csv.split("\n");

    //   var result = [];

    //   var headers = lines[0].split(",");

    //   for (var i = 1; i < lines.length; i++) {
    //     var obj = {};
    //     var currentline = lines[i].split(",");

    //     for (var j = 0; j < headers.length; j++) {
    //       obj[headers[j]] = currentline[j];
    //     }

    //     result.push(obj);
    //   }

    //   //return result; //JavaScript object
    //   return JSON.stringify(result); //JSON
    // },
    studentFile(e) {
      var form_data = new FormData();
      form_data.append("upload", e.target.files[0]);

      this.fileData = form_data;

      const input = document.getElementById("studentInput");
      this.bookStudentName = input.files[0].name;

      // var files = e.target.files,
      //   f = files[0];
      // var reader = new FileReader();
      // let array = [];
      // let _this = this;
      // reader.onload = function(e) {
      //   var data = new Uint8Array(e.target.result);
      //   var workbook = XLSX.read(data, { type: "array", cellDates: true });
      //   let sheetName = workbook.SheetNames[0];
      //   // /* DO SOMETHING WITH workbook HERE */
      //   let worksheet = workbook.Sheets[sheetName];
      //   array = XLSX.utils.sheet_to_json(worksheet);
      //   _this.studentFileJson = array;
      // };
      // reader.readAsArrayBuffer(f);
    },

    // csvJSON(csv) {
    //   var lines = csv.split("\n");

    //   var result = [];
    //   var headers = lines[0].split(",");

    //   for (var i = 1; i < lines.length; i++) {
    //     var obj = {};
    //     var currentline = lines[i].split(",");

    //     for (var j = 0; j < headers.length; j++) {
    //       obj[headers[j]] = currentline[j];
    //     }
    //     this.teacherFileJson.push(obj);
    //   }
    // },
    importTeacher() {
      this.loading = true;
      var teacherfile = {};
      teacherfile.teacherData = this.teacherFileJson;
      http()
        .post("/importTeacherData", this.teacherDetail, {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.snackbar = true;
          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";
          this.loading = false;
        });
    },
    importParent() {
      this.parentLoading = true;
      var parentfile = {};
      parentfile.parentData = this.parentFileJson;
      http()
        .post("/importParentData", parentfile, {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.parentLoading = false;
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.parentLoading = false;
          this.color = "red";
        });
    },
    importUser() {
      this.userLoading = true;
      var userfile = {};
      userfile.userData = this.userFileJson;
      http()
        .post("/importUserData", this.userDetail, {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.userLoading = false;
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.userLoading = false;
          this.color = "red";
        });
    },
    importBook() {
      this.BookLoading = true;
      var bookfile = {};
      bookfile.bookData = this.bookFileJson;
      http()
        .post("/importBookData", bookfile, {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.BookLoading = false;
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "red";
          this.BookLoading = false;
        });
    },
    importStudent() {
      this.studentLoading = true;
      var studentfile = {};
      //   console.log("this.studentFileJson", this.studentFileJson);
      studentfile.studentData = this.studentFileJson;
      http()
        .post("/importStudentData", this.fileData, {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.studentLoading = false;
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "red";
          this.studentLoading = false;
        });
    },
  },
  mounted() {
    this.token = this.$store.state.token;

    /** TEACHERS SAMPLE CSV */
    const getTeacherData = teacherData();
    this.teacherData = getTeacherData;

    /** STUDENTS SAMPLE CSV */
    const getstudentData = studentData();
    this.studentData = getstudentData;

    /** PARENTS SAMPLE CSV */
    const getparentData = parentData();
    this.parentData = getparentData;

    /** USERS SAMPLE CSV */
    const getUserData = userData();
    this.userData = getUserData;

    /** BOOKS SAMPLE CSV */
    const getBookData = bookData();
    this.bookData = getBookData;
  },
};
</script>
<style>
.card-styles {
  background: #7f62f8 !important;
  border-color: #7f62f8 !important;
}
</style>
