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

      <!-- ****** EDIT  SECTION  ****** -->
      <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-toolbar color="grey lighten-2">
            <v-spacer></v-spacer>
            <v-toolbar-title>
              <h3>Edit Section</h3>
            </v-toolbar-title>
            <v-spacer></v-spacer>
          </v-toolbar>
          <v-card>
            <v-container>
              <v-layout wrap justify-center>
                <v-flex xs12 sm9>
                  <v-form>
                    <v-layout>
                      <v-flex xs5 sm4 class="pt-4 subheading">
                        <label class="pl-3">Class Name:</label>
                        <!-- <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Class:</label> -->
                      </v-flex>
                      <v-flex xs7 sm8>
                        <v-autocomplete
                          :items="addclass"
                          :label="editedItem.classData.classNum"
                          v-model="editItem.classId"
                          item-text="classNum"
                          item-value="_id"
                        ></v-autocomplete>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm4 class="pt-4 subheading">
                        <label>Section Name:</label>
                      </v-flex>
                      <v-flex xs7 sm8>
                        <v-autocomplete
                          v-model="editedItem.name"
                          placeholder="fill your Section Name"
                          :items="SectionName"
                        ></v-autocomplete>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm4 class="pt-4 subheading">
                        <label>Class Incharge:</label>
                      </v-flex>
                      <v-flex xs7 sm8>
                        <v-select
                          :items="teacherList"
                          v-model="editedItem.classInchargeId"
                          :label="editedItem.teacherData[0].name"
                          item-text="name"
                          item-value="_id"
                        ></v-select>
                      </v-flex>
                    </v-layout>
                    <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-form>
                </v-flex>
              </v-layout>
            </v-container>
          </v-card>
        </v-dialog>

        <!-- ****** PROFILE VIEW SECTION DATA ******  -->

        <v-dialog v-model="dialog1" max-width="600px">
          <v-toolbar color="grey lighten-2">
            <v-spacer></v-spacer>
            <v-toolbar-title>
              <h3>Section</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 hidden-xs-only hidden-sm-only">
                          <b>Class Name:</b>
                        </h5>
                        <h5 class="right my-1 hidden-lg-only hidden-md-only hidden-xl-only">
                          <b>Class:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs5>
                        <h5 class="my-1">{{ editedItem.classData.classNum }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs7 sm6>
                        <h5 class="right my-1">
                          <b>Section Name:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs5>
                        <h5 class="my-1">{{ editedItem.name }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs7 sm6>
                        <h5 class="right my-1">
                          <b>Class Incharge:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs5>
                        <h5 class="my-1">{{ editedItem.teacherData[0].name }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs7 sm6>
                        <h5 class="right my-1">
                          <b>Session:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs5>
                        <h5 class="my-1">{{ editedItem.session }}</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-USERS StudentS Table ****** -->

        <v-data-table
          :headers="headers"
          :items="desserts"
          :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.classData.classNum }}</td>
            <td id="td" class="text-xs-center">{{ props.item.name }}</td>
            <td id="td" class="text-xs-center">{{ props.item.session }}</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 Students ****** -->

      <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 class="mt-4">
                    <v-form ref="form" v-model="valid" lazy-validation>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Section:</label>
                        </v-flex>
                        <v-flex xs6 class="ml-3">
                          <v-autocomplete
                            v-model="sectionData.name"
                            placeholder="fill your Section Name"
                            :items="SectionName"
                            :rules="nameRules"
                            required
                          ></v-autocomplete>
                        </v-flex>
                      </v-layout>
                      <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="addclass"
                            label="Select Class"
                            v-model="sectionData.classNum"
                            item-text="classNum"
                            item-value="_id"
                            name="Select Class"
                            :rules="classRules"
                            required
                          ></v-select>
                        </v-flex>
                      </v-layout>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Incharge:</label>
                        </v-flex>
                        <v-flex xs6 class="ml-3">
                          <v-select
                            :items="teacherList"
                            label="Select Incharge"
                            v-model="sectionData.sectionId"
                            item-text="name"
                            item-value="_id"
                            name="Select Class"
                            :rules="inchargeRules"
                            required
                          ></v-select>
                        </v-flex>
                      </v-layout>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Session:</label>
                        </v-flex>
                        <v-flex xs6 class="ml-3">
                          <v-text-field
                            v-model="sectionData.session"
                            placeholder="fill your Session"
                            name="name"
                            type="text"
                            :rules="sessionRules"
                            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 { apiCollection } from "@/schoolApi/apiCollection";
// const getSectionData = apiCollection.get("posts");

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,
    validEdit: true,
    isActive: true,
    newActive: false,
    details: [],
    AddUsercredentials: {},
    pagination: {
      rowsPerPage: 15
    },
    nameRules: [v => !!v || " Section Name is required"],
    classRules: [v => !!v || " Class Name is required"],
    sessionRules: [v => !!v || " Session is required"],
    inchargeRules: [v => !!v || " Incharge Name is required"],
    SectionName: ["A", "B", "C", "D", "E", "F"],
    headers: [
      {
        text: "No",
        align: "center",
        sortable: false,
        value: "No"
      },
      {
        text: "Class Name",
        value: "classData.classNum",
        sortable: false,
        align: "center"
      },
      { text: "Section Name", value: "name", sortable: false, align: "center" },
      { text: "Session", value: "session", sortable: false, align: "center" },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    desserts: [],
    addclass: [],
    teacherList: [],
    select: "",
    selectId: "",
    token: "",
    editedIndex: -1,
    editedItem: {
      classData: {
        classNum: ""
      },
      // classId: "",
      // classInchargeId: "",
      teacherData: [
        {
          name: ""
        }
      ]
      // name: "",
      // session: new Date().getFullYear()
    },
    sectionData: {
      session: new Date().getFullYear()
    }
  }),
  methods: {
    async getSectionList() {
      // const { data } = await getSectionData.get();
      this.showLoader = true;
      await http()
        .get("/getAllSections", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.desserts = response.data.data;
          this.showLoader = false;
          // console.log("getAllSections=====>",response.data.data)
        })
        .catch(error => {
          this.showLoader = false;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    editItem(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
    },
    profile(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
    },
    deleteItem(item) {
      let deleteStudent = {
        sectionId: item._id
      };
      http()
        .delete(
          "/deleteSection",
          confirm("Are you sure you want to delete this?") && {
            params: deleteStudent
          }
        )
        .then(response => {
          this.snackbar = true;
          this.text = "Successfully delete Existing Section";
          this.getSectionList();
        })
        .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;
    },
    close2() {
      this.dialog2 = false;
    },
    submit() {
      if (this.$refs.form.validate()) {
        let addSection = {
          name: this.sectionData.name,
          classId: this.sectionData.classNum,
          session: this.sectionData.session,
          classInchargeId: this.sectionData.sectionId
        };
        this.loading = true;
        http()
          .post("/createSection", addSection)
          .then(response => {
            this.getSectionList();
            this.snackbar = true;
            this.text = "New Section added successfully";
            this.clear();
            this.loading = false;
          })
          .catch(error => {
            // console.log(error);
            this.snackbar = true;
            this.text = error.response.data.message;
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      this.editedItem.sectionId = this.editedItem._id;
      http()
        .put("/updateSection", this.editedItem)
        .then(response => {
          this.snackbar = true;
          this.text = "Successfully Edit Existing Section";
          this.getSectionList();
          this.close();
        })
        .catch(error => {
          this.text = error.response.data.message;
        });
    },
    getAllTeacher() {
      http()
        .get("/getTeachersList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.teacherList = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          // console.log("err====>", err);
          this.showLoader = false;
        });
    },
    getAllClasses() {
      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.getSectionList();
    this.getAllClasses();
    this.getAllTeacher();
  },
  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>