<template>
  <v-container fluid class="body-color">
    <!-- ****** ATTENDENCE TACHERS 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="addTeacherAttendenceDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        v-if="role != 'TEACHER' "
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addTeacherAttendenceDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Teacher Attendence
      </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 sm8 md3 lg2 v-if="showSearch">
        <v-layout>
          <v-text-field
            autofocus
            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="teachersData"
      :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">
            <v-avatar size="40">
              <img :src="props.item.profilePicUrl" v-if="props.item.profilePicUrl" />
              <img src="/static/icon/user.png" v-else-if="!props.item.profilePicUrl" />
            </v-avatar>
          </td>
          <td class="td td-row text-xs-center">{{ props.item.name}}</td>
          <td class="td td-row text-xs-center">{{ props.item.email }}</td>
          <td class="td td-row text-xs-center">{{ props.item.mobileNo }}</td>
          <td class="text-xs-center td td-row">
            <router-link
              :to="{ name:'View Teacher Attendence',params: { teacherId:props.item._id } }"
            >
              <span>
                <v-tooltip top>
                  <img
                    slot="activator"
                    style="cursor:pointer; width:25px; height:25px; "
                    src="/static/icon/view.png"
                  />
                  <span>View</span>
                </v-tooltip>
              </span>
            </router-link>
          </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 Teachers Attendece****** -->
    <v-dialog v-model="addTeacherAttendenceDialog" width="1600" v-if="addTeacherAttendenceDialog" persistent>
      <v-card flat class="pa-2">
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Teacher Attendence</label>
            <v-icon
              size="24"
              class="right"
              @click="$refs.form.reset();addTeacherAttendenceDialog = false"
            >cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-flex xs12 class="mt-4">
          <v-form ref="form" v-model="valid" lazy-validation>
            <v-layout wrap>
              <v-flex xs12 class="px-4">
                <v-layout>
                  <v-flex xs6 sm6 lg3 md4>
                    <v-menu
                      ref="menu"
                      :close-on-content-click="false"
                      v-model="menu"
                      :nudge-right="40"
                      lazy
                      transition="scale-transition"
                      offset-y
                      full-width
                      min-width="290px"
                    >
                      <v-text-field
                        slot="activator"
                        v-model="date"
                        label="Select Date"
                        append-icon="event"
                        :rules="dataValid"
                        readonly
                      ></v-text-field>
                      <v-date-picker
                        ref="picker"
                        v-model="date"
                        :max="new Date().toISOString().substr(0, 10)"
                        min="1950-01-01"
                        @change="save"
                      ></v-date-picker>
                    </v-menu>
                  </v-flex>
                  <v-flex xs6 sm6 lg9 md8>
                    <v-btn class="right mt-3 add-button" dark round @click="showTable">Attendence</v-btn>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-form>
        </v-flex>
        <v-flex xs12 v-show="attendeceTable" class>
          <v-data-table
            :headers="headers"
            :items="teachersData"
            :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">
                  <v-avatar size="40">
                    <img :src="props.item.profilePicUrl" v-if="props.item.profilePicUrl" />
                    <img src="/static/icon/user.png" v-else-if="!props.item.profilePicUrl" />
                  </v-avatar>
                </td>
                <td class="text-xs-center td td-row">{{ props.item.name}}</td>
                <td class="text-xs-center td td-row">{{ props.item.email }}</td>
                <td class="text-xs-center td td-row">{{ props.item.mobileNo }}</td>
                <td class="text-xs-center td td-row">
                  <v-radio-group v-model="props.item.attendence" :mandatory="false" row>
                    <v-radio
                      v-for="attendences in attendenceType"
                      :key="attendences.value"
                      :label="`${attendences.label}`"
                      :value="attendences.value"
                    ></v-radio>
                  </v-radio-group>
                </td>
              </tr>
            </template>
          </v-data-table>
          <v-flex xs12>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn @click="submit()" class="add-button" round dark>Submit</v-btn>
            </v-card-actions>
          </v-flex>
        </v-flex>
      </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>
    <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 moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    role: "",
    mode: "",
    timeout: 5000,
    text: "",
    date: null,
    menu: false,
    show: true,
    showSearch: false,
    addTeacherAttendenceDialog: false,
    attendeceTable: false,
    showLoader: false,
    loading: false,
    search: "",
    valid: true,
    isActive: true,
    newActive: false,
    dataValid: [(v) => !!v || "Date is required"],
    attendenceType: [
      {
        label: "Present",
        value: "present",
      },
      {
        label: "Late Present With Excuset",
        value: "latePresentWithExcuse",
      },
      {
        label: "Late Present",
        value: "latePresent",
      },
      {
        label: "Absent",
        value: "absent",
      },
    ],
    pagination: {
      rowsPerPage: 8,
    },
    headers: [
      {
        text: "No",
        align: "",
        sortable: false,
        value: "No",
      },
      {
        text: "Profile Pic",
        value: "profilePicUrl",
        sortable: false,
        align: "center",
      },
      { text: "Name", value: "name", sortable: false, align: "center" },
      { text: "Email", value: "email", sortable: false, align: "center" },
      {
        text: "Mobile No",
        value: "mobileNo",
        sortable: false,
        align: "center",
      },
      { text: "Attendance", value: "", sortable: false, align: "center" },
    ],
    desserts: [],
    teachersData: [],
    addTeachers: {},
  }),
  watch: {
    menu(val) {
      val && this.$nextTick(() => (this.$refs.picker.activePicker = "DAY"));
    },
    addTeacherAttendenceDialog: function (val) {
      if (!val) {
        // this.teachersData = [];
        this.date = null;
        this.menu = false;
      }
    },
  },
  methods: {
    save(date) {
      this.$refs.menu.save(date);
    },
    showTable() {
      this.attendeceTable = true;
      this.getTeacherList();
    },
    getTeacherList() {
      this.showLoader = true;
      var token = this.$store.state.token;
      http()
        .get("/getTeachersList", {
          headers: { Authorization: "Bearer " + token },
        })
        .then((response) => {
          this.teachersData = response.data.data;
          // this.desserts = response.data.data;
          var attendence = "";
          for (let i = 0; i < this.teachersData.length; i++) {
            this.teachersData[i].attendence = "present";
          }
          this.showLoader = false;
          // console.log("getTeacherList=====>",this.desserts)
          // console.log("getTeacherList=====>",this.teachersData)
        })
        .catch((error) => {
          this.showLoader = false;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    submit() {
      var teachersAttendence = [];
      for (var j = 0; j < this.teachersData.length; j++) {
        teachersAttendence.push({
          teacherId: this.teachersData[j]._id,
          attendanceType: this.teachersData[j].attendence,
        });
      }
      if (this.$refs.form.validate()) {
        let attendanceData = {
          date: this.date,
          teachers: teachersAttendence,
        };
        http()
          .post("/createTeacherAttendance", attendanceData)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            this.addTeacherAttendenceDialog = false;
            this.clear();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.imageUrl = "";
    },

    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    this.getTeacherList();
    this.role = this.$store.state.role;
  },
};
</script>