<template>
  <v-container fluid class="body-color">
    <!-- ****** EDITS COURSES DETAILS ****** -->
    <v-dialog v-model="editStudentDialog" max-width="600px" scrollable>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Annoucement</label>
            <v-icon size="24" class="right" @click="editStudentDialog = 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"
                        label="Select Class"
                        v-model="editedItem.select"
                        item-text="classNum"
                        item-value="_id"
                        name="Select Class"
                        required
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 sm5 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Course Name:</label>
                      <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Course:</label>
                    </v-flex>
                    <v-flex xs8 sm7 class="ml-3">
                      <v-select
                        :items="courseData"
                        item-text="courseName"
                        item-value="_id"
                        v-model="editedItem.courseName"
                        placeholder="fill your Course name"
                        type="text"
                        :rules="courseRules"
                        required
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 sm5 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Discussion Type:</label>
                      <label
                        class="right hidden-lg-only hidden-md-only hidden-xl-only"
                      >DiscussionType:</label>
                    </v-flex>
                    <v-flex xs8 sm7 class="ml-3">
                      <v-text-field
                        v-model="editedItem.discussionType"
                        placeholder="fill your Course Name"
                        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
                        label="Select Image"
                        @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>

    <!-- ****** PROFILE VIEW STUDENTS DEATILS ******  -->

    <v-dialog v-model="profileStudentDialog" max-width="600px" scrollable>
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Annoucement</label>
            <v-icon size="24" class="right" @click="profileStudentDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-flex align-center justify-center layout text-xs-center class="mt-3">
            <v-avatar size="100px">
              <img src="/static/icon/user.png" v-if="!editedItem.attachementUrl" />
              <img :src="editedItem.attachementUrl" v-else-if="editedItem.attachementUrl" />
            </v-avatar>
          </v-flex>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex xs12>
                <v-layout>
                  <v-flex xs6 sm6>
                    <h5 class="right my-1">
                      <b>Discussion Type :</b>
                    </h5>
                  </v-flex>
                  <v-flex sm6 xs6>
                    <h5 class="my-1 left">{{ editedItem.discussionType }}</h5>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- ****** Annoucement 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="addAnnoucementDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addAnnoucementDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Annoucement
      </v-btn>
      <v-card-actions class="hidden-xs-only hidden-sm-only">
        <v-flex md13 lg12>
          <v-layout>
            <v-flex lg6 md12>
              <v-layout>
                <v-select
                  :items="addclass"
                  label="Select Class"
                  v-model="selectAnnoucement.classId"
                  item-text="classNum"
                  item-value="_id"
                  name="Select Class"
                  :rules="classRules"
                  required
                  class="ml-2"
                  @change="getCourses(selectAnnoucement.classId)"
                ></v-select>
                <v-select
                  :items="courseData"
                  label="Select Course"
                  v-model="selectAnnoucement.courseId"
                  item-text="courseName"
                  item-value="_id"
                  :rules="courseRules"
                  required
                  class="ml-4"
                ></v-select>
              </v-layout>
            </v-flex>
          </v-layout>
        </v-flex>
      </v-card-actions>
      <v-spacer></v-spacer>
      <v-btn
        @click="getAnnoucementes()"
        round
        dark
        :loading="loading"
        class="open-dialog-button hidden-xs-only hidden-sm-only"
      >Find</v-btn>
      <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 sm7 lg2 md3 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-card flat class="elevation-0 transparent">
      <v-flex class="hidden-xl-only hidden-lg-only hidden-md-only">
        <v-layout>
          <v-flex xs12>
            <v-select
              :items="addclass"
              label="Select Class"
              v-model="selectAnnoucement.select"
              item-text="classNum"
              item-value="_id"
              name="Select Class"
              :rules="classRules"
              class="px-2"
            ></v-select>
          </v-flex>
        </v-layout>
        <v-layout>
          <v-flex xs5 class="mx-auto mb-2">
            <v-btn
              @click="getAnnoucementes()"
              block
              round
              dark
              :loading="loading"
              class="add-button"
            >Find</v-btn>
          </v-flex>
        </v-layout>
      </v-flex>
    </v-card>
    <v-data-table
      :headers="headers"
      :items="annoucementData"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr row-click" @click="rowAnnoucement(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.discussionType}}</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; "
                  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>
    <!-- ****** Add Annoucement DETAILS******-->
    <v-dialog v-model="addAnnoucementDialog" max-width="500" v-if="addAnnoucementDialog">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Annoucement</label>
            <v-icon
              size="24"
              class="right"
              @click="$refs.form.reset();addAnnoucementDialog = false"
            >cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-layout align-center>
            <v-flex xs12>
              <v-flex xs12 sm12>
                <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"
                    >
                      <v-avatar size="100px" v-if="!imageUrl">
                        <img src="/static/icon/user.png" />
                      </v-avatar>
                      <input
                        type="file"
                        style="display: none"
                        ref="image"
                        accept="image/*"
                        @change="onFilePicked"
                      />
                      <img
                        :src="imageData.imageUrl"
                        height="150"
                        width="150"
                        v-if="imageUrl"
                        style="border-radius:50%; width:200px"
                      />
                    </v-flex>
                  </v-layout>
                  <v-layout wrap>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex x4 sm4 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 sm8 class="ml-3">
                          <v-select
                            :items="addclass"
                            label="Select Class"
                            v-model="addAnnoucement.select"
                            item-text="classNum"
                            item-value="_id"
                            name="Select Class"
                            :rules="classRules"
                            @change="getCourses(addAnnoucement.select)"
                            required
                          ></v-select>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout wrap>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 sm4 class="pt-4 subheading">
                          <label class="right hidden-xs-only hidden-sm-only">Course Name:</label>
                          <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Course:</label>
                        </v-flex>
                        <v-flex xs8 sm8 class="ml-3">
                          <v-select
                            :items="courseData"
                            item-text="courseName"
                            item-value="_id"
                            v-model="addAnnoucement.courseName"
                            placeholder="fill your Course name"
                            type="text"
                            :rules="courseRules"
                            required
                          ></v-select>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 sm4 class="pt-4 subheading">
                          <label class="right hidden-xs-only hidden-sm-only">Discussion Type:</label>
                          <label
                            class="right hidden-lg-only hidden-md-only hidden-xl-only"
                          >DiscussionType:</label>
                        </v-flex>
                        <v-flex xs8 sm8 class="ml-3">
                          <v-text-field
                            v-model="addAnnoucement.discussionType"
                            placeholder="fill your Course name"
                            type="text"
                            :rules="courseRules"
                            required
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 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 class="ml-3">
                          <v-text-field
                            label="Select Image"
                            @click="pickFile"
                            v-model="imageName"
                            append-icon="attach_file"
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout class="right">
                        <v-btn @click="submit" round dark :loading="loading" class="add-button">Add</v-btn>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                </v-form>
              </v-flex>
            </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 moment from "moment";
