<template>
  <v-container fluid class="body-color">
    <!-- ****** EDIT ISSUE  ****** -->
    <v-dialog v-model="editIssueDialog" max-width="600px" scrollable>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Issue</label>
            <v-icon size="24" class="right" @click="editIssueDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-form ref="form">
            <v-container fluid>
              <v-layout wrap>
                <v-flex xs12 sm12>
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right">Library Id:</label>
                    </v-flex>
                    <v-flex xs7 class="ml-3">
                      <v-text-field
                        v-model="editedItem.libraryId"
                        placeholder="fill your Library Id"
                        name="name"
                        type="text"
                        disabled
                      ></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 xs7 class="ml-3">
                      <v-select
                        v-model="editedItem.bookId"
                        label="Select Book Name"
                        :rules="bookRules"
                        :items="books"
                        item-text="name"
                        item-value="_id"
                      ></v-select>
                    </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 xs7 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 xs7 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 xs7 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 xs7 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 xs7 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>
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn round dark @click="save" class="add-button">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="viewIssueDialog" max-width="500px">
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Issue</label>
            <v-icon size="24" class="right" @click="viewIssueDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <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>
    <!-- ****** 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-toolbar color="transparent" flat>
      <v-btn
        fab
        dark
        class="open-dialog-button hidden-xl-only hidden-md-only hidden-lg-only"
        small
        @click="addIssueDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addIssueDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Issue
      </v-btn>
      <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-spacer></v-spacer>
      <v-btn
        round
        class="add-button mt-1 right hidden-xs-only"
        @click="getIssueList"
        :loading="loadingSearch"
        dark
      >Search</v-btn>
      <v-btn
        round
        class="add-button 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-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-show="showSearch">
        <v-layout>
          <v-text-field 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="desserts"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props" v-if="props.item.isReturn != true">
        <tr class="tr">
          <td class="td td-row">{{ props.index + 1}}</td>
          <td class="text-xs-center td td-row">{{ props.item.bookId.name}}</td>
          <td class="text-xs-center td td-row">{{ props.item.serialNumber}}</td>
          <td class="text-xs-center td td-row">{{ dates(props.item.created) }}</td>
          <td class="text-xs-center td td-row">{{ dates(props.item.dueDate) }}</td>
          <td class="text-xs-center td td-row">
            <span
              v-if="props.item.bookId.status === 'AVAILABLE'"
              class="green lighten-1 pa-1 px-2 white--text paymentStatus"
            >{{ props.item.bookId.status}}</span>
            <span
              v-if="props.item.bookId.status === 'UNAVAILABLE'"
              class="red lighten-1 pa-1 px-2 white--text paymentStatus"
            >{{ props.item.bookId.status}}</span>
          </td>
          <td class="text-xs-center td td-row">
            <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>
                <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 Issue ****** -->
    <v-dialog v-model="addIssueDialog" max-width="600px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Issue</label>
            <v-icon size="24" class="right" @click="addIssueDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <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 xs7 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 xs7 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 xs7 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 xs7 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 xs7 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 xs7 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"
                      :rules="dueDateRule"
                      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 xs7 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>
                <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"
                    :disabled="disable"
                  >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-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";

export default {
  data: () => ({
    snackbar: false,
    date: null,
    menu1: false,
    menu2: false,
    color: "",
    show: true,
    showSearch: false,
    dueDate: null,
    y: "top",
    x: "right",
    mode: "",
    timeout: 10000,
    text: "",
    libraryId: "",
    loading: false,
    loadingSearch: false,
    date: null,
    search: "",
    addIssueDialog: false,
    viewIssueDialog: false,
    showLoader: false,
    editIssueDialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    addclass: [],
    addSection: [],
    pagination: {
      rowsPerPage: 10
    },
    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"],
    dueDateRule: [v => !!v || "Due Date 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;
      if (this.libraryID) {
        this.libraryId = this.libraryID;
      }
      http()
        .get(
          "/getBooksIssueList",
          {
            params: {
              libraryId: this.libraryId,
              schoolId: this.$store.state.schoolId
            }
          },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.desserts = response.data.data;
          this.showLoader = false;
          this.loadingSearch = false;
        })
        .catch(error => {
          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);
            this.$store.dispatch("Role", null);
          }
        });
    },
    editItem(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.editIssueDialog = 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.viewIssueDialog = true;
    },
    deleteItem(item) {
      let deleteParticularIssue = {
        bookIssueId: item._id
      };
      http()
        .delete(
          "/deleteBookIssue",
          confirm("Are you sure you want to delete this?") && {
            params: deleteParticularIssue
          }
        )
        .then(response => {
          this.snackbar = true;
          this.text = "Delete Successfully";
          this.getIssueList();
          if (this.libraryID) {
            this.libraryId = this.libraryID;
          }
          if (this.libraryId) {
            this.libraryId = this.libraryId;
          }
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.loading = false;
        })
        .catch(error => {
          // console.log(error);
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "red";
        });
    },
    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 => {});
    },
    close() {
      this.editIssueDialog = false;
    },
    close1() {
      this.viewIssueDialog = false;
    },
    submit() {
      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,
          schoolId: this.$store.state.schoolId
        };
        this.loading = true;
        http()
          .post("/createBookIssue", createBook)
          .then(response => {
            this.getIssueList();
            this.snackbar = true;
            this.text = response.data.message;
            this.addIssueDialog = false;
            this.color = "green";
            this.loading = false;
            this.clear();
          })
          .catch(error => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "red";
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.disable = false;
    },
    save() {
      this.editedItem.bookIssueId = this.editedItem._id;
      this.editedItem.bookId = this.editedItem.bookId;
      http()
        .put("/updateBookIssue", this.editedItem)
        .then(response => {
          this.editIssueDialog = false;
          this.snackbar = true;
          this.text = "Successfully Edit Issue a Book";
          this.color = "green";
          this.getIssueList();
          this.close();
        })
        .catch(error => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "red";
        });
    },
    getBookData() {
      this.showLoader = true;
      http()
        .get("/getBooksList", {
          params: {
            schoolId: this.$store.state.schoolId
          },
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.books = response.data.data;
          this.showLoader = false;
        })
        .catch(error => {
          this.showLoader = false;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    getParticularBookData(books) {
      for (let i = 0; i < this.books.length; i++) {
        if (books == this.books[i]._id) {
          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;
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getBookData();
  }
};
</script>
<style scoped>
.active {
  background-color: gray;
  color: white !important;
}
.activebtn {
  color: black !important;
}
</style>