<template>
  <div class="body-color">
    <!-- LOADER -->
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>

    <!-- SNACKBAR -->
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="snackbarColor"
    >
      {{ text }}
      <v-spacer></v-spacer>
      <v-btn flat text @click="snackbar = false">X</v-btn>
    </v-snackbar>

    <v-container grid-list-xl class="pt-0">
      <v-layout row class="mt-1">
        <v-flex xs12 md9>
          <v-layout column>
            <!-- HEADING -->
            <v-flex>
              <div class="title side-bar-color font-weight-bold">Announcements</div>
              <div class="subheading grey--text lighten-1">General news and announcements</div>
            </v-flex>

            <!-- DATA TABLE -->
            <v-flex>
              <v-data-table
                :headers="announcementHeaders"
                :items="announcementsList"
                :pagination.sync="pagination"
                :search="search"
                item-key="_id"
              >
                <template slot="items" slot-scope="props">
                  <tr
                    class="tr"
                    @click="props.expanded = !props.expanded; selectedAnnoucementId = props.item._id; getDiscussionesThread()"
                    style="cursor: pointer;"
                  >
                    <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>
                      </span>
                    </td>
                  </tr>
                </template>
                <!-- COURSE ANNOUNCEMENTS REPLY FUNCTIONALITY -->
                <template slot="expand" slot-scope="props">
                  <v-layout>
                    <v-flex xs12 v-for="(annoucementData,i) in annoucementData" :key="i">
                      <!-- TOPIC HEADING -->
                      <v-card class="elevation-0 grey lighten-3 pa-2" flat>
                        <v-list two-line subheader>
                          <v-list-tile>
                            <v-list-tile-avatar>
                              <v-avatar size="46">
                                <img
                                  :src="annoucementData.attachementUrl"
                                  v-if="annoucementData.attachementUrl"
                                />
                                <img
                                  src="/static/icon/user.png"
                                  v-else-if="!annoucementData.attachementUrl"
                                />
                              </v-avatar>
                            </v-list-tile-avatar>
                            <v-list-tile-content>
                              <v-list-tile-title>{{ annoucementData.discussionType }}</v-list-tile-title>
                              <!-- <v-list-tile-sub-title>
                  By
                  <span class="info--text">{{ annoucementData.studentId.name }}</span>
                  - {{dates(annoucementData.created ) }}
                              </v-list-tile-sub-title>-->
                            </v-list-tile-content>
                            <v-list-tile-action>
                              <div>
                                <v-btn
                                  flat
                                  round
                                  dark
                                  class="reply-btn"
                                  @click="showReplyBox = true"
                                >Reply</v-btn>
                              </div>
                            </v-list-tile-action>
                          </v-list-tile>
                        </v-list>
                      </v-card>
                      <!-- REPLY BOX -->
                      <v-flex xs12 class="mt-4" v-show="showReplyBox">
                        <v-textarea
                          name="input-7-1"
                          solo
                          label="Label Text"
                          multi-line
                          v-model="replyDescription"
                        ></v-textarea>
                        <v-btn
                          round
                          dark
                          class="open-dialog-button"
                          flat
                          @click="showReplyBox = false"
                        >Cancel</v-btn>
                        <v-btn
                          round
                          dark
                          :loading="loading"
                          class="reply-btn"
                          @click="replyThreadDiscussion()"
                        >Submit</v-btn>
                      </v-flex>
                      <!-- REPLY THREAD -->
                      <v-layout
                        :class="['mt-4','pl-5','mx-auto',replyThread.teacherId?'justify-start':'justify-end']"
                        v-for="(replyThread,i) in annoucementData.discussionThread.slice().reverse()"
                        :key="i"
                      >
                        <v-flex xs12 md7>
                          <v-card class="elevation-0 grey lighten-1" flat>
                            <v-list two-line subheader class="grey lighten-1 pa-1">
                              <v-list-tile>
                                <v-list-tile-avatar>
                                  <v-avatar size="46">
                                    <img
                                      :src="annoucementData.attachementUrl"
                                      v-if="annoucementData.attachementUrl"
                                    />
                                    <img
                                      src="/static/icon/user.png"
                                      v-else-if="!annoucementData.attachementUrl"
                                    />
                                  </v-avatar>
                                </v-list-tile-avatar>
                                <v-list-tile-content>
                                  <v-list-tile-title>Re: {{ annoucementData.discussionType }}</v-list-tile-title>
                                  <v-list-tile-sub-title>
                                    By
                                    <span
                                      class="info--text"
                                      v-if="replyThread.teacherId"
                                    >{{ replyThread.teacherId.name }}</span>
                                    <span
                                      class="info--text"
                                      v-if="replyThread.studentId"
                                    >{{ replyThread.studentId.name }}</span>
                                    - {{dates(replyThread.created ) }}
                                  </v-list-tile-sub-title>
                                </v-list-tile-content>
                              </v-list-tile>
                            </v-list>
                            <v-list class="pa-2 reply-desc">
                              <v-list-tile-content>
                                <v-list-tile-title
                                  v-show="replyThread.showDescriptionReplyThread"
                                >{{ replyThread.description }}</v-list-tile-title>
                                <v-flex
                                  xs12
                                  sm12
                                  md4
                                  v-show="replyThread.showUpdateReplyThread == true"
                                >
                                  <v-text-field v-model="replyThread.description"></v-text-field>
                                  <v-btn
                                    flat
                                    round
                                    dark
                                    class="reply-btn right"
                                    @click="updateRelpyThreadDiscussion(replyThread)"
                                  >Save</v-btn>
                                </v-flex>
                              </v-list-tile-content>
                            </v-list>
                            <v-list class="grey lighten-4 pa-0">
                              <v-list-tile-action>
                                <v-spacer></v-spacer>
                                <div
                                  v-if="replyThread.studentId && replyThread.studentId._id == localStorage.getItem('parentStudentId')"
                                >
                                  <v-btn
                                    flat
                                    round
                                    dark
                                    class="reply-btn"
                                    @click="deleteRelpyThreadDiscussion(replyThread._id)"
                                  >Delete</v-btn>
                                  <v-btn
                                    flat
                                    round
                                    dark
                                    class="reply-btn mr-4"
                                    @click="showUpdateReplyThreadDiscussion(replyThread)"
                                  >Edit</v-btn>
                                </div>
                              </v-list-tile-action>
                            </v-list>
                          </v-card>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                </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-flex>
          </v-layout>
        </v-flex>

        <v-spacer></v-spacer>

        <!-- COURSES - positioned to the right of the page -->
        <v-flex xs12 md3>
          <v-card class="elevation-0 card-border" height="100%">
            <v-container class="pt-0">
              <div class="side-bar-color font-weight-bold title">Courses</div>

              <div v-for="(course,index) in courseData">
                <v-btn
                  flat
                  class="subheading text-xs-start justify-left"
                  style="cursor: pointer;"
                  block
                  @click="routeToCourseDetails(course._id)"
                >
                  <div style="width: 100%;text-align: left;">
                    <v-icon style="color: red;padding-bottom: 3px;" size="15">play_arrow</v-icon>
                    {{course.courseName}}
                  </div>
                </v-btn>
              </div>
            </v-container>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </div>
