<template>
  <v-container fluid class="body-color">
    <!-- ****** Edit  Notice Board ****** -->
    <v-dialog v-model="editNoticeBoardDialog" max-width="500px" scrollable persistent>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Notice Board</label>
            <v-icon size="24" class="right" @click="editNoticeBoardDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-layout>
            <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
              <img
                src="/static/icon/user.png"
                v-if="!editedItem.eventImageUrl && !imageUrl"
                width="100px"
              />
              <img
                :src="editedItem.eventImageUrl"
                height="150"
                v-else-if="editedItem.eventImageUrl && !imageUrl"
                width="150px"
              />
              <img
                v-if="imageUrl"
                :src="imageUrl"
                height="150"
                style="border-radius:50%; width:150px"
              />
              <input
                type="file"
                style="display: none"
                ref="image"
                accept="image/*"
                @change="onFilePicked"
              />
            </v-flex>
          </v-layout>
          <v-layout wrap>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Title:</label>
                </v-flex>
                <v-flex xs8 class="ml-3">
                  <v-text-field
                    v-model="editedItem.title"
                    placeholder="fill your Title"
                    name="name"
                    type="text"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Description:</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-text-field
                    placeholder="fill your Description"
                    v-model="editedItem.description"
                    type="text"
                    name="email"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right hidden-xs-only hidden-sm-only">Uplaod Image:</label>
                  <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Uplaod :</label>
                </v-flex>
                <v-flex xs7 class="ml-3">
                  <v-text-field
                    label="Select Image"
                    @click="pickFile"
                    v-model="imageName"
                    append-icon="attach_file"
                  ></v-text-field>
                  <input
                    type="file"
                    style="display: none"
                    ref="image"
                    accept="image/*"
                    @change="onFilePicked"
                  />
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn round dark @click="save" class="add-button">Save</v-btn>
              </v-card-actions>
            </v-flex>
          </v-layout>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- ****** VIEW PROFIL NOTICE BOARD ******  -->

    <v-dialog v-model="viewNoticeBoardDialog" max-width="600px" scrollable persistent>
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Notice Board</label>
            <v-icon size="24" class="right" @click="viewNoticeBoardDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-layout>
            <v-flex align-center justify-center layout text-xs-center>
              <img src="/static/icon/user.png" v-if="!editedItem.eventImageUrl" width="80" />
              <img
                :src="editedItem.eventImageUrl"
                v-else-if="editedItem.eventImageUrl"
                class="img"
                width="200"
              />
            </v-flex>
          </v-layout>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex>
                <v-layout>
                  <v-flex xs5 sm6>
                    <h5 class="right my-1">
                      <b>Title:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm6 xs8>
                    <h5 class="my-1">{{ editedItem.title }}</h5>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs5 sm6>
                    <h5 class="right my-1">
                      <b>Description:</b>
                    </h5>
                  </v-flex>
                  <v-flex sm6 xs8>
                    <h5 class="my-1">{{ editedItem.description }}</h5>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>
    <!-- ****** EXISTING Notice Board 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="addNoticeBoardDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addNoticeBoardDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Notice Board
      </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="notices"
      :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="td td-row text-xs-center">
            <v-avatar size="40">
              <img :src="props.item.eventImageUrl" v-if="props.item.eventImageUrl" />
              <img src="/static/icon/user.png" v-else-if="!props.item.eventImageUrl" />
            </v-avatar>
          </td>
          <td class="text-xs-center td td-row">{{ props.item.title}}</td>
          <td class="text-xs-center td td-row">
            <v-btn
              class="add-button"
              @click="generatePDF2Canvas(props.item)"
              :loading="loadingPdf"
              dark
            >{{ props.item.fileType }}</v-btn>
          </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"
                />
                <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  Notice Board ****** -->
    <v-dialog v-model="addNoticeBoardDialog" max-width="600px" v-if="addNoticeBoardDialog" persistent>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Notice Board</label>
            <v-icon size="24" class="right" @click="closeNoticeBoardModel">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 xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
                    <v-avatar size="80px" v-if="!imageUrl">
                      <img src="/static/icon/user.png" />
                    </v-avatar>
                    <input
                      type="file"
                      style="display: none"
                      ref="image"
                      accept="image/*"
                      @change="onFilePicked"
                    />

                    <v-avatar size="150px" v-if="imageUrl">
                      <img :src="imageUrl" height="150" />
                    </v-avatar>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 class="pt-4 subheading">
                    <label class="right">Title:</label>
                  </v-flex>
                  <v-flex xs7 class="ml-3">
                    <v-text-field
                      v-model="addNoticeBoard.title"
                      placeholder="fill your Title"
                      name="name"
                      type="text"
                      :rules="titleRules"
                      required
                    ></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 class="pt-4 subheading">
                    <label class="right">Description:</label>
                  </v-flex>
                  <v-flex xs7 class="ml-3">
                    <v-text-field
                      v-model="addNoticeBoard.description"
                      placeholder="fill your Description"
                      name="name"
                      type="text"
                      :rules="descriptionRules"
                      required
                    ></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs4 class="pt-4 subheading">
                    <label class="right hidden-xs-only hidden-sm-only">Uplaod Image:</label>
                    <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Uplaod :</label>
                  </v-flex>
                  <v-flex xs7 class="ml-3">
                    <v-text-field
                      label="Select Image"
                      @click="pickFile"
                      v-model="imageName"
                      append-icon="attach_file"
                    ></v-text-field>
                    <input
                      type="file"
                      style="display:none"
                      ref="image"
                      accept="image/*"
                      @change="onFilePicked"
                    />
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs12>
                    <v-card-actions>
                      <v-spacer></v-spacer>
                      <v-btn @click="clear" round dark class="clear-button">clear</v-btn>
                      <v-btn @click="submit" round dark :loading="loading" class="add-button">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";

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: "",
    addNoticeBoardDialog: false,
    editNoticeBoardDialog: false,
    viewNoticeBoardDialog: false,
    valid: true,
    addclass: [],
    addSection: [],
    gender: ["Male", "Female"],
    pagination: {
      rowsPerPage: 10,
    },
    imageName: "",
    imageUrl: "",
    imageFile: "",
    upload: "",
    loadingPdf: false,

    titleRules: [(v) => !!v || " Title is required"],
    descriptionRules: [(v) => !!v || " Description is required"],
    headers: [
      {
        text: "No",
        align: "",
        sortable: false,
        value: "No",
      },
      {
        text: "Event Image",
        align: "center",
        sortable: false,
        value: "eventImageUrl",
      },
      { text: "Title", value: "title", sortable: false, align: "center" },
      {
        text: "File",
        value: "eventImageUrl",
        sortable: false,
        align: "center",
      },
      { text: "Action", value: "", sortable: false, align: "center" },
    ],
    notices: [],
    editedIndex: -1,
    addNoticeBoard: {},
    editedItem: {
      title: "",
      description: "",
    },
  }),
  watch: {
    addNoticeBoardDialog: function (val) {
      if (!val) {
        this.addNoticeBoard = [];
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
  },
  methods: {
    pickFile() {
      this.$refs.image.click();
    },
    getNoticeDataList() {
      this.showLoader = true;
      var token = this.$store.state.token;
      http()
        .get("/getEventsList", {
          headers: { Authorization: "Bearer " + token },
        })
        .then((response) => {
          this.notices = response.data.data;
          this.showLoader = false;
        })
        .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.notices.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editNoticeBoardDialog = true;
    },
    profile(item) {
      this.editedIndex = this.notices.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.viewNoticeBoardDialog = true;
    },
    deleteItem(item) {
      let deleteEvent = {
        eventId: item._id,
      };
      http()
        .delete(
          "/deleteEvent",
          confirm("Are you sure you want to delete this?") && {
            params: deleteEvent,
          }
        )
        .then((response) => {
          // console.log("deleteUers",deleteEvent)
          if ((this.snackbar = true)) {
            this.text = "Successfully delete Existing Notice Data";
          }
          this.snackbar = true;
          this.color = "green";
          this.getNoticeDataList();
        })
        .catch((error) => {
          // console.log(error);
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    close() {
      this.editNoticeBoardDialog = false;
    },
    closeNoticeBoardModel() {
      this.addNoticeBoardDialog = false;
      this.addNoticeBoard = [];
      this.imageName = "";
      this.imageFile = "";
      this.imageUrl = "";
    },
    submit() {
      var signatures = {
        JVBERi0: "other",
        iVBORw0KGgo: "image",
        UEsDBBQ: "other",
        "/": "image",
        AAABAA: "image",
        IywiV2hhdC: "other",
        bmFtZSxl: "other",
      };
      function detectMimeType(b64) {
        for (var s in signatures) {
          if (b64.indexOf(s) === 0) {
            return signatures[s];
          }
        }
      }
      if (this.$refs.form.validate()) {
        if (this.imageUrl) {
          var str = this.imageUrl;
          const [baseUrl, imageUrl] = str.split(/,/);
          this.addNoticeBoard.upload = imageUrl;
          this.addNoticeBoard.fileType = detectMimeType(imageUrl);
          this.addNoticeBoard.fileName = this.imageName;
        }
        http()
          .post("/createEvent", this.addNoticeBoard)
          .then((response) => {
            this.imageUrl = "";
            this.snackbar = true;
            this.color = "green";
            this.text = response.data.message;
            this.getNoticeDataList();
            this.addNoticeBoardDialog = false;
            this.clear();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "error";
          });
      }
    },
    onFilePicked(e) {
      const files = e.target.files;
      this.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 = "";
      }
    },
    clear() {
      this.$refs.form.reset();
      this.imageUrl = "";
    },
    save() {
      let editNoticeBoard = {
        eventId: this.editedItem._id,
        title: this.editedItem.title,
        description: this.editedItem.description,
        fileName: this.imageName,
      };
      var signatures = {
        JVBERi0: "other",
        iVBORw0KGgo: "image",
        UEsDBBQ: "other",
        "/": "image",
        AAABAA: "image",
        IywiV2hhdC: "other",
      };
      function detectMimeType(b64) {
        for (var s in signatures) {
          if (b64.indexOf(s) === 0) {
            return signatures[s];
          }
        }
      }
      if (this.imageUrl) {
        var str = this.imageUrl;
        const [baseUrl, imageUrl] = str.split(/,/);
        editNoticeBoard.upload = imageUrl;
        editNoticeBoard.fileType = detectMimeType(imageUrl);
      }
      http()
        .put("/updateEvent", editNoticeBoard)
        .then((response) => {
          if ((this.snackbar = true)) {
            this.text = "Successfully Edit Existing Notice Data";
          }
          this.color = "green";
          this.snackbar = true;
          this.getNoticeDataList();
          this.close();
        })
        .catch((error) => {
          // console.log(error);
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "red";
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
    async generatePDF2Canvas(item) {
      var dataType = "";
      var type = "";
      if (item.fileType == "image") {
        dataType = "file.jpg";
      } else if (item.fileType == "other") {
        dataType = "file.pdf";
        type = "application/pdf";
      }
      var FileSaver = require("file-saver");
      FileSaver.saveAs(item.eventImageUrl, "image.jpg");
    },
  },
  mounted() {
    this.getNoticeDataList();
  },
};
</script>