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

      <!-- ****** EDITS ALL NEWS DETAILS ****** -->

      <v-tab-item>
        <v-snackbar
          :timeout="timeout"
          :top="y === 'top'"
          :right="x === 'right'"
          :vertical="mode === 'vertical'"
          v-model="snackbar"
          color="success"
        >{{ text }}</v-snackbar>
        <v-dialog v-model="dialog" max-width="1000px" scrollable>
          <v-card flat>
            <v-toolbar class="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>Edit E-Books</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
            </v-toolbar>
            <v-card-text style="height:760px;">
              <v-form ref="form">
                <v-container fluid>
                  <v-layout row>
                    <v-flex
                      xs12
                      class="text-xs-center text-sm-center text-md-center text-lg-center mr-4"
                    >
                      <input
                        type="file"
                        style="display: none"
                        ref="image"
                        accept="image/*"
                        multiple
                        @change="onImagePicked"
                      />
                      <v-layout justify-center>
                        <v-flex v-if="files != ''">
                          <img :src="files" height="200" width="160;" />
                        </v-flex>
                      </v-layout>
                      <img
                        v-if="editedItem.coverPhotoUrl && files == '' "
                        :src="editedItem.coverPhotoUrl"
                        height="200"
                        width="160"
                        alt="eBooks"
                        class="pa-2"
                      />
                      <!-- <v-layout justify-center>
                        <v-flex
                          xs3
                          v-for="Image in editedItem.newsImageUrl"
                          :key="Image._id"
                          v-if="editedItem.newsImageUrl"
                          class="profile-image-wrapper"
                        >
                         
                          <v-icon
                            class="red edit-profile-icon"
                            dark
                            @click="deleteImage(Image._id,editedItem._id)"
                          >close</v-icon>
                        </v-flex>
                        <v-flex v-for="(file, index) in files" :key="index">
                          <img :src="file" height="160" width="160" class="pa-2" />
                        </v-flex>
                      </v-layout>-->
                      <img
                        src="/static/icon/user.png"
                        v-if="editedItem.coverPhotoUrl == ''"
                        height="160"
                        width="160"
                        alt="Books"
                      />
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Name:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            v-model="editedItem.name"
                            placeholder="fill your Name"
                            type="text"
                          ></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">Author:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field placeholder="fill your Author" v-model="editedItem.author"></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">Class:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            v-model="editedItem.className"
                            :items="addClass"
                            label="Select Class"
                            item-text="classNum"
                            item-value="_id"
                          ></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">Upload Image:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            label="Select Image"
                            @click="pickImage"
                            v-model="imageName"
                            append-icon="attach_file"
                            multiple
                          ></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">Upload File:</label>
                        </v-flex>
                        <v-flex xs5 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"
                            multiple
                          ></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">Private:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-checkbox v-model="editedItem.private"></v-checkbox>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm8 offset-sm2>
                      <v-card-actions>
                        <v-btn round dark @click.native="close">Cancel</v-btn>
                        <v-spacer></v-spacer>
                        <v-btn round dark @click="save" :loading="loadingUpadte">Save</v-btn>
                      </v-card-actions>
                    </v-flex>
                  </v-layout>
                </v-container>
              </v-form>
            </v-card-text>
          </v-card>
        </v-dialog>

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

        <v-dialog v-model="dialog1" max-width="800px" scrollable>
          <v-card style="height: 700px;">
            <v-toolbar color="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>E-Books</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
              <v-icon @click="close1">close</v-icon>
            </v-toolbar>
            <v-card-text>
              <v-container>
                <v-layout wrap>
                  <v-flex sm12 xs12>
                    <iframe :src="editedItem.fileUrl" height="600" width="100%"></iframe>
                  </v-flex>
                </v-layout>
              </v-container>
            </v-card-text>
          </v-card>
        </v-dialog>
        <!-- ****** EXISTING-USERS NEWS TABLE ****** -->
        <v-data-table
          :headers="headers"
          :items="eBookData"
          :pagination.sync="pagination"
          :search="search"
        >
          <template slot="items" slot-scope="props">
            <td class="text-xs-center">{{ props.index + 1}}</td>
            <td id="td" class="text-xs-center">
              <img :src="props.item.coverPhotoUrl" alt="newsImage" width="100" height="70" />
            </td>
            <td id="td" class="text-xs-center">{{ props.item.name}}</td>
            <td id="td" class="text-xs-center">{{ props.item.author}}</td>
            <td id="td" class="text-xs-center">{{ props.item.classId.classNum}}</td>

            <td class="text-xs-center">
              <span>
                <v-tooltip top>
                  <img
                    slot="activator"
                    style="cursor:pointer; width:25px; height:18px; "
                    class="mr5"
                    @click="profile(props.item)"
                    src="/static/icon/eye1.png"
                  />
                  <span>View</span>
                </v-tooltip>
                <v-tooltip top>
                  <img
                    slot="activator"
                    style="cursor:pointer; width:20px; height:18px; "
                    class="mr5"
                    @click="editItem(props.item)"
                    src="/static/icon/edit1.png"
                  />
                  <span>Edit</span>
                </v-tooltip>
                <v-tooltip top>
                  <img
                    slot="activator"
                    style="cursor:pointer; width:20px; height:20px; "
                    class="mr5"
                    @click="deleteItem(props.item)"
                    src="/static/icon/delete1.png"
                  />
                  <span>Delete</span>
                </v-tooltip>
              </span>
            </td>
          </template>
          <v-alert
            slot="no-results"
            :value="true"
            color="error"
            icon="warning"
          >Your search for "{{ search }}" found no results.</v-alert>
        </v-data-table>
      </v-tab-item>

      <!-- ****** ADD MULTIPLE E-BOOK ****** -->

      <v-tab-item>
        <v-container>
          <v-snackbar
            :timeout="timeout"
            :top="y === 'top'"
            :right="x === 'right'"
            :vertical="mode === 'vertical'"
            v-model="snackbar"
            color="success"
          >{{ text }}</v-snackbar>
          <v-flex xs12 sm12 class="my-4">
            <v-card flat>
              <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 my-4 mr-4"
                    >
                      <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="240" width="260px;" />
                        </v-flex>
                      </v-layout>
                      <img
                        src="/static/icon/user.png"
                        v-if="files ==''"
                        height="140"
                        width="180px;"
                      />
                    </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 xs4 class="ml-3">
                        <v-text-field
                          v-model="addEBooks.name"
                          placeholder="fill your Title"
                          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 xs4 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 xs4 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 xs4 class="ml-3">
                        <v-text-field
                          label="Select Image"
                          @click="pickImage"
                          v-model="imageName"
                          append-icon="attach_file"
                          multiple
                        ></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 xs4 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"
                          multiple
                        ></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 xs4 class="ml-3">
                        <v-checkbox v-model="addEBooks.private"></v-checkbox>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-layout>
                    <v-flex xs12 sm7 offset-sm2>
                      <v-card-actions>
                        <v-btn @click="clear" round dark>clear</v-btn>
                        <v-spacer></v-spacer>
                        <v-btn @click="submit" round dark :loading="loading">Add</v-btn>
                      </v-card-actions>
                    </v-flex>
                  </v-layout>
                </v-container>
              </v-form>
            </v-card>
          </v-flex>
        </v-container>
      </v-tab-item>
    </v-tabs>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
  </v-app>