</template>
<script>
import AllApiCalls from "@/Services/AllApiCalls.js";
import http from "@/Services/http.js";
import moment from "moment";
export default {
  mixins: [AllApiCalls],
  data() {
    return {
      // DATA TABLE
      localStorage: localStorage,
      moment: moment,
      search: "",
      pagination: {
        rowsPerPage: 10
      },
      announcementHeaders: [
        {
          text: "Image",
          value: "attachementUrl",
          sortable: false,
          align: "center"
        },
        {
          text: "Discussion Type",
          value: "discussionType",
          sortable: false,
          align: "center"
        },
        { text: "Action", value: "", sortable: false, align: "center" }
      ],
      announcementsList: [],
      selectedAnnoucementId: "",

      // COURSE ANNOUNCEMENTS REPLY FUNCTONALITY
      snackbar: false,
      y: "top",
      x: "right",
      mode: "",
      timeout: 3000,
      text: "",
      showLoader: false,
      loading: false,
      date: null,
      token: "",
      role: "",
      schoolRole: "",
      menu: false,
      annoucementData: {},
      showReplyBox: false,
      replyDescription: "",
      loginId: "",
      editedIndex: -1
    };
  },
  methods: {
    getAnnoucementes() {
      this.showLoader = true;
      http()
        .get("/getAnnoucementesList", {
          params: {
            courseId: this.$route.query.courseId,
            classId: localStorage.getItem("parentClassId")
          }
        })
        .then(response => {
          this.announcementsList = response.data.data;
          this.showLoader = false;
        })
        .catch(err => {
          console.log("err====>", err);
          this.showLoader = false;
        });
    },

    async routeToCourseDetails(courseId) {
      /* getParticularCourseDetail- To get courseDetail - defined in GetApis.js*/
      let response = await this.getParticularCourseDetail(courseId);

      /* If the response is null then dont route */
      if (response.data.data.length > 0) {
        this.$router.push({
          name: "Course Details",
          query: { courseId: courseId }
        });
      } else {
        this.seeSnackbar("No Data Available", "warning");
      }
    },

    // COURSE ANNOUNCEMENTS REPLY FUNCTONALITY
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY hh:mm A");
    },
    getDiscussionesThread() {
      // console.log("id", this.getSelectedData.courseId);
      this.showLoader = true;
      http()
        .get("/getParticularAnnoucement", {
          params: {
            annoucementId: this.selectedAnnoucementId
          }
        })
        .then(response => {
          //   console.log("response", response.data.data);
          this.annoucementData = response.data.data;
          // console.log("response", this.annoucementData);
          for (let i = 0; i < this.annoucementData.length; i++) {
            for (
              let j = 0;
              j < this.annoucementData[i].discussionThread.length;
              j++
            ) {
              if (this.annoucementData[i].discussionThread[j]) {
                this.annoucementData[i].discussionThread[
                  j
                ].showUpdateReplyThread = false;
                this.annoucementData[i].discussionThread[
                  j
                ].showDescriptionReplyThread = true;
              }
            }
          }
          this.showLoader = false;
          this.showReplyBox = false;
        })
        .catch(error => {
          console.log("err====>", error);
          this.showLoader = false;
        });
    },
    replyThreadDiscussion() {
      this.showLoader = true;
      var payloadData = {
        annoucementId: this.selectedAnnoucementId,
        studentId: localStorage.getItem("parentStudentId"),
        description: this.replyDescription
      };
      http()
        .put("/replyThread", payloadData)
        .then(response => {
          this.showLoader = false;
          this.getDiscussionesThread();
        })
        .catch(error => {
          this.showLoader = false;
        });
    },
    showUpdateReplyThreadDiscussion(item) {
      this.editedIndex = this.annoucementData.indexOf(item);
      var editedItem = Object.assign({}, item);
      var arrayOfannoucementData = [];
      for (let i = 0; i < this.annoucementData.length; i++) {
        for (
          let j = 0;
          j < this.annoucementData[i].discussionThread.length;
          j++
        ) {
          if (
            editedItem._id == this.annoucementData[i].discussionThread[j]._id
          ) {
            this.annoucementData[i].discussionThread[
              j
            ].showUpdateReplyThread = true;
            this.annoucementData[i].discussionThread[
              j
            ].showDescriptionReplyThread = false;
          }
        }
        arrayOfannoucementData.push(this.annoucementData[i]);
      }
      this.annoucementData = arrayOfannoucementData;
    },
    updateRelpyThreadDiscussion(replyThread) {
      this.showLoader = true;
      var payloadData = {
        discussionThreadId: replyThread._id,
        annoucementId: this.selectedAnnoucementId,
        studentId: localStorage.getItem("parentStudentId"),
        description: replyThread.description
      };
      http()
        .put("/updateThread", payloadData)
        .then(response => {
          this.showLoader = false;
          this.getDiscussionesThread();
        })
        .catch(error => {
          this.showLoader = false;
        });
    },
    deleteRelpyThreadDiscussion(id) {
      this.showLoader = true;
      var payloadData = {
        discussionThreadId: id,
        annoucementId: this.selectedAnnoucementId
      };
      http()
        .put(
          "/deleteThread",
          confirm("Are you sure you want to delete this?") && payloadData
        )
        .then(response => {
          this.showLoader = false;
          this.getDiscussionesThread();
        })
        .catch(error => {
          this.showLoader = false;
        });
    }
  },
  async created() {
    /* getStudentCourses - to get courseData - defined in GetApis.js*/
    await this.getStudentCourses({
      classId: localStorage.getItem("parentClassId"),
      studentId: localStorage.getItem("parentStudentId")
    });

    /* getAnnoucementesList - to populate the data table */
    this.getAnnoucementes();
  }
};
</script>
<style scoped>
.side-bar-color {
  color: #827bfa !important;
  /* border-top-right-radius: 74px !important; */
}
.card-border {
  border: 1px #bdbdbd solid;
  border-radius: 3px;
}

/* ANNOUNCEMENTS REPLY FUNCTIONALITY */
.reply-desc {
  border: 1px solid #f2f2f2;
}
.open-dialog-button {
  background: #827bfa !important;
  border-color: #827bfa !important;
  text-transform: none !important;
}

.reply-btn {
  background: #feb83c !important;
  border-color: #feb83c !important;
  text-transform: none !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}
</style>