<template>
  <v-app id="pages-dasboard">
    <v-tabs grow slider-color="black">
      <v-tab
        ripple
        @click="activeTab('existing')"
        v-bind:class="{ active: isActive }"
        id="tab"
        class="subheading"
      >Existing News</v-tab>
      <v-tab
        ripple
        @click="activeTab('new')"
        v-bind:class="{ active: newActive }"
        id="tab1"
        User
        class="subheading"
      >Add News</v-tab>

      <!-- ****** EDITS ALL NEWS DETAILS ****** -->

      <v-tab-item>
        <v-snackbar
          :timeout="timeout"
          :top="y === 'top'"
          :right="x === 'right'"
          :vertical="mode === 'vertical'"
          v-model="snackbar"
          color="success"
        >{{ text }}</v-snackbar>
        <v-dialog v-model="dialog" max-width="1000px" scrollable>
          <v-card flat>
            <v-toolbar class="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>Edit News</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
            </v-toolbar>
            <v-card-text style="height:600px;">
              <v-form ref="form">
                <v-container fluid>
                  <v-layout row>
                    <v-flex
                      xs12
                      class="text-xs-center text-sm-center text-md-center text-lg-center my-4 mr-4"
                    >
                      <input
                        type="file"
                        style="display: none"
                        ref="image"
                        accept="image/*"
                        multiple
                        @change="onFilePicked"
                      />
                      <v-layout justify-center>
                        <v-flex
                          xs3
                          v-for="Image in editedItem.newsImageUrl"
                          :key="Image._id"
                          v-if="editedItem.newsImageUrl"
                          class="profile-image-wrapper"
                        >
                          <img
                            :src="Image.imageUrl"
                            height="160"
                            width="160"
                            alt="News"
                            class="pa-2"
                          />
                          <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="160" width="160" class="pa-2" />
                        </v-flex>
                      </v-layout>
                      <img
                        src="/static/icon/user.png"
                        v-if="editedItem.newsImageUrl ==''"
                        height="160"
                        width="160"
                        alt="News"
                      />
                    </v-flex>
                  </v-layout>
                  <!-- </v-layout> -->
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Title:</label>
                        </v-flex>
                        <v-flex xs5 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 xs5 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">Add New Images:</label>
                        </v-flex>
                        <v-flex xs5 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 sm8 offset-sm2>
                      <v-card-actions>
                        <v-btn round dark @click.native="close">Cancel</v-btn>
                        <v-spacer></v-spacer>
                        <v-btn round dark @click="save">Save</v-btn>
                      </v-card-actions>
                    </v-flex>
                  </v-layout>
                </v-container>
              </v-form>
            </v-card-text>
          </v-card>
        </v-dialog>

        <!-- ****** PROFILE VIEW ALL NEWS DEATILS ******  -->

        <v-dialog v-model="dialog1" max-width="800px">
          <v-card>
            <v-toolbar color="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>News</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
              <v-icon @click="close1">close</v-icon>
            </v-toolbar>
            <v-flex align-center justify-center layout text-xs-center>
              <!-- <v-avatar size="50px" style="position:absolute; top:20px;">
                <img src="/static/icon/user.png">
              </v-avatar>-->
              <span v-for="(image,i) in editedItem.newsImageUrl" :key="i" class="mt-4 pa-2">
                <img :src="image.imageUrl" alt="News" width="240" height="180" />
              </span>
            </v-flex>
            <v-card-text>
              <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>

        <v-snackbar
          :timeout="timeout"
          :top="y === 'top'"
          :right="x === 'right'"
          :vertical="mode === 'vertical'"
          v-model="snackbar"
          color="success"
        >{{ text }}</v-snackbar>

        <!-- ****** EXISTING-USERS NEWS TABLE ****** -->
        <v-data-table
          :headers="headers"
          :items="desserts"
          :pagination.sync="pagination"
          :search="search"
        >
          <template slot="items" slot-scope="props">
            <td class="text-xs-center">{{ props.index}}</td>
            <td id="td" class="text-xs-center">
              <span v-for="(image,_id) in props.item.newsImageUrl" class="pa-2">
                <img :src="image.imageUrl" alt="newsImage" width="100" height="70" />
              </span>
            </td>
            <td id="td" class="text-xs-center">{{ props.item.title}}</td>
            <td id="td" class="text-xs-center">{{ props.item.description}}</td>

            <td class="text-xs-center">
              <span>
                <img
                  style="cursor:pointer; width:25px; height:18px; "
                  class="mr-5"
                  @click="profile(props.item)"
                  src="/static/icon/eye1.png"
                />
                <img
                  style="cursor:pointer; width:20px; height:18px; "
                  class="mr-5"
                  @click="editItem(props.item)"
                  src="/static/icon/edit1.png"
                />
                <img
                  style="cursor:pointer;width:20px; height:20px; "
                  class="mr-5"
                  @click="deleteItem(props.item)"
                  src="/static/icon/delete1.png"
                />
              </span>
            </td>
          </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-tab-item>

      <!-- ****** ADD MULTIPLE NEWS ****** -->

      <v-tab-item>
        <v-container>
          <v-snackbar
            :timeout="timeout"
            :top="y === 'top'"
            :right="x === 'right'"
            :vertical="mode === 'vertical'"
            v-model="snackbar"
            color="success"
          >{{ text }}</v-snackbar>
          <v-flex xs12 sm12 class="my-4">
            <v-card flat>
              <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 mr-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="160" width="160px;" />
                        </v-flex>
                      </v-layout>
                      <img
                        src="/static/icon/user.png"
                        v-if="files ==''"
                        height="140"
                        width="180px;"
                      />
                    </v-flex>
                  </v-layout>
                  <v-flex xs12>
                    <v-layout>
                      <v-flex xs4 class="pt-4 subheading">
                        <label class="right">Title:</label>
                      </v-flex>
                      <v-flex xs4 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 xs4 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">Uplaod Image:</label>
                      </v-flex>
                      <v-flex xs4 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 xs12 sm6 offset-sm3>
                      <v-card-actions>
                        <v-btn @click="clear" round dark>clear</v-btn>
                        <v-spacer></v-spacer>
                        <v-btn @click="submit" round dark :loading="loading">Add</v-btn>
                      </v-card-actions>
                    </v-flex>
                  </v-layout>
                </v-container>
              </v-form>
            </v-card>
          </v-flex>
        </v-container>
      </v-tab-item>
    </v-tabs>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
  </v-app>