</template>

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

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    loading: false,
    loadingUpadte: false,
    date: null,
    search: "",
    showLoader: false,
    dialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    addClass: [],
    addSection: [],
    AddUsercredentials: {},
    pagination: {
      rowsPerPage: 15
    },
    imageName: "",
    fileName: "",
    imageUrl: "",
    imageFile: "",
    image: [],
    upload: "",
    files: "",
    anyFile: "",
    titleRules: [v => !!v || " Tilte is required"],
    descriptionRules: [v => !!v || " Description is required"],
    headers: [
      {
        align: "justify-center",
        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: {},
    token: ""
  }),
  methods: {
    pickImage() {
      this.$refs.image.click();
    },
    pickFile() {
      this.$refs.file.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 = "";
      }
    },
    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 = "";
      }
    },
    editItem(item) {
      this.files = [];
      this.editedIndex = this.eBookData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editedItem.className = item.classId.classNum;
      this.dialog = true;
    },
    profile(item) {
      this.editedIndex = this.eBookData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog1 = 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;
        });
    },
    activeTab(type) {
      switch (type) {
        case "existing":
          this.newActive = false;
          this.isActive = true;
          break;

        default:
          this.newActive = true;
          this.isActive = false;
          break;
      }
    },
    close() {
      this.dialog = false;
      setTimeout(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      }, 300);
    },
    close1() {
      this.dialog1 = false;
    },
    submit() {
      if (this.$refs.form.validate()) {
        if (this.files) {
          const [baseUrl, imageUrl] = this.files.split(/,/);
          this.addEBooks.uploadCover = imageUrl;
          // console.log("anyFile.split(/,/)", this.addEBooks.uploadCover);
        }
        if (this.anyFile) {
          const [baseUrl, fileUrl] = this.anyFile.split(/,/);
          this.addEBooks.uploadFile = fileUrl;
          // console.log("anyFile.split(/,/)", this.addEBooks.uploadFile);
        }
        this.addEBooks = this.$store.state.schoolId;
        this.loading = true;
        http()
          .post("/createEBook", this.addEBooks)
          .then(response => {
            this.snackbar = true;
            this.text = "New E-Book added successfully";
            this.addEBooks.uploadCover = "";
            this.addEBooks.uploadFile = "";
            this.files = "";
            this.getEBooksList();
            this.loading = false;
            this.clear();
          })
          .catch(error => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.addEBooks.uploadCover = "";
      this.files = "";
    },
    save() {
      this.loadingUpadte = true;
      if (this.files.length > 0) {
        const [baseUrl, imageUrl] = this.files.split(/,/);
        this.editedItem.uploadCover = imageUrl;
        // console.log("anyFile.split(/,/)", this.addEBooks.uploadCover);
      }
      if (this.anyFile) {
        const [baseUrl, fileUrl] = this.anyFile.split(/,/);
        this.editedItem.uploadFile = fileUrl;
        // console.log("anyFile.split(/,/)", this.addEBooks.uploadFile);
      }
      this.editedItem.ebookId = this.editedItem._id;
      http()
        .put("/updateEBook", this.editedItem)
        .then(response => {
          this.loadingUpadte = false;
          this.snackbar = true;
          this.text = "Successfully Edit Existing E-Book";
          this.getEBooksList();
          this.editedItem.uploadFile = "";
          this.editedItem.uploadCover = "";
          this.anyFile = "";
          this.files = "";
          this.close();
        })
        .catch(error => {
          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: "/" });
        });
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getEBooksList();
    this.getAllClass();
    // this.getBookData();
    // this.editItem;
  },
  created() {
    this.$root.$on("app:search", search => {
      this.search = search;
    });
  },
  beforeDestroy() {
    // dont forget to remove the listener
    this.$root.$off("app:search");
  }
};
</script>
<style scoped>
.active {
  background-color: gray;
  color: white !important;
}
.activebtn {
  color: black !important;
}
</style>