<template>
  <v-container fluid class="body-color">
    <!-- ****** EDIT NEWS  ****** -->
    <v-dialog v-model="editNewsDialog" max-width="600px" persistent>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit News</label>
            <v-icon size="24" class="right" @click="editNewsDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-layout row>
            <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center my-4">
              <input
                type="file"
                style="display: none"
                ref="image"
                accept="image/*"
                multiple
                @change="onFilePicked"
              />
              <v-layout justify-center>
                <v-flex
                  xs12
                  sm12
                  md3
                  v-for="Image in editedItem.newsImageUrl"
                  :key="Image._id"
                  v-if="editedItem.newsImageUrl"
                  class="profile-image-wrapper"
                >
                  <img
                    :src="Image.imageUrl"
                    height="100"
                    width="100"
                    alt="News"
                    class="pa-2 imgNews"
                  />
                  <v-icon
                    class="red edit-profile-icon"
                    dark
                    @click="deleteImage(Image._id,editedItem._id)"
                  >close</v-icon>
                </v-flex>
                <v-flex v-for="(file, index) in files" :key="index">
                  <img :src="file" height="100" width="100" class="pa-2" />
                </v-flex>
                <img
                  src="/static/icon/user.png"
                  v-if="files == '' && editedItem.newsImageUrl == ''"
                  height="100"
                  width="100"
                  alt="News"
                />
              </v-layout>
            </v-flex>
          </v-layout>
          <!-- </v-layout> -->
          <v-layout wrap>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Title:</label>
                </v-flex>
                <v-flex sm6 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 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Description:</label>
                </v-flex>
                <v-flex sm6 xs8 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">Add New Images:</label>
                  <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Uplaod :</label>
                </v-flex>
                <v-flex sm6 xs8 class="ml-3">
                  <v-text-field
                    label="Select Image"
                    @click="pickFile"
                    v-model="imageName"
                    append-icon="attach_file"
                    multiple
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
          </v-layout>
          <v-layout>
            <v-flex xs12 sm9 offset-sm2 class="hidden-xs-only hidden-sm-only">
              <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-flex xs12 class="hidden-lg-only hidden-md-only hidden-xl-only">
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn round dark @click="save" class="add-button">Save</v-btn>
                <v-spacer></v-spacer>
              </v-card-actions>
            </v-flex>
          </v-layout>
        </v-card-text>
      </v-card>
    </v-dialog>
    <!-- ****** PROFILE  NEWS  ******  -->
    <v-dialog v-model="dialog1" max-width="500px" persistent>
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View News</label>
            <v-icon size="24" class="right" @click="dialog1 = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-flex align-center justify-center layout text-xs-center>
            <span v-for="(image,i) in editedItem.newsImageUrl" :key="i" class="pa-2">
              <img :src="image.imageUrl" alt="News" width="100" height="100" class="imgNews" />
            </span>
            <img
              src="/static/icon/user.png"
              v-if="editedItem.newsImageUrl == ''"
              height="80"
              width="80"
              alt="News"
            />
          </v-flex>
          <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-USERS NEWS 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="addNewsDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addNewsDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add News
      </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="desserts"
      :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">
            <span v-for="(image,_id) in props.item.newsImageUrl" class="pa-2">
              <img :src="image.imageUrl" alt="newsImage" width="40" height="40" />
            </span>
            <img
              src="/static/icon/user.png"
              v-if="props.item.newsImageUrl == ''"
              width="40"
              alt="News"
            />
          </td>
          <td class="td td-row text-xs-center">{{ props.item.title}}</td>
          <td class="td td-row text-xs-center">{{ props.item.description}}</td>

          <td class="td td-row text-xs-center">
            <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  NEWS ****** -->
    <v-dialog v-model="addNewsDialog" max-width="600px" v-if="addNewsDialog" persistent>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add News</label>
            <v-icon size="24" class="right" @click="closeAddNewsModel">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-form ref="form" v-model="valid" lazy-validation>
          <v-container fluid>
            <v-layout>
              <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center my-4">
                <input
                  type="file"
                  style="display: none"
                  ref="image"
                  accept="image/*"
                  multiple
                  @change="onFilePicked"
                />
                <v-layout justify-center>
                  <v-flex v-for="(file,index) in files" :key="index" v-if="files">
                    <img :src="file" height="100" width="100;" class="imgNews" />
                  </v-flex>
                </v-layout>
                <img src="/static/icon/user.png" v-if="files ==''" height="80" width="80" />
              </v-flex>
            </v-layout>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 sm4 class="pt-4 subheading">
                  <label class="right">Title:</label>
                </v-flex>
                <v-flex sm6 xs8 class="ml-3">
                  <v-text-field
                    v-model="addNews.title"
                    placeholder="fill your Title"
                    name="name"
                    type="text"
                    :rules="titleRules"
                    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 sm6 xs8 class="ml-3">
                  <v-text-field
                    placeholder="fill your Description"
                    :rules="descriptionRules"
                    v-model="addNews.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 xs8 sm6 class="ml-3">
                  <v-text-field
                    label="Select Image"
                    @click="pickFile"
                    v-model="imageName"
                    append-icon="attach_file"
                    multiple
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-layout>
              <v-flex xs11>
                <v-layout>
                  <v-spacer></v-spacer>
                  <v-btn @click="clear" round class="clear-button" dark>clear</v-btn>
                  <v-btn @click="submit" round dark :loading="loading" class="add-button">Add</v-btn>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-form>
      </v-card>
    </v-dialog>
    <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: 5000,
    color: "",
    text: "",
    loading: false,
    date: null,
    search: "",
    show: true,
    showSearch: false,
    showLoader: false,
    editNewsDialog: false,
    addNewsDialog: false,
    dialog1: false,
    valid: true,
    addclass: [],
    addSection: [],
    pagination: {
      rowsPerPage: 10,
    },
    imageName: "",
    imageUrl: "",
    imageFile: "",
    image: [],
    upload: "",
    files: [],
    titleRules: [(v) => !!v || " Tilte is required"],
    descriptionRules: [(v) => !!v || " Description is required"],
    headers: [
      {
        align: "justify-center",
        text: "No",
        sortable: false,
        value: "No",
      },
      { text: "Image", vaue: "image", sortable: false, align: "center" },
      { text: "Title", value: "title", sortable: false, align: "center" },
      {
        text: "Description",
        value: "description",
        sortable: false,
        align: "center",
      },
      { text: "Action", value: "", sortable: false, align: "center" },
    ],
    desserts: [],
    editedIndex: -1,
    addNews: {
      title: "",
      description: "",
    },
    editedItem: {
      title: "",
      description: "",
    },
    defaultItem: {
      title: "",
      description: "",
    },
  }),
  watch: {
    addNewsDialog: function (val) {
      if (!val) {
        this.addNews = [];
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
        this.files = [];
      }
    },
  },
  methods: {
    getSections(_id) {
      var token = this.$store.state.token;
      http()
        .get(
          "/getSectionsList",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + token },
          }
        )
        .then((response) => {
          this.addSection = response.data.data;
        })
        .catch((err) => {
          console.log("err====>", err);
        });
    },
    pickFile() {
      this.$refs.image.click();
    },
    onFilePicked(e) {
      // console.log(e)
      const files = e.target.files;
      /** fetch Image Name **/
      if (files[0] !== undefined) {
        this.imageName = files[0].name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        this.files = [];
        // console.log("files", this.files);
        /** Select many image and showing many image add to news card **/
        const test = Array.from(files).forEach((file, idx) => {
          const fr = new FileReader();
          const getResult = new Promise((resolve) => {
            fr.onload = (e) => {
              this.files.push(
                // id: idx,
                e.target.result
              );
            };
          });
          fr.readAsDataURL(file);
          return getResult.then((file) => {
            return file;
          });
        });
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.imageFile = files; // this is an image file that can be sent to server...
          // console.log("uploadImage=======>", this.imageFile );
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
    getNewsList() {
      this.showLoader = true;
      var token = this.$store.state.token;
      http()
        .get("/getNewsList", {
          headers: { Authorization: "Bearer " + token },
        })
        .then((response) => {
          this.desserts = 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.files = [];
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editNewsDialog = true;
    },
    profile(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
    },
    deleteItem(item) {
      let deleteNews = {
        newsId: item._id,
      };
      http()
        .delete(
          "/deleteNews",
          confirm("Are you sure you want to delete this?") && {
            params: deleteNews,
          }
        )
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.getNewsList();
        })
        .catch((error) => {
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    deleteImage(imageId, newsId) {
      let deleteImages = {
        newsId: newsId,
        imageId: imageId,
      };
      http()
        .put("/deleteImages", deleteImages)
        .then((response) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.close();
        })
        .catch((error) => {
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    close() {
      this.dialog = false;
    },
    close1() {
      this.dialog1 = false;
    },
    closeAddNewsModel() {
      this.addNewsDialog = false;
      this.addNews = [];
      this.imageName = "";
      this.imageFile = "";
      this.imageUrl = "";
      this.files = [];
    },
    submit() {
      if (this.$refs.form.validate()) {
        let newsData = {
          title: this.addNews.title,
          description: this.addNews.description,
        };
        if (this.files) {
          var ary = [];
          var imageData = [];
          ary = this.files;
          for (let i = 0; i < ary.length; i++) {
            const [baseUrl, imageUrl] = ary[i].split(/,/);
            imageData.push(imageUrl);
            newsData.upload = imageData;
          }
        }
        this.loading = true;
        http()
          .post("/createNews", newsData)
          .then((response) => {
            this.files = [];
            this.snackbar = true;
            this.text = response.data.message;
            this.getNewsList();
            this.color = "green";
            this.addNewsDialog = false;
            this.loading = false;
            this.clear();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.color = "error";
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.files = [];
    },
    save() {
      let editNews = {
        title: this.editedItem.title,
        description: this.editedItem.description,
        newsId: this.editedItem._id,
      };
      if (this.files) {
        var ary = [];
        var imageData = [];
        ary = this.files;
        for (let i = 0; i < ary.length; i++) {
          const [baseUrl, imageUrl] = ary[i].split(/,/);
          imageData.push(imageUrl);
          editNews.upload = imageData;
        }
      }
      http()
        .put("/updateNews", editNews)
        .then((response) => {
          this.snackbar = true;
          this.text = "Successfully updated News";
          this.color = "green";
          this.editNewsDialog = false;
          this.getNewsList();
          this.close();
        })
        .catch((error) => {
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    this.getNewsList();
    this.editItem;
  },
};
</script>