<template>
  <v-container fluid class="body-color">
    <!-- ****** EDITS EBOOK DETAILS ****** -->
    <v-dialog v-model="editEbookDialog" max-width="600px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit E-Book</label>
            <v-icon size="24" class="right" @click="editEbookDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
            <input
              type="file"
              style="display: none"
              ref="editImage"
              accept="image/*"
              @change="onEditImagePicked"
            />
            <img
              v-if="editedItem.coverPhotoUrl"
              :src="editedItem.coverPhotoUrl"
              height="160"
              width="160"
              alt="eBooks"
              class="pa-2"
            />
            <img
              src="/static/icon/user.png"
              v-if="editedItem.coverPhotoUrl == ''"
              height="160"
              width="160"
              alt="Books"
            />
          </v-flex>
          <v-container grid-list-md>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right hidden-xs-only hidden-sm-only">Name :</label>
                  <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Name :</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <v-text-field
                    v-model="editedItem.name"
                    placeholder="fill your full Name"
                    name="name"
                    type="text"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right hidden-xs-only hidden-sm-only">Author :</label>
                  <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Author :</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <v-text-field
                    v-model="editedItem.author"
                    placeholder="fill your full author"
                    name="name"
                    type="text"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right hidden-xs-only hidden-sm-only">Class :</label>
                  <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Class :</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <v-select
                    v-model="editedItem.classId"
                    :items="addClass"
                    label="Select Class"
                    item-text="classNum"
                    item-value="_id"
                    type="_id"
                    required
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right hidden-xs-only hidden-sm-only">Upload Image :</label>
                  <label class="right hidden-lg-only hidden-md-only hidden-xl-only">UploadImage :</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <v-text-field
                    label="Select Image"
                    @click="editPickImage"
                    v-model="editImageName"
                    append-icon="attach_file"
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Upload File:</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <input
                    type="file"
                    style="display: none"
                    ref="editFile"
                    @change="onEditFilePicked"
                  />
                  <v-text-field
                    label="Select File"
                    @click="editPickFile"
                    v-model="editFileName"
                    append-icon="attach_file"
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn round dark @click="save" :loading="editLoading" class="add-button">Save</v-btn>
              <v-spacer></v-spacer>
            </v-card-actions>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- ****** PROFILE VIEW ALL NEWS DEATILS ******  -->

    <v-dialog v-model="viewEbookDialog" max-width="600px" scrollable>
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View E-book</label>
            <v-icon size="24" class="right" @click="viewEbookDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-layout>
          <v-flex align-center justify-center layout text-xs-center class="mt-3">
            <v-avatar size="100px">
              <img src="/static/icon/user.png" v-if="!editedItem.coverPhotoUrl" />
              <img :src="editedItem.coverPhotoUrl" v-else-if="editedItem.coverPhotoUrl" />
            </v-avatar>
          </v-flex>
        </v-layout>
        <v-container grid-list-md>
          <v-layout wrap>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs6 sm6>
                  <h5 class="right my-1">
                    <b>Name:</b>
                  </h5>
                </v-flex>
                <v-flex sm6 xs6>
                  <h5 class="my-1 left">{{ editedItem.name }}</h5>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs6 sm6>
                  <h5 class="right my-1">
                    <b>Author:</b>
                  </h5>
                </v-flex>
                <v-flex sm6 xs6>
                  <h5 class="my-1 left">{{ editedItem.author }}</h5>
                </v-flex>
              </v-layout>
            </v-flex>
          </v-layout>
          <v-flex xs12 sm12>
            <v-layout>
              <v-flex xs6 sm6>
                <h5 class="right my-1">
                  <b>Class:</b>
                </h5>
              </v-flex>
              <v-flex sm6 xs6>
                <h5 class="my-1 left">{{ editedItem.classId .classNum}}</h5>
              </v-flex>
            </v-layout>
          </v-flex>
        </v-container>
      </v-card>
    </v-dialog>
    <!-- ****** EXISTING-USERS NEWS 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="addEBookDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addEBookDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add E-Book
      </v-btn>
      <v-spacer></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/search.png" alt="icon" />
          </v-avatar>
        </v-btn>
      </v-card-title>
      <v-flex xs8 sm8 md3 lg2 v-if="showSearch">
        <v-layout>
          <v-text-field
            autofocus
            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-data-table
      :headers="headers"
      :items="eBookData"
      :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.coverPhotoUrl" v-if="props.item.coverPhotoUrl" alt="ebooks" />
              <img src="/static/icon/user.png" v-if="!props.item.coverPhotoUrl" />
            </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.author}}</td>
          <td class="td td-row text-xs-center">{{ props.item.classId.classNum}}</td>
          <td class="td td-row text-xs-center">
            <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 v-if="role != 'TEACHER' ">
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:20px; "
                  @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 E-BOOK ****** -->
    <v-dialog v-model="addEBookDialog" max-width="600px" v-if="addEBookDialog">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add E-Book</label>
            <v-icon size="24" class="right" @click="closeAddEBookModel">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-form ref="form" v-model="valid" lazy-validation>
          <v-container fluid>
            <v-layout>
              <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
                <input
                  type="file"
                  style="display: none"
                  ref="image"
                  accept="image/*"
                  @change="onImagePicked"
                />
                <v-layout justify-center>
                  <v-flex v-if="files != ''">
                    <img :src="files" height="150" width="150" />
                  </v-flex>
                </v-layout>
                <img src="/static/icon/user.png" v-if="files ==''" height="80" width="80px;" />
              </v-flex>
            </v-layout>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Name:</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-text-field
                    v-model="addEBooks.name"
                    placeholder="fill name"
                    name="name"
                    type="text"
                    :rules="titleRules"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Author:</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-text-field
                    v-model="addEBooks.author"
                    placeholder="fill your Author Name"
                    name="name"
                    type="text"
                    :rules="titleRules"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Class:</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-select
                    v-model="addEBooks.classId"
                    :items="addClass"
                    label="Select Class"
                    item-text="classNum"
                    item-value="_id"
                    :rules="titleRules"
                    required
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Upload Image:</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-text-field
                    label="Select Image"
                    @click="pickImage"
                    v-model="imageName"
                    append-icon="attach_file"
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Upload File:</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <input type="file" style="display: none" ref="file" @change="onFilePicked" />
                  <v-text-field
                    label="Select File"
                    @click="pickFile"
                    v-model="fileName"
                    append-icon="attach_file"
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-3 subheading">
                  <label class="right">Private:</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-checkbox v-model="addEBooks.private" :rules="uploadPrivateRule"></v-checkbox>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-layout>
              <v-flex xs12>
                <v-card-actions>
                  <v-spacer></v-spacer>
                  <v-btn @click="clear" round dark class="clear-button">clear</v-btn>
                  <v-btn @click="submit" round dark :loading="loading" class="add-button">Add</v-btn>
                </v-card-actions>
              </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-container>
