<template>
  <v-container fluid class="body-color">
    <v-dialog v-model="editSectionDialog" max-width="460px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Section</label>
            <v-icon size="24" class="right" @click="editSectionDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-layout wrap justify-center>
            <v-flex xs12 sm12>
              <v-form>
                <v-layout>
                  <v-flex xs5 sm4 class="pt-4 subheading">
                    <label class="right">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"
                      class="ml-2"
                    ></v-autocomplete>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs5 sm4 class="pt-4 subheading">
                    <h5 class="right my-1 hidden-xs-only hidden-sm-only">Section Name :</h5>
                    <h5 class="right my-1 hidden-lg-only hidden-md-only hidden-xl-only">Name :</h5>
                  </v-flex>
                  <v-flex xs7 sm8>
                    <v-autocomplete
                      v-model="editedItem.name"
                      placeholder="fill your Section Name"
                      :items="SectionName"
                      class="ml-2"
                    ></v-autocomplete>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs5 sm4 class="pt-4 subheading">
                    <h5 class="right my-1 hidden-xs-only hidden-sm-only">Incharge :</h5>
                    <h5 class="right my-1 hidden-lg-only hidden-md-only hidden-xl-only">Incharge :</h5>
                  </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"
                      class="ml-2"
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-flex xs12>
                  <v-card-actions>
                    <v-btn round dark @click.native="closeSectionDialog" class="add-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-flex>
          </v-layout>
        </v-container>
      </v-card>
    </v-dialog>

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

    <v-dialog v-model="viewSectionDialog" max-width="500px">
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Section</label>
            <v-icon size="24" class="right" @click="viewSectionDialog = 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 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 hidden-xs-only hidden-sm-only">
                      <b>Class Incharge :</b>
                    </h5>
                    <h5 class="right my-1 hidden-lg-only hidden-md-only hidden-xl-only">
                      <b>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>
    <!-- ****** Section 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="addSectionDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addSectionDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Section
      </v-btn>
      <v-spacer></v-spacer>
      <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 v-if="showSearch">
        <v-layout>
          <v-text-field
            autofocus
            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="sectionList"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr">
          <td class="td td-row">{{ props.index + 1 }}</td>
          <td class="text-xs-center td td-row">{{ props.item.classData.classNum }}</td>
          <td class="text-xs-center td td-row">{{ props.item.name }}</td>
          <td class="text-xs-center td td-row">{{ props.item.session }}</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"
                  class="mr-3"
                />
                <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>
    <!-- </v-tab-item> -->

    <!-- DIALOG BOX - ADD Students Dialog box -->
    <v-dialog v-model="addSectionDialog" max-width="400px" v-if="addSectionDialog">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Section</label>
            <v-icon
              size="24"
              class="right"
              @click="$refs.form.reset();addSectionDialog = 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 class="pt-4 subheading">
                    <label class="right">Section :</label>
                  </v-flex>
                  <v-flex xs8 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 xs8 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 xs8 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 xs8 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 sm12>
                    <v-card-actions>
                      <v-btn @click="clear" class="add-button" round dark>Clear</v-btn>
                      <v-spacer></v-spacer>
                      <v-btn @click="submit" class="add-button" 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-dialog>
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ text }}</v-snackbar>
    <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 { apiCollection } from "@/schoolApi/apiCollection";
// const getSectionData = apiCollection.get("posts");

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 5000,
    text: "",
    color: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    editSectionDialog: false,
    viewSectionDialog: false,
    valid: true,
    validEdit: true,
    addSectionDialog: false,
    editLoading: false,
    details: [],
    pagination: {
      rowsPerPage: 10,
    },
    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: "",
        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" },
    ],
    sectionList: [],
    addclass: [],
    teacherList: [],
    select: "",
    selectId: "",
    token: "",
    editedIndex: -1,
    editedItem: {
      classData: {
        classNum: "",
      },
      teacherData: [
        {
          name: "",
        },
      ],
      // name: "",
      // session: new Date().getFullYear()
    },
    sectionData: {
      session: new Date().getFullYear(),
    },
  }),
  watch: {
    addSectionDialog: function (val) {
      if (!val) {
        this.sectionData = [];
      }
    },
  },
  methods: {
    getSectionList() {
      // const { data } = await getSectionData.get();
      this.showLoader = true;
      http()
        .get("/getAllSections", {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.sectionList = 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.sectionList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editSectionDialog = true;
    },
    profile(item) {
      this.editedIndex = this.sectionList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.viewSectionDialog = 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 = response.data.message;
          this.color = "green";
          this.getSectionList();
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "green";
        });
    },
    closeSectionDialog() {
      this.editSectionDialog = false;
    },
    closeviewSectionDialog() {
      this.viewSectionDialog = 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.color = "green";
            this.text = "New Section added successfully";
            this.clear();
            this.addSectionDialog = false;
            this.loading = false;
          })
          .catch((error) => {
            this.snackbar = true;
            this.color = "error";
            this.text = error.response.data.message;
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      this.editedItem.sectionId = this.editedItem._id;
      this.editLoading = true;
      http()
        .put("/updateSection", this.editedItem)
        .then((response) => {
          this.editLoading = false;
          this.snackbar = true;
          this.color = "green";
          this.text = response.data.message;
          this.getSectionList();
          this.closeSectionDialog();
        })
        .catch((error) => {
          this.editLoading = false;
          this.snackbar = true;
          this.color = "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: "/" });
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getSectionList();
    this.getAllClasses();
    this.getAllTeacher();
  },
};
</script>