</template>

<script>
import http from "@/Services/http.js";
import Util from "@/util";

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    loading: false,
    date: null,
    search: "",
    showLoader: false,
    dialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    addclass: [],
    addSection: [],
    AddUsercredentials: {},
    pagination: {
      rowsPerPage: 15
    },
    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: ""
    },
  }),
  methods: {
    getSections(_id) {
      console.log("_id", _id);
      var token = this.$store.state.token;
      http()
        .get(
          "/getSectionsList",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + token }
          }
        )
        .then(response => {
          this.addSection = response.data.data;
          // console.log("getSectionsList=====>", this.addSection);
        })
        .catch(err => {
          console.log("err====>", err);
          // this.$router.replace({ path: '/' });
        });
    },
    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;
          // console.log("getNewsList=====>",this.desserts)
        })
        .catch(err => {
          // console.log("err====>", err);
          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.dialog = 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 => {
          // console.log("deleteNews",deleteNews)
          if ((this.snackbar = true)) {
            this.text = "Successfully delete Existing News";
          }
          this.getNewsList();
        })
        .catch(error => {
          // console.log(error);
        });
    },
    deleteImage(imageId, newsId) {
      console.log(imageId, newsId);
      let deleteImages = {
        newsId: newsId,
        imageId: imageId
      };
      http()
        .put("/deleteImages", deleteImages)
        .then(response => {
          console.log("deleteNews", deleteImages);
          if ((this.snackbar = true)) {
            this.text = "Image deleted Successfully";
          }
          this.getNewsList();
          this.close();
        })
        .catch(error => {
          console.log(error);
        });
    },
    activeTab(type) {
      switch (type) {
        case "existing":
          this.newActive = false;
          this.isActive = true;
          break;

        default:
          this.newActive = true;
          this.isActive = false;
          break;
      }
    },
    close() {
      this.dialog = false;
      setTimeout(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      }, 300);
    },
    close1() {
      this.dialog1 = false;
    },
    submit() {
      this.loading = true;
      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;
          }
        }
        http()
          .post("/createNews", newsData)
          .then(response => {
            console.log(newsData);
            if ((this.snackbar = true)) {
              this.text = "New News added successfully";
            }
            this.getNewsList();
            this.loading = false;
            this.clear();
          })
          .catch(error => {
            if ((this.snackbar = true)) {
              this.text = error.response.data.message;
            }
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    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 => {
          // console.log("updateNews",updateNews);
          if ((this.snackbar = true)) {
            this.text = "Successfully Edit Existing News";
          }
          this.getNewsList();
          this.close();
        })
        .catch(error => {
          // console.log(error);
        });
    },
  },
  mounted() {
    this.getNewsList();
    this.editItem;
  },
  created() {
    this.$root.$on("app:search", search => {
      this.search = search;
    });
  },
  beforeDestroy() {
    // dont forget to remove the listener
    this.$root.$off("app:search");
  }
};
</script>
<style scoped>
.active {
  background-color: black;
  color: white !important;
}
.activebtn {
  color: black !important;
}
</style>