</template>

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

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    show: true,
    showSearch: false,
    loading: false,
    loadingUpadte: false,
    date: null,
    search: "",
    showLoader: false,
    editEbookDialog: false,
    viewEbookDialog: false,
    valid: true,
    addEBookDialog: false,
    editLoading: false,
    addClass: [],
    addSection: [],
    pagination: {
      rowsPerPage: 10,
    },
    imageName: "",
    fileName: "",
    imageUrl: "",
    imageFile: "",
    image: [],
    upload: "",
    files: "",
    anyFile: "",
    titleRules: [(v) => !!v || " Tilte is required"],
    descriptionRules: [(v) => !!v || " Description is required"],
    uploadImageRule: [(v) => !!v || " field is required"],
    uploadFileRule: [(v) => !!v || " fied is required"],
    uploadPrivateRule: [(v) => !!v || " fied is required"],

    headers: [
      {
        align: "left",
        text: "No",
        sortable: false,
        value: "No",
      },
      { text: "Photo", vaue: "fileUrl", sortable: false, align: "center" },
      { text: "Name", vaue: "name", sortable: false, align: "center" },
      { text: "Author", value: "author", sortable: false, align: "center" },
      {
        text: "Class",
        value: "classId",
        sortable: false,
        align: "center",
      },
      { text: "Action", value: "", sortable: false, align: "center" },
    ],
    eBookData: [],
    editedIndex: -1,
    addEBooks: {
      private: false,
    },
    editedItem: {},
    editedItem: {
      classId: {
        classNum: "",
      },
    },
    token: "",
    uploadCover: {},
    editImageName: "",
    editFiles: "",
    editAnyFile: "",
    editFileName: "",
  }),
  watch: {
    addEBookDialog: function (val) {
      if (!val) {
        this.addEBooks = [];
        this.imageName = "";
        this.fileName = "";
        this.files = "";
      }
    },
  },
  methods: {
    editPickImage() {
      this.$refs.editImage.click();
    },
    pickImage() {
      this.$refs.image.click();
    },
    pickFile() {
      this.$refs.file.click();
    },
    editPickFile() {
      this.$refs.editFile.click();
    },
    onImagePicked(e) {
      // console.log(e)
      const files = e.target.files;
      /** fetch Image Name **/
      if (files[0] !== undefined) {
        this.imageName = files[0].name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        /** Select many image and showing many image add to news card **/
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.files = fr.result;
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.files = "";
        this.imageUrl = "";
      }
    },
    onEditImagePicked(e) {
      // console.log(e)
      const files = e.target.files;
      /** fetch Image Name **/
      if (files[0] !== undefined) {
        this.editImageName = files[0].name;
        if (this.editImageName.lastIndexOf(".") <= 0) {
          return;
        }
        /** Select many image and showing many image add to news card **/
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.editFiles = fr.result;
        });
      } else {
        this.editImageName = "";
        this.editFiles = "";
      }
    },
    getEBooksList() {
      this.showLoader = true;
      http()
        .get("/getEBooksList", {
          params: { schoolId: this.$store.state.schoolId },
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.eBookData = response.data.data;
          this.showLoader = false;
        })
        .catch((error) => {
          // console.log("err====>", err);
          this.showLoader = false;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    onFilePicked(e) {
      // console.log(e)
      const files = e.target.files;
      /** fetch Image Name **/
      if (files[0] !== undefined) {
        this.fileName = files[0].name;
        if (this.fileName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.anyFile = fr.result;
          // console.log(" this.anyFile Url", this.anyFile )
        });
      } else {
        this.anyFile = "";
        this.fileName = "";
      }
    },
    onEditFilePicked(e) {
      // console.log(e)
      const files = e.target.files;
      /** fetch Image Name **/
      if (files[0] !== undefined) {
        this.editFileName = files[0].name;
        if (this.editFileName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.editAnyFile = fr.result;
          // console.log(" this.anyFile Url", this.anyFile )
        });
      } else {
        this.editAnyFile = "";
        this.editFileName = "";
      }
    },
    editItem(item) {
      this.files = [];
      this.editedIndex = this.eBookData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editedItem.className = item.classId.classNum;
      this.editEbookDialog = true;
    },
    profile(item) {
      this.editedIndex = this.eBookData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.viewEbookDialog = true;
    },
    deleteItem(item) {
      let deleteEBooks = {
        ebookId: item._id,
      };
      http()
        .delete(
          "/deleteEBook",
          confirm("Are you sure you want to delete this?") && {
            params: deleteEBooks,
          }
        )
        .then((response) => {
          this.snackbar = true;
          this.text = "Successfully delete Existing News";
          this.getEBooksList();
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
        });
    },
    close() {
      this.editEbookDialog = false;
    },
    close1() {
      this.viewEbookDialog = false;
    },
    closeAddEBookModel() {
      this.addEBookDialog = false;
      //   this.eBookData = [];
      this.addEBooks = [];
      this.imageName = "";
      this.fileName = "";
      this.files = "";
    },
    submit() {
      if (this.$refs.form.validate()) {
        this.loading = true;
        var uploadCover = "";
        var uploadFile = "";
        if (this.files) {
          const [baseUrl, imageUrl] = this.files.split(/,/);
          uploadCover = imageUrl;
          console.log("anyFile.split(/,/)", uploadCover);
        }
        if (this.anyFile) {
          const [baseUrl, fileUrl] = this.anyFile.split(/,/);
          uploadFile = fileUrl;
          console.log("anyFile.split(/,/)", uploadFile);
        }
        let data = {
          classId: this.addEBooks.classId,
          name: this.addEBooks.name,
          author: this.addEBooks.author,
          private: this.addEBooks.private,
          uploadCover: uploadCover,
          uploadFile: uploadFile,
        };
        http()
          .post("/createEBook", data)
          .then((response) => {
            this.getEBooksList();
            // this.getEBooksList = [];
            this.addEBookDialog = false;
            this.snackbar = true;
            this.text = response.data.message;
            this.color = "green";
            this.loading = false;
            (this.imageName = ""), (this.fileName = "");
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "red";
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.addEBooks.uploadCover = "";
      this.files = "";
    },
    save() {
      this.editLoading = true;
      this.loadingUpadte = true;
      if (this.editFiles) {
        const [baseUrl, imageUrl] = this.editFiles.split(/,/);
        this.editedItem.uploadCover = imageUrl;
        // console.log("anyFile.split(/,/)", this.addEBooks.uploadCover);
      }
      if (this.editAnyFile) {
        const [baseUrl, fileUrl] = this.editAnyFile.split(/,/);
        this.editedItem.uploadFile = fileUrl;
        // console.log("anyFile.split(/,/)", this.addEBooks.uploadFile);
      }
      if (this.editedItem.classId._id) {
        this.editedItem.classId = this.editedItem.classId._id;
      }
      this.editedItem.ebookId = this.editedItem._id;
      console.log("this.editedItem", this.editedItem);
      http()
        .put("/updateEBook", this.editedItem)
        .then((response) => {
          this.loadingUpadte = false;
          this.snackbar = true;
          this.text = "Successfully Edit Existing E-Book";
          this.getEBooksList();
          this.editLoading = false;
          this.editedItem.uploadFile = "";
          this.editedItem.uploadCover = "";
          this.anyFile = "";
          this.files = "";
          this.close();
        })
        .catch((error) => {
          this.editLoading = false;
          this.loadingUpadte = false;
          this.snackbar = true;
          this.text = error.response.data.message;
          // console.log(error);
        });
    },
    getAllClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.addClass = response.data.data;
        })
        .catch((err) => {
          // console.log("err====>", err);
          // this.$router.replace({ path: "/" });
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getEBooksList();
    this.getAllClass();
    this.role = this.$store.state.role;
    // this.getBookData();
    // this.editItem;
  },
};
</script>