<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 Issue</v-tab>
      <v-tab
        ripple
        @click="activeTab('new')"
        v-bind:class="{ active: newActive }"
        id="tab1"
        User
        class="subheading"
      >Add Issue a book</v-tab>

      <!-- ****** EDIT ISSUE  A BOOK ****** -->

      <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 Issue</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
            </v-toolbar>
            <v-card-text style="height:600px;">
              <v-form ref="form">
                <v-container fluid>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Library Id:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            v-model="editedItem.libraryId"
                            placeholder="fill your Library Id"
                            name="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">Book:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            v-model="editedItem.name"
                            placeholder="fill your Book name"
                            name="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 Name"
                            v-model="editedItem.author"
                            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">Subject Code:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            placeholder="fill your Subject Codes"
                            v-model="editedItem.subjectCode"
                            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">Serial Number:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            placeholder="fill your Serial Number"
                            v-model="editedItem.serialNumber"
                            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">due Date:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-menu
                            ref="menu1"
                            :close-on-content-click="false"
                            v-model="menu1"
                            :nudge-right="40"
                            :return-value.sync="menu1"
                            lazy
                            transition="scale-transition"
                            offset-y
                            full-width
                            min-width="290px"
                          >
                            <v-text-field
                              slot="activator"
                              v-model="editedItem.dueDate"
                              label="Select Due Date"
                              append-icon="event"
                              readonly
                            ></v-text-field>
                            <v-date-picker v-model="editedItem.dueDate" @input="menu1 = false"></v-date-picker>
                          </v-menu>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Note:</label>
                        </v-flex>
                        <v-flex xs5 class="ml-3">
                          <v-text-field
                            placeholder="fill your Serial Number"
                            v-model="editedItem.note"
                            type="text"
                          ></v-text-field>
                        </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">Save</v-btn>
                      </v-card-actions>
                    </v-flex>
                  </v-layout>
                </v-container>
              </v-form>
            </v-card-text>
          </v-card>
        </v-dialog>

        <!-- ****** PROFILE VIEW PARTICULAR ISSUE DATA ******  -->

        <v-dialog v-model="dialog1" max-width="800px">
          <v-card>
            <v-toolbar color="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>Issue a Book</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
              <v-icon @click="close1">close</v-icon>
            </v-toolbar>
            <v-card-text>
              <v-container grid-list-md>
                <v-layout wrap>
                  <v-flex>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Book:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ editedItem.name }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Serial Number:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ editedItem.serialNumber }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Issue date:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ dates(editedItem.creted) }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Due date:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ dates(editedItem.dueDate) }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Status:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ editedItem.status }}</h5>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                </v-layout>
              </v-container>
            </v-card-text>
          </v-card>
        </v-dialog>

        <v-snackbar
          :timeout="timeout"
          :top="y === 'top'"
          :right="x === 'right'"
          :vertical="mode === 'vertical'"
          v-model="snackbar"
          color="success"
        >{{ text }}</v-snackbar>

        <!-- ****** EXISTING ISSUE TABLE****** -->
        <v-card>
          <v-layout>
            <v-flex lg1 xs4 md4 xl1 class="hidden-xs-only">
              <label class="right pt-4">Library ID:</label>
            </v-flex>
            <v-flex lg2 md3 xs7>
              <v-text-field
                class="pl-3"
                @keyup.enter="getIssueList"
                v-model="libraryId"
                placeholder="fill your library Id"
              ></v-text-field>
            </v-flex>
            <v-flex lg9 md3 xs5>
              <v-btn
                round
                class="black mt-1 right hidden-xs-only"
                @click="getIssueList"
                :loading="loadingSearch"
                dark
              >Search</v-btn>
              <v-btn
                round
                class="black mt-4 right hidden-sm-only hidden-xl-only hidden-md-only hidden-lg-only"
                :loading="loadingSearch"
                @click="getIssueList"
                small
                dark
              >Search</v-btn>
            </v-flex>
          </v-layout>
        </v-card>
        <v-data-table
          :headers="headers"
          :items="desserts"
          :pagination.sync="pagination"
          :search="search"
        >
          <template slot="items" slot-scope="props" v-if="props.item.isReturn != true">
            <td class="text-xs-center">{{ props.index + 1}}</td>
            <td id="td" class="text-xs-center">{{ props.item.bookId.name}}</td>
            <td id="td" class="text-xs-center">{{ props.item.serialNumber}}</td>
            <td id="td" class="text-xs-center">{{ dates(props.item.created) }}</td>
            <td id="td" class="text-xs-center">{{ dates(props.item.dueDate) }}</td>
            <td id="td" class="text-xs-center">
              <span
                class="green lighten-1 pa-2 white--text paymentStatus"
              >{{ props.item.bookId.status}}</span>
            </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 Issue ****** -->

      <v-tab-item>
        <v-container>
          <v-snackbar
            :timeout="timeout"
            :top="y === 'top'"
            :right="x === 'right'"
            :vertical="mode === 'vertical'"
            v-model="snackbar"
            :color="color"
          >{{ 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-flex xs12>
                    <v-layout>
                      <v-flex xs4 class="pt-4 subheading">
                        <label class="right">Library ID:</label>
                      </v-flex>
                      <v-flex xs4 class="ml-3">
                        <v-text-field
                          v-model="libraryID"
                          placeholder="fill your Library ID"
                          :rules="libraryIDRules"
                          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">Book:</label>
                      </v-flex>
                      <v-flex xs4 class="ml-3">
                        <v-select
                          label="Select Book Name"
                          :rules="bookRules"
                          :items="books"
                          item-text="name"
                          item-value="_id"
                          v-model="bookId"
                          @change="getParticularBookData(bookId)"
                          required
                        ></v-select>
                      </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
                          placeholder="fill your Author"
                          :rules="authorRules"
                          v-model="addIssue.author"
                        ></v-text-field>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-flex xs12>
                    <v-layout>
                      <v-flex xs4 class="pt-4 subheading">
                        <label class="right">Subject Code:</label>
                      </v-flex>
                      <v-flex xs4 class="ml-3">
                        <v-text-field
                          placeholder="fill your Subject Code"
                          :rules="subjectCodeRules"
                          v-model="addIssue.subjectCode"
                        ></v-text-field>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-flex xs12>
                    <v-layout>
                      <v-flex xs4 class="pt-4 subheading">
                        <label class="right">Serial No:</label>
                      </v-flex>
                      <v-flex xs4 class="ml-3">
                        <v-text-field
                          placeholder="fill your Serial No"
                          :rules="authorRules"
                          v-model="serialNo"
                        ></v-text-field>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-flex xs12>
                    <v-layout>
                      <v-flex xs4 class="pt-4 subheading">
                        <label class="right">Due Date:</label>
                      </v-flex>
                      <v-flex xs4 class="ml-3">
                        <v-menu
                          ref="menu2"
                          :close-on-content-click="false"
                          v-model="menu2"
                          :nudge-right="40"
                          :return-value.sync="date"
                          lazy
                          transition="scale-transition"
                          offset-y
                          full-width
                          min-width="290px"
                        >
                          <v-text-field
                            slot="activator"
                            v-model="date"
                            label="Select Due Date"
                            append-icon="event"
                            readonly
                          ></v-text-field>
                          <v-date-picker v-model="date" @input="$refs.menu2.save(date)"></v-date-picker>
                        </v-menu>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-flex xs12>
                    <v-layout>
                      <v-flex xs4 class="pt-4 subheading">
                        <label class="right">Note:</label>
                      </v-flex>
                      <v-flex xs4 class="ml-3">
                        <v-text-field
                          placeholder="fill your Note"
                          :rules="noteRules"
                          v-model="note"
                        ></v-text-field>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-layout>
                    <v-flex xs12 sm6 offset-sm3>
                      <v-card-actions>
                        <v-btn @click="clear" round dark>clear</v-btn>
                        <v-spacer></v-spacer>
                        <v-btn @click="submit" round dark :loading="loading" :disabled="disable">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 moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    date: null,
    menu1: false,
    menu2: false,
    color: "",
    dueDate: null,
    y: "top",
    x: "right",
    mode: "",
    timeout: 10000,
    text: "",
    libraryId: "",
    loading: false,
    loadingSearch: false,
    date: null,
    search: "",
    showLoader: false,
    dialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    addclass: [],
    addSection: [],
    pagination: {
      rowsPerPage: 15
    },
    libraryIDRules: [v => !!v || " Library ID is required"],
    bookRules: [v => !!v || " book Name is required"],
    authorRules: [v => !!v || "Author Name is required"],
    subjectCodeRules: [v => !!v || "Subject Code is required"],
    authorRules: [v => !!v || "Author is required"],
    noteRules: [v => !!v || "Note is required"],
    headers: [
      {
        align: "justify-center",
        text: "No",
        sortable: false,
        value: "No"
      },
      { text: "Book", vaue: "name", sortable: false, align: "center" },
      {
        text: "Serial Number",
        value: "serialNumber",
        sortable: false,
        align: "center"
      },
      {
        text: "Issue Date",
        value: "created",
        sortable: false,
        align: "center"
      },
      {
        text: "Due Date",
        value: "dueDate",
        sortable: false,
        align: "center"
      },
      {
        text: "Status",
        value: "status",
        sortable: false,
        align: "center"
      },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    desserts: [],
    addIssue: {},
    bookId: "",
    libraryID: "",
    serialNo: "",
    note: "",
    editedItem: {},
    books: [],
    token: "",
    disable: false
  }),
  methods: {
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    pickFile() {
      this.$refs.image.click();
    },
    getIssueList() {
      this.showLoader = true;
      this.loadingSearch = true;
      http()
        .get(
          "/getBooksIssueList",
          {
            params: { libraryId: this.libraryId }
          },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.desserts = response.data.data;
          this.showLoader = false;
          this.loadingSearch = false;
        })
        .catch(error => {
          // console.log("err====>", err);
          this.showLoader = false;
          this.loadingSearch = false;
          this.snackbar = true;
          this.text = error.response.data.message;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    editItem(item) {
      console.log("item", item);
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editedItem.name = item.bookId.name;
      this.editedItem.status = item.bookId.status;
      this.editedItem.dueDate =
        this.editedItem.dueDate != undefined
          ? (this.editedItem.dueDate = this.editedItem.dueDate.substring(0, 10))
          : (this.editedItem.dueDate = "");
      this.dialog = true;
    },
    profile(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editedItem.name = item.bookId.name;
      this.editedItem.status = item.bookId.status;

      this.dialog1 = true;
    },
    returnBook(item) {
      let returnBook = {
        bookIssueId: item._id
      };
      http()
        .put(
          "/returnBook",
          confirm("Are you sure you want to return this?") && returnBook
        )
        .then(response => {
          this.snackbar = true;
          this.text = "Successfully return Issue a Book ";
          this.getIssueList();
        })
        .catch(error => {
          // console.log(error);
        });
    },
    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;
    },
    close1() {
      this.dialog1 = false;
    },
    submit() {
      this.loading = true;
      if (this.$refs.form.validate()) {
        let createBook = {
          bookId: this.bookId,
          author: this.addIssue.author,
          subjectCode: this.addIssue.subjectCode,
          libraryId: this.libraryID,
          serialNumber: this.serialNo,
          note: this.note,
          dueDate: this.date
        };
        console.log("====================", createBook);
        http()
          .post("/createBookIssue", createBook)
          .then(response => {
            this.snackbar = true;
            this.text = "New Issue a Book added successfully";
            this.getIssueList();
            this.color = "succses";
            this.loading = false;
            this.clear();
          })
          .catch(error => {
            if ((this.snackbar = true)) {
              this.text = error.response.data.message;
              this.color = "red";
            }
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.disable = false;
    },
    save() {
      this.editedItem.bookIssueId = this.editedItem._id;
      this.editedItem.bookId = this.editedItem.bookId._id
      http()
        .put("/updateBookIssue", this.editedItem)
        .then(response => {
          console.log("updateIssue", response);
          this.snackbar = true;
          this.text = "Successfully Edit Issue a Book";
          this.color = "green";
          this.getIssueList();
          this.close();
        })
        .catch(error => {
          // console.log(error);
          if ((this.snackbar = true)) {
            this.text = error.response.data.message;
            this.color = "red";
          }
        });
    },
    getBookData() {
      this.showLoader = true;
      http()
        .get("/getBooksList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.books = response.data.data;
          this.showLoader = false;
          // console.log("getAllfeetypes=====>",response.data.data)
        })
        .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);
          }
        });
    },
    getParticularBookData(books) {
      console.log("books", books);
      for (let i = 0; i < this.books.length; i++) {
        if (books == this.books[i]._id) {
          console.log("books", this.books[i].remaining);
          if (this.books[i].remaining <= 0) {
            this.snackbar = true;
            this.text = "Book is unavailable";
            this.color = "red";
            this.disable = true;
          } else if (this.books[i].remaining > 0) {
            this.disable = false;
          }
          this.addIssue = {
            author: this.books[i].author,
            subjectCode: this.books[i].subjectCode
          };
        }
      }
      this.addIssue.boojk = books;
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getBookData();
  },
  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>