import countryList from "@/script/country.js";
import parent from "@/script/parents.js";

export default {
  data: () => ({
    showNext: false,
    snackbar: false,
    y: "top",
    x: "right",
    role: "",
    mode: "",
    append: "",
    timeout: 3000,
    text: "",
    show: true,
    color: "",
    showSearch: false,
    showLoader: false,
    loading: false,
    editLoading: false,
    date: null,
    search: "",
    menu: false,
    menu1: false,
    editStudentDialog: false,
    profileStudentDialog: false,
    addAnnoucementDialog: false,
    valid: true,
    addclass: [],
    addSection: [],
    pagination: {
      rowsPerPage: 10,
    },
    imageData: {},
    imageName: "",
    imageUrl: "",
    imageFile: "",
    editImageName: "",
    editImageUrl: "",
    courseRules: [(v) => !!v || " Course Name is required"],
    classRules: [(v) => !!v || " Class Name is required"],
    sectionRules: [(v) => !!v || "Section Name is required"],
    errorMessages: "",
    headers: [
      {
        text: "Image",
        value: "attachementUrl",
        sortable: false,
        align: "center",
      },
      {
        text: "Discussion Type",
        value: "discussionType",
        sortable: false,
        align: "center",
      },
      { text: "Action", value: "", sortable: false, align: "center" },
    ],
    courseData: [],
    editedIndex: -1,
    addAnnoucement: {
      select: "",
    },
    selectAnnoucement: {},
    editedItem: {},
    annoucementData: [],
  }),
  watch: {
    addAnnoucementDialog: function (val) {
      if (!val) {
        this.addAnnoucement = [];
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
  },
  methods: {
    getCourses(selectCourseId) {
      this.showLoader = true;
      http()
        .get("/getCourseesList", {
          params: {
            classId: selectCourseId,
          },
        })
        .then((response) => {
          this.courseData = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          console.log("err====>", err);
          this.showLoader = false;
        });
    },
    getAnnoucementes() {
      this.showLoader = true;
      http()
        .get("/getAnnoucementesList", {
          params: {
            courseId: this.selectAnnoucement.courseId,
            classId: this.selectAnnoucement.classId,
          },
        })
        .then((response) => {
          this.annoucementData = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          console.log("err====>", err);
          this.showLoader = false;
        });
    },
    // getSections(_id) {
    //   var token = this.$store.state.token;
    //   this.showLoader = true;
    //   http()
    //     .get(
    //       "/getSectionsList",
    //       { params: { classId: _id } },
    //       {
    //         headers: { Authorization: "Bearer " + token }
    //       }
    //     )
    //     .then(response => {
    //       this.addSection = response.data.data;
    //       this.showLoader = false;
    //     })
    //     .catch(err => {
    //       this.showLoader = false;
    //     });
    // },
    pickFile() {
      this.$refs.image.click();
    },
    pickEditFile() {
      this.$refs.editDataImage.click();
    },
    dates: function (date) {
      return moment(date).format("MMMM DD, YYYY");
      return date;
    },
    onFilePicked(e) {
      // console.log(e)
      const files = e.target.files;
      this.imageData.upload = e.target.files[0];
      if (files[0] !== undefined) {
        this.imageName = files[0].name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.imageUrl = fr.result;
          this.imageFile = files[0]; // this is an image file that can be sent to server...
          this.imageData.imageUrl = URL.createObjectURL(this.imageFile);
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
    onEditFilePicked(e) {
      console.log(e);
      const files = e.target.files;
      if (files[0] !== undefined) {
        this.editImageName = files[0].name;
        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 = "";
      }
    },
    editItem(item) {
      this.editedIndex = this.courseData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editStudentDialog = true;
    },
    profile(item) {
      this.editedIndex = this.courseData.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.profileStudentDialog = true;
    },
    deleteItem(item) {
      let deleteAnnoucement = {
        annoucementId: item._id,
      };
      http()
        .delete(
          "/deleteAnnoucement",
          confirm("Are you sure you want to delete this?") && {
            params: deleteAnnoucement,
          }
        )
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.getAnnoucementes();
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    close() {
      this.editStudentDialog = false;
    },
    closeStudentProfile() {
      this.profileStudentDialog = false;
    },
    rowAnnoucement(id) {
      this.$router.push({
        name: "Annoucement Forum",
        params: { annoucementId: id },
      });
    },
    submit() {
      if (this.$refs.form.validate()) {
        let addCourse = {
          classId: this.addAnnoucement.select,
          sectionId: this.addAnnoucement.selectSection,
          discussionType: this.addAnnoucement.discussionType,
          courseId: this.addAnnoucement.courseName,
        };
        if (this.imageUrl) {
          var str = this.imageUrl;
          const [baseUrl, imageUrl] = str.split(/,/);
          addCourse.upload = imageUrl;
        }
        this.loading = true;
        http()
          .post("/createAnnoucement", addCourse)
          .then((response) => {
            this.snackbar = true;
            this.text = "New Annoucement added successfully";
            this.color = "green";
            this.addAnnoucementDialog = false;
            this.clear();
            this.loading = false;
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "error";
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.imageUrl = "";
    },
    save() {
      let editAnnoucement = {
        annoucementId: this.editedItem._id,
        discussionType: this.editedItem.discussionType,
        classId: this.editedItem.select,
        courseId: this.editedItem.courseName,
      };
      if (this.editImageUrl) {
        var str = this.editImageUrl;
        const [baseUrl, editImageUrl] = str.split(/,/);
        editAnnoucement.upload = editImageUrl;
      }
      this.editLoading = true;
      http()
        .put("/updateAnnoucement", editAnnoucement)
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.imageUrl = "";
          this.getAnnoucementes();
          this.close();
          this.editLoading = false;
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.statusText;
          this.color = "error";
          this.editLoading = false;
        });
    },
    displaySearch() {
      this.show = false;
      this.showSearch = true;
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    var token = this.$store.state.token;
    http()
      .get("/getClassesList", {
        headers: { Authorization: "Bearer " + token },
      })
      .then((response) => {
        this.addclass = 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);
          this.$store.dispatch("Role", null);
        }
      });
  },
};
</script>
<style>
.row-click {
  cursor: pointer;
}
</style>