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

      <!-- ****** EDIT  Subject ****** -->

      <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="600px">
          <v-flex xs12 sm12 class>
            <v-toolbar color="v-toolbar">
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>Edit Subject</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
            </v-toolbar>
            <v-card flat>
                <v-container fluid>
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right">Class:</label>
                    </v-flex>
                    <v-flex xs6 class="ml-3">
                      <v-select
                        :items="classList"
                        label="Select Class"
                        v-model="addSubject.selectName"
                        item-text="classNum"
                        item-value="_id"
                        name="Select Class"
                        :rules="nameRules"
                        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 xs6 class="ml-3">
                      <v-text-field
                        placeholder="fill your Subject"
                        v-model="editedItem.subjectName"
                        type="text"
                        name="email"
                        required
                      ></v-text-field>
                    </v-flex>
                  </v-layout>
                  <v-flex xs12 sm9 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-container>
            </v-card>
          </v-flex>
        </v-dialog>

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

        <v-dialog v-model="dialog1" max-width="600px">
          <v-toolbar color="v-toolbar">
            <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>

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

        <!-- ****** EXISTING SUBJECTS TABLE ****** -->
        <v-card flat>
          <v-card-actions>
            <v-layout>
              <v-flex xs4 sm1>
                <label class="right mt-4">Select Class:</label>
              </v-flex>
              <v-flex xs8 sm3 >
                <v-select
                  :items="classList"
                  label="Select Class"
                  v-model="addSubject.selectName"
                  item-text="classNum"
                  item-value="_id"
                  name="Select Class"
                  :rules="nameRules"
                  @change="getClassSubject(addSubject.selectName)"
                  class="px-4"
                  required
                ></v-select>
              </v-flex>
            </v-layout>
          </v-card-actions>
        </v-card>
        <v-data-table
          :headers="headers"
          :items="subjectList.subjects"
          :pagination.sync="pagination"
          :search="search"
        >
          <template slot="items" slot-scope="props">
            <td id="td" class="text-xs-center">{{ props.index  + 1}}</td>
            <td id="td" class="text-xs-center">{{ props.item.subjectName}}</td>

            <td class="text-xs-center">
              <span>
                <img
                  style="cursor:pointer; width:25px; height:18px; "
                  class="mr-5"
                  @click="profile(props.item)"
                  src="/static/icon/eye1.png"
                />
                <img
                  style="cursor:pointer; width:20px; height:18px; "
                  class="mr-5"
                  @click="editItem(props.item)"
                  src="/static/icon/edit1.png"
                />
                <img
                  style="cursor:pointer;width:20px; height:20px; "
                  class="mr-5"
                  @click="deleteItem(props.item)"
                  src="/static/icon/delete1.png"
                />
              </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 Subject ****** -->

      <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 sm8 offset-sm2 class="top">
            <v-card flat>
              <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
                          xs12
                          class="text-xs-center text-sm-center text-md-center text-lg-center my-4 mr-4"
                        >
                          <v-avatar size="100px">
                            <img src="/static/icon/user.png" />
                          </v-avatar>
                        </v-flex>
                      </v-layout>
                      <v-layout>
                        <v-flex xs4 sm4 class="pt-4 subheading">
                          <label class="right">Class:</label>
                        </v-flex>
                        <v-flex xs8 sm6 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 sm6 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 sm9 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-form>
                  </v-flex>
                </v-layout>
              </v-container>
            </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: "",
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    dialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    gender: ["Male", "Female"],
    pagination: {
      rowsPerPage: 19
    },
    token: "",
    nameRules: [v => !!v || " Class Name is required"],
    subjectRules: [v => !!v || " Subject Name is required"],
    headers: [
      {
        text: "No",
        align: "center",
        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: "",
    editedItem: {
      subjectName: ""
    }
  }),
  methods: {
    pickFile() {
      this.$refs.image.click();
    },

    editItem(item) {
      this.editedItem = Object.assign({}, item);
      console.log("this.editedItem._id", this.editedItem._id);
      this.dialog = true;
    },
    profile(item) {
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
    },
    deleteItem(item) {
      let deleteSubject = {
        classId: this.addSubject.selectName,
        subjectId: item._id
      };
      http()
        .delete(
          "/deleteSubject",
          confirm("Are you sure you want to delete this?") && {
            params: deleteSubject
          }
        )
        .then(response => {
          if ((this.snackbar = true)) {
            this.text = "Successfully delete Existing Subject";
          }
          this.getEventList();
        })
        .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;
      setTimeout(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      }, 300);
    },
    close1() {
      this.dialog1 = false;
    },
    submit() {
      if (this.$refs.form.validate()) {
        http()
          .post("/addSubject", this.addSubject)
          .then(response => {
            if ((this.snackbar = true)) {
              this.text = "New Subject added successfully";
            }
            this.clear();
          })
          .catch(error => {
            // console.log(error);
            if ((this.snackbar = true)) {
              this.text = error.response.data.message;
            }
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      let editSubject = {
        classId: this.addSubject.selectName,
        subjectId: this.editedItem._id,
        subjectName: this.editedItem.subjectName
      };
      http()
        .put("/updateSubject", editSubject)
        .then(response => {
          // console.log("editEvent",editEvent);
          if ((this.snackbar = true)) {
            this.text = "Successfully Edit Existing Subject";
          }
          //   this.getClassSubject();
          http()
            .get(
              "/getParticularClass",
              { params: { classId: this.selectClassId } },
              {
                headers: { Authorization: "Bearer " + this.token }
              }
            )
            .then(response => {
              this.subjectList = response.data.data;
            })
            .catch(err => {
              console.log("err====>", err);
            });
        })
        .catch(error => {
          // console.log(error);
        });
      this.close();
    },
    getClassSubject(id) {
      this.selectClassId = id;
      http()
        .get(
          "/getParticularClass",
          { params: { classId: this.selectClassId } },
          {
            headers: { Authorization: "Bearer " + this.token }
          }
        )
        .then(response => {
          this.subjectList = response.data.data;
        })
        .catch(err => {
          console.log("err====>", err);
        });
    },
    getClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.classList = response.data.data;
        })
        .catch(err => {
          // console.log("err====>", err);
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    // this.getNoticeDataList();
    this.getClass();
  },
  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>