<template>
  <v-container fluid class="body-color">
    <v-dialog v-model="editDialog" max-width="600px" scrollable persistent>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Course Discussion</label>
            <v-icon size="24" class="right" @click="editDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-form ref="form">
            <v-container fluid>
              <v-layout>
                <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
                  <v-avatar size="100px" v-if="!editedItem.attachementUrl && !editImageUrl">
                    <img src="/static/icon/user.png" />
                  </v-avatar>
                  <img
                    :src="editedItem.attachementUrl"
                    v-else-if="editedItem.attachementUrl && !editImageUrl"
                    height="150"
                    style="border-radius:50%; width:150px"
                  />
                  <img
                    v-if="editImageUrl"
                    :src="editImageUrl"
                    style="border-radius:50%; width:150px;height:150px"
                  />
                  <input
                    type="file"
                    style="display: none"
                    ref="editDataImage"
                    accept="image/*"
                    @change="onEditFilePicked"
                  />
                </v-flex>
              </v-layout>
              <v-layout wrap>
                <v-flex xs12 sm12>
                  <v-layout>
                    <v-flex xs4 sm5 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Select Class:</label>
                      <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Class:</label>
                    </v-flex>
                    <v-flex xs8 sm7 class="ml-3">
                      <v-select
                        :items="addclass"
                        v-model="editedItem.classId"
                        item-text="classNum"
                        item-value="_id"
                        name="Select Class"
                        required
                        @change="editGetCourses(editedItem.classId)"
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 sm5 class="pt-4 subheading">
                          <label class="right">Select Course:</label>
                        </v-flex>
                        <v-flex xs8 sm7 class="ml-3">
                          <v-select
                            :items="editCourseData"
                            label="Select Course"
                            v-model="editedItem.courseId"
                            item-text="courseName"
                            item-value="_id"
                            required
                            class="ml-2"
                          ></v-select>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 sm5 class="pt-4 subheading">
                      <label class="right">Subject:</label>
                    </v-flex>
                    <v-flex xs8 sm7 class="ml-3">
                      <v-text-field v-model="editedItem.subject" type="text" required></v-text-field>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 sm5 class="pt-4 subheading">
                      <label class="right">Description:</label>
                    </v-flex>
                    <v-flex xs8 sm7 class="ml-3">
                      <v-text-field v-model="editedItem.description" type="text" required></v-text-field>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 sm5 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Upload Image:</label>
                      <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Upload:</label>
                    </v-flex>
                    <v-flex xs8 sm7 class="ml-3">
                      <v-text-field
                        @click="pickEditFile"
                        v-model="editImageName"
                        append-icon="attach_file"
                      ></v-text-field>
                    </v-flex>
                  </v-layout>
                </v-flex>
              </v-layout>
              <v-layout>
                <v-flex xs12 sm12 class="px-0 mx-0">
                  <v-layout class="right">
                    <v-btn @click="save" round dark :loading="editLoading" class="add-button">Save</v-btn>
                  </v-layout>
                </v-flex>
              </v-layout>
            </v-container>
          </v-form>
        </v-card-text>
      </v-card>
    </v-dialog>
    <!-- ****** DIsCUSIION TABLE ****** -->
    <v-toolbar color="transparent" flat>
      <v-spacer></v-spacer>
      <v-flex xs12 sm4 md2>
        <v-select
          small
          :items="addclass"
          label="Select Class"
          v-model="getSelectedData.classId"
          item-text="classNum"
          item-value="_id"
          name="Select Class"
          @change="getCourses(getSelectedData.classId)"
          class="mr-2"
          required
        ></v-select>
      </v-flex>
      <v-flex xs12 sm4 md2>
        <v-select
          :items="courseData"
          label="Select Course"
          v-model="getSelectedData.courseId"
          item-text="courseName"
          item-value="_id"
          required
          class="ml-2"
          @change="getCourseDiscussionTable(getSelectedData.courseId)"
        ></v-select>
      </v-flex>
      <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="courseDiscussionData"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr row-click" @click="rowCourseDiscussion(props.item._id)">
          <td class="text-xs-center td td-row">
            <v-avatar size="40">
              <img :src="props.item.attachementUrl" v-if="props.item.attachementUrl" />
              <img src="/static/icon/user.png" v-else-if="!props.item.attachementUrl" />
            </v-avatar>
          </td>
          <td class="text-xs-center td td-row">{{ props.item.subject }}</td>
          <td class="text-xs-center td td-row">{{ props.item.studentId.name}}</td>
          <td class="text-xs-center td td-row">-</td>
          <td class="text-xs-center td td-row">{{ props.item.forumThread.length }}</td>
          <td class="text-xs-center td td-row">
            <span>
              <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>
    <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 moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    color: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    addclass: [],
    pagination: {
      rowsPerPage: 10,
    },
    headers: [
      {
        text: "Image",
        value: "subjattachementUrlect",
        sortable: false,
        align: "center",
      },
      {
        text: "Discussion",
        value: "subject",
        sortable: false,
        align: "center",
      },
      { text: "Started", value: "studentId", sortable: false, align: "center" },
      {
        text: "Last Post",
        value: "forumThread",
        sortable: false,
        align: "center",
      },
      { text: "replies", value: "email", sortable: false, align: "center" },
      { text: "Action", value: "", sortable: false, align: "center" },
    ],
    token: "",
    selectStudents: {
      select: "",
      selectSection: "",
    },

    role: "",
    schoolRole: "",
    menu: false,
    valid: true,

    getSelectedData: {},
    courseDiscussionData: [],
    courseData: [],
    editCourseData: [],
    addSection: [],
    editedItem: {},
    editDialog: false,
    editedIndex: -1,
    editiImageFile: "",
    editImageName: "",
    editImageUrl: "",
    editLoading: false,
    showData: false,
  }),
  methods: {
    // save(date) {
    //   this.$refs.menu.save(date);
    // },
    pickEditFile() {
      this.$refs.editDataImage.click();
    },
    onEditFilePicked(e) {
      console.log(e);
      const files = e.target.files;
      if (files[0] !== undefined) {
        this.editImageName = files[0].name;
        console.log("this.editImageName", this.editImageName);

        if (this.editImageName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.editImageUrl = fr.result;
          this.editiImageFile = files[0]; // this is an image file that can be sent to server...
        });
      } else {
        this.editImageName = "";
        this.editiImageFile = "";
      }
    },
    getAllClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.addclass = response.data.data;
        })
        .catch((error) => {
          // console.log("err====>", err);
          // this.$router.replace({ path: "/" });
        });
    },
    getCourses(classId) {
      this.showLoader = true;
      http()
        .get("/getCourseesList", {
          params: {
            classId: classId,
          },
        })
        .then((response) => {
          this.courseData = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          console.log("err====>", err);
          this.showLoader = false;
        });
    },
    editGetCourses(classId) {
      this.showLoader = true;
      http()
        .get("/getCourseesList", {
          params: {
            classId: classId,
          },
        })
        .then((response) => {
          this.editCourseData = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          console.log("err====>", err);
          this.showLoader = false;
        });
    },
    getCourseDiscussionTable(id) {
      // console.log("id", this.getSelectedData.courseId);
      this.showLoader = true;
      http()
        .get("/getCourseDiscussionesList", {
          params: {
            classId: this.getSelectedData.classId,
            courseId: id,
          },
        })
        .then((response) => {
          //   console.log("response", response.data.data);
          this.courseDiscussionData = response.data.data;
          if (this.courseDiscussionData.length === 0) {
            this.showLoader = false;
            this.snackbar = true;
            this.text = "Data not found!";
            this.color = "error";
            return;
          }
          this.showData = true;
          this.showLoader = false;
        })
        .catch((error) => {
          console.log("err====>", error);
          this.showLoader = false;
        });
    },
    rowCourseDiscussion(id) {
      this.$router.push({
        name: "Course Discussiones Fourm",
        params: { discussionId: id },
      });
    },
    editItem(item) {
      this.editedIndex = this.courseDiscussionData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editDialog = true;
    },
    save() {
      console.log("this.editedItem", this.editedItem);
      let editCourseDiscuss = {
        courseDiscussionId: this.editedItem._id,
        courseId: this.editedItem.courseId,
        studentId: this.editedItem.studentId._id,
        subject: this.editedItem.subject,
        description: this.editedItem.description,
      };
      if (this.editedItem.classId._id) {
        editCourseDiscuss.classId = this.editedItem.classId._id;
      }
      if (!this.editedItem.classId._id) {
        editCourseDiscuss.classId = this.editedItem.classId;
      }
      if (this.editImageUrl) {
        var str = this.editImageUrl;
        const [baseUrl, editImageUrl] = str.split(/,/);
        editCourse.upload = editImageUrl;
      }
      this.editLoading = true;
      http()
        .put("/updateCourseDiscussion", editCourseDiscuss)
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.imageUrl = "";
          this.getCourseDiscussionTable();
          this.editDialog = false;
          this.editLoading = false;
        })
        .catch((error) => {
          this.editLoading = false;
          this.snackbar = true;
          this.text = error.response.data.statusText;
          this.color = "error";
        });
    },
    deleteItem(item) {
      let deleteCourseDiscussion = {
        courseDiscussionId: item._id,
      };
      http()
        .delete(
          "/deleteCourseDiscussion",
          confirm("Are you sure you want to delete this?") && {
            params: deleteCourseDiscussion,
          }
        )
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.getCourseDiscussionTable();
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    displaySearch() {
      this.show = false;
      this.showSearch = true;
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    // this.getStudentList();
    this.token = this.$store.state.token;
    this.role = this.$store.state.role;
    this.getAllClass();
  },
};
</script>

<style>
.row-click {
  cursor: pointer !important;
}
</style>