<template>
  <v-container fluid class="body-color">
    <!-- ****** EDIT  Subject ****** -->
    <v-dialog v-model="editSubjectDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Subject</label>
            <v-icon size="24" class="right" @click="editSubjectDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-form ref="formEditSubject" v-model="validEditSubject" lazy-validation>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Class:</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-select
                  :items="classList"
                  label="Select Class"
                  v-model="addSubject.selectName"
                  item-text="classNum"
                  item-value="_id"
                  name="Select Class"
                  :rules="nameEditSubjectRules"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
            <v-layout>
              <v-flex xs4 class="pt-4 subheading">
                <label class="right">Subject:</label>
              </v-flex>
              <v-flex xs8 class="ml-3">
                <v-text-field
                  placeholder="fill your Subject"
                  v-model="editedItem.subjectName"
                  :rules="subjectEditNameRules"
                  type="text"
                  name="email"
                  required
                ></v-text-field>
              </v-flex>
            </v-layout>
            <v-flex xs12 sm12>
              <v-card-actions>
                <v-btn round dark @click.native="close" class="clear-button">Cancel</v-btn>
                <v-spacer></v-spacer>
                <v-btn round dark @click="save" :loading="editLoading" class="add-button">Save</v-btn>
              </v-card-actions>
            </v-flex>
          </v-form>
        </v-container>
      </v-card>
    </v-dialog>

    <!-- ****** VIEW PROFIL NOTICE BOARD ******  -->

    <v-dialog v-model="viewSubjectDialog" max-width="600px">
      <v-toolbar flat class="card-style pa-3" dark>
        <v-spacer></v-spacer>
        <v-toolbar-title>
          <h3>Subject</h3>
        </v-toolbar-title>
        <v-spacer></v-spacer>
        <v-icon @click="close1">close</v-icon>
      </v-toolbar>
      <v-card>
        <v-card-text>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex>
                <v-layout>
                  <v-flex xs7 sm6>
                    <h5 class="right my-1">
                      <b>Subject Name:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm6 xs5>
                    <h5 class="my-1">{{ editedItem.subjectName }}</h5>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- ****** EXISTING SUBJECTS 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="addSubjectDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-flex xs1 class="hidden-sm-only hidden-xs-only">
        <v-btn round class="open-dialog-button" dark @click="addSubjectDialog = true">
          <v-icon class="white--text pr-1" size="20">add</v-icon>Add Subject
        </v-btn>
      </v-flex>
      <v-spacer></v-spacer>
      <v-flex lg2 md2 xs12 v-show="show">
        <v-select
          :items="classList"
          label="Select Your Class"
          v-model="selectClassId"
          item-text="classNum"
          item-value="_id"
          name="Select Class"
          :rules="nameRules"
          @change="getClassSubject"
          class="pl-2"
          required
        ></v-select>
      </v-flex>
      <v-card-title class="body-1" v-show="show">
        <v-btn icon flat @click="displaySearch">
          <v-avatar size="27">
            <img src="/static/icon/search.png" alt="icon" />
          </v-avatar>
        </v-btn>
      </v-card-title>
      <v-flex xs9 sm9 md2 lg2 xl2 v-show="showSearch">
        <v-layout>
          <v-text-field
            v-model="search"
            label="Search"
            prepend-inner-icon="search"
            color="primary"
            style="transition: 0.8s cubic-bezier(0.25, 0.8, 0.25, 1); !important"
          ></v-text-field>
          <v-icon @click="closeSearch" color="error">close</v-icon>
        </v-layout>
      </v-flex>
    </v-toolbar>
    <v-data-table
      :headers="headers"
      :items="subjectList.subjects"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr">
          <td class="td-row td">{{ props.index + 1 }}</td>
          <td class="text-xs-center td td-row">{{ props.item.subjectName }}</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; "
                  class="mr-3"
                  @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 Subject ****** -->
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ text }}</v-snackbar>
    <v-dialog v-model="addSubjectDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Subject</label>
            <v-icon size="24" class="right" @click="addSubjectDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid fill-height>
          <v-layout align-center>
            <v-flex xs12>
              <v-form ref="form" v-model="valid" lazy-validation>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Class :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-3">
                    <v-select
                      v-model="addSubject.classId"
                      label="Select your class"
                      type="text"
                      :items="classList"
                      item-text="classNum"
                      item-value="_id"
                      :rules="nameRules"
                      required
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 sm4 class="pt-4 subheading">
                    <label class="right">Subject :</label>
                  </v-flex>
                  <v-flex xs8 sm8 class="ml-3">
                    <v-text-field
                      v-model="addSubject.subjectName"
                      placeholder="fill your Subject Name"
                      name="name"
                      type="text"
                      :rules="subjectRules"
                      required
                    ></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs12 sm12>
                    <v-card-actions>
                      <v-btn @click="clear" round dark class="clear-button">Clear</v-btn>
                      <v-spacer></v-spacer>
                      <v-btn @click="submit" round dark :loading="loading" class="add-button">Add</v-btn>
                    </v-card-actions>
                  </v-flex>
                </v-layout>
              </v-form>
            </v-flex>
          </v-layout>
        </v-container>
      </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: "",
    color: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    editLoading: false,
    date: null,
    search: "",
    viewSubjectDialog: false,
    editSubjectDialog: false,
    valid: true,
    validEditSubject: true,
    addSubjectDialog: false,
    // isActive: true,
    // newActive: false,
    gender: ["Male", "Female"],
    pagination: {
      rowsPerPage: 10
    },
    token: "",
    nameRules: [v => !!v || " Class Name is required"],
    nameEditSubjectRules: [v => !!v || " Class Name is required"],
    subjectRules: [v => !!v || " Subject Name is required"],
    subjectEditNameRules: [v => !!v || " Subject Name is required"],
    headers: [
      {
        text: "No",
        align: "",
        sortable: false,
        value: "No"
      },
      {
        text: "Subject Name",
        value: "subjectName",
        sortable: false,
        align: "center"
      },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    subjectList: [],
    classList: [],
    editedIndex: -1,
    addSubject: {},
    selectClassId: "",
    selectClassId: "",
    editedItem: {
      subjectName: ""
    }
  }),
  methods: {
    pickFile() {
      this.$refs.image.click();
    },
    editItem(item) {
      this.editedIndex = this.subjectList.subjects;
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
      this.editSubjectDialog = true;
    },
    profile(item) {
      this.editedIndex = this.subjectList.subjects;
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
      this.viewSubjectDialog = true;

    },
    deleteItem(item) {
      let deleteSubject = {
        classId: this.selectClassId,
        subjectId: item._id
      };
      http()
        .delete(
          "/deleteSubject",
          confirm("Are you sure you want to delete this?") && {
            params: deleteSubject
          }
        )
        .then(response => {
          this.getClassSubject();
          this.snackbar = true;
          this.text = "Successfully delete Existing Subject";
        })
        .catch(error => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    close() {
      this.editSubjectDialog = false;
    },
    close1() {
      this.viewSubjectDialog = false;
    },
    submit() {
      if (this.$refs.form.validate()) {
        http()
          .post("/addSubject", this.addSubject)
          .then(response => {
            this.getClassSubject();
            this.snackbar = true;
            this.text = "New Subject added successfully";
            this.clear();
            this.color = "green";
            this.addSubjectDialog = false;
          })
          .catch(error => {
            // console.log(error);
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "error";
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      if (this.$refs.formEditSubject.validate()) {
        let editSubject = {
          classId: this.addSubject.selectName,
          subjectId: this.editedItem._id,
          subjectName: this.editedItem.subjectName
        };
        this.editLoading = true;
        http()
          .put("/updateSubject", editSubject)
          .then(response => {
            this.snackbar = true;
            this.text = "Successfully Edit Existing Subject";
            this.editLoading = false;
            http()
              .get(
                "/getParticularClass",
                { params: { classId: this.selectClassId } },
                {
                  headers: { Authorization: "Bearer " + this.token }
                }
              )
              .then(response => {
                this.subjectList = response.data.data;
                this.getClassSubject();
                this.snackbar = true;
                this.color = "green";
                this.text = response.data.message;
                this.close();
              })
              .catch(err => {
                console.log("err====>", err);
              });
          })
          .catch(error => {
            this.editLoading = false;

            // console.log(error);
          });
      }
    },
    getClassSubject() {
      this.showLoader = true;
      this.selectClassId = this.selectClassId;
      http()
        .get(
          "/getParticularClass",
          { params: { classId: this.selectClassId } },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.subjectList = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          this.showLoader = false;
        });
    },
    getClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.classList = response.data.data;
        })
        .catch(error => {
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    // this.getNoticeDataList();
    this.getClass();
  }
};
</script>