<template>
  <v-app id="pages-dasboard">
    <v-tabs grow slider-color="gray">
      <v-tab
        ripple
        @click="activeTab('existing')"
        v-bind:class="{ active: isActive }"
        id="tab"
        class="subheading"
      >Existing Expense</v-tab>
      <v-tab
        ripple
        @click="activeTab('new')"
        v-bind:class="{ active: newActive }"
        id="tab1"
        User
        class="subheading"
      >Add New Expense</v-tab>
      <!-- ****** EDIT EXPENSE 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="600px" scrollable>
          <v-card flat>
            <v-toolbar color="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>Edit Expense Profile</v-toolbar-title>
              <v-spacer></v-spacer>
            </v-toolbar>
            <v-card-text style="height: 600px;">
              <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 my-4 mr-4"
                    >
                      <v-avatar size="160px">
                        <img src="/static/icon/user.png" v-if="!editedItem.fileUrl && !imageUrl" />
                        <img :src="editedItem.fileUrl" v-else-if="editedItem.fileUrl && !imageUrl" />
                        <img
                          v-if="imageUrl"
                          :src="imageUrl"
                          height="150"
                          style="border-radius:50%; width:200px"
                        />
                      </v-avatar>
                      <input
                        type="file"
                        style="display:none"
                        ref="image"
                        accept="image/*"
                        @change="onFilePicked"
                      />
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Name:</label>
                        </v-flex>
                        <v-flex xs6 class="ml-3">
                          <v-text-field
                            v-model="editedItem.name"
                            placeholder="fill your full Name"
                            name="name"
                            type="text"
                            required
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Date:</label>
                        </v-flex>
                        <v-flex xs6 class="ml-3">
                          <v-menu
                            ref="menu"
                            :close-on-content-click="false"
                            v-model="menu3"
                            :nudge-right="40"
                            lazy
                            transition="scale-transition"
                            offset-y
                            full-width
                            min-width="290px"
                          >
                            <v-text-field
                              slot="activator"
                              v-model="editedItem.date"
                              placeholder="Select date"
                            ></v-text-field>
                            <v-date-picker
                              ref="picker"
                              v-model="editedItem.date"
                              @input="$refs.menu.save(editedItem.date)"
                            ></v-date-picker>
                          </v-menu>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <v-layout>
                      <v-flex xs12 sm12>
                        <v-layout>
                          <v-flex xs4 class="pt-4 subheading">
                            <label class="right">Amount:</label>
                          </v-flex>
                          <v-flex xs6 class="ml-3">
                            <v-text-field v-model="editedItem.amount" required></v-text-field>
                          </v-flex>
                        </v-layout>
                      </v-flex>
                    </v-layout>
                    <v-flex xs12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Uplaod Image:</label>
                        </v-flex>
                        <v-flex xs6 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-flex xs12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Note:</label>
                        </v-flex>
                        <v-flex xs6 class="ml-3">
                          <v-textarea
                            name="input-7-1"
                            v-model="editedItem.note"
                            placeholder="fill your Note"
                            type="text"
                            :rules="noteRules"
                            multi-line
                            required
                          ></v-textarea>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-card-actions>
                        <v-btn round dark @click.native="close">Cancel</v-btn>
                        <v-spacer></v-spacer>
                        <v-btn round dark :loading="loading" @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 TEACHERS DETAILS ******  -->

        <v-dialog v-model="dialog1" max-width="600px" scrollable>
          <v-card>
            <v-toolbar color="grey lighten-2" flat>
              <v-spacer></v-spacer>
              <v-toolbar-title>
                <h3>Expense Profile</h3>
              </v-toolbar-title>
              <v-spacer></v-spacer>
              <v-icon @click="close1">close</v-icon>
            </v-toolbar>
            <v-card-text style="height: 460px;">
              <v-container grid-list-md>
                <v-layout wrap>
                  <v-flex>
                    <v-flex align-center justify-center layout text-xs-center>
                      <v-avatar size="160px">
                        <img src="/static/icon/user.png" v-if="!editedItem.fileUrl" />
                        <img :src="editedItem.fileUrl" v-else-if="editedItem.fileUrl" />
                      </v-avatar>
                    </v-flex>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Name:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ editedItem.name }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Amount:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ editedItem.amount }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Date:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ dates(editedItem.date) }}</h5>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs5 sm6>
                        <h5 class="right my-1">
                          <b>Note:</b>
                        </h5>
                      </v-flex>
                      <v-flex sm6 xs8>
                        <h5 class="my-1">{{ editedItem.note }}</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-EXPENSE TABLE DATA****** -->

        <v-data-table
          :headers="headers"
          :items="expenseList"
          :pagination.sync="pagination"
          :search="search"
        >
          <template slot="items" slot-scope="props">
            <td id="td" class="text-xs-center">{{ props.index + 1}}</td>
            <td id="td" class="text-xs-center">
              <v-avatar>
                <img :src="props.item.fileUrl" v-if="props.item.fileUrl" />
                <img src="/static/icon/user.png" v-else-if="!props.item.fileUrl" />
              </v-avatar>
            </td>
            <td id="td" class="text-xs-center">{{ props.item.name}}</td>
            <td id="td" class="text-xs-center">{{ dates(props.item.date) }}</td>
            <td id="td" class="text-xs-center">{{ props.item.user }}</td>
            <td id="td" class="text-xs-center">{{ props.item.amount }}</td>
            <td id="td" class="text-xs-center">{{ props.item.note }}</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 Expense Data****** -->
      <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"
                    >
                      <v-avatar size="100px">
                        <img src="/static/icon/user.png" v-if="!imageUrl" />
                      </v-avatar>
                      <img
                        :src="imageUrl"
                        height="150"
                        v-if="imageUrl"
                        style="border-radius:50%; width:200px"
                      />
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Name:</label>
                        </v-flex>
                        <v-flex xs8 sm4 class="ml-3">
                          <v-text-field
                            v-model="addExpense.name"
                            placeholder="fill your full Name"
                            name="name"
                            type="text"
                            :rules="nameRules"
                            required
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Amount:</label>
                        </v-flex>
                        <v-flex xs8 sm4 class="ml-3">
                          <v-text-field
                            v-model="addExpense.amount"
                            placeholder="fill your Amount"
                            name="name"
                            type="text"
                            :rules="amountRules"
                            required
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">Date</label>
                        </v-flex>
                        <v-flex xs8 sm4 class="ml-3">
                          <v-menu
                            ref="menu1"
                            :close-on-content-click="false"
                            v-model="menu1"
                            :nudge-right="40"
                            lazy
                            transition="scale-transition"
                            offset-y
                            full-width
                            min-width="290px"
                          >
                            <v-text-field
                              slot="activator"
                              :rules="joinDateRules"
                              v-model="addExpense.date"
                              placeholder="Select date"
                            ></v-text-field>
                            <v-date-picker
                              ref="picker"
                              v-model="addExpense.date"
                              @input="$refs.menu1.save(addExpense.date)"
                            ></v-date-picker>
                          </v-menu>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right">File:</label>
                        </v-flex>
                        <v-flex xs8 sm4 class="ml-3">
                          <v-text-field
                            label="Select file"
                            @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-layout>
                      <v-flex xs12 sm12>
                        <v-layout>
                          <v-flex xs4 class="pt-4 subheading">
                            <label class="right">Note:</label>
                          </v-flex>
                          <v-flex xs8 sm4 class="ml-3">
                            <v-textarea
                              name="input-7-1"
                              v-model="addExpense.note"
                              placeholder="fill your Note"
                              type="text"
                              :rules="noteRules"
                              multi-line
                              required
                            ></v-textarea>
                          </v-flex>
                        </v-layout>
                      </v-flex>
                    </v-layout>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-card-actions>
                        <v-flex xs12 sm5>
                          <v-btn @click="clear" class="right" round dark>clear</v-btn>
                        </v-flex>
                        <v-spacer></v-spacer>
                        <v-flex xs12 sm5>
                          <v-btn @click="submit" round dark :loading="loading">Add</v-btn>
                        </v-flex>
                      </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";
import moment from "moment";

export default {
  data: () => ({
    component: "report-generate",
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    menu: false,
    menu1: false,
    menu2: false,
    menu3: false,
    dialog: false,
    dialog1: false,
    valid: true,
    isActive: true,
    newActive: false,
    pagination: {
      rowsPerPage: 15
    },
    imageData: {},
    imageName: "",
    imageUrl: "",
    imageFile: "",
    nameRules: [v => !!v || " Full Name is required"],
    amountRules: [v => !!v || "Amount is required"],
    noteRules: [v => !!v || "Note Name is required"],
    joinDateRules: [v => !!v || "Date is required"],
    errorMessages: "",
    headers: [
      {
        text: "No",
        align: "center",
        sortable: false,
        value: "No"
      },
      {
        text: "Profile Pic",
        value: "profilePicUrl",
        sortable: false,
        align: "center"
      },
      { text: "Name", value: "name", sortable: false, align: "center" },
      { text: "Date", value: "date", sortable: false, align: "center" },
      { text: "User", value: "user", sortable: false, align: "center" },
      { text: "Amount", value: "amount", sortable: false, align: "center" },
      { text: "Note", value: "note", sortable: false, align: "center" },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    expenseList: [],
    editedIndex: -1,
    upload: "",
    editedItem: {
      role: "TEACHER",
      name: "",
      email: "",
      date: null,
      city: "",
      pincode: "",
      country: "",
      permanentAddress: "",
      presentAddress: "",
      mobileNo: "",
      state: "",
      joinDate: null
    },
    addExpense: {},
    defaultItem: {
      role: "TEACHER",
      name: "",
      email: ""
    }
  }),
  watch: {
    menu(val) {
      val && this.$nextTick(() => (this.$refs.picker.activePicker = "YEAR"));
    },
    menu1(val) {
      val && this.$nextTick(() => (this.$refs.picker.activePicker = "YEAR"));
    }
  },
  methods: {
    save(date) {
      this.$refs.menu.save(date);
    },
    save(date) {
      this.$refs.menu1.save(date);
    },
    pickFile() {
      this.$refs.image.click();
    },
    onFilePicked(e) {
      // console.log(e)
      const files = e.target.files;
      this.upload = e.target.files[0];
      console.log("imageData-upload========>", this.upload);
      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);
          // console.log("upload=======>", this.imageData.imageUrl);
          console.log("imageFile", this.imageUrl);
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    getExpenseList() {
      this.showLoader = true;
      var token = this.$store.state.token;
      http()
        .get("/getExpensesList", {
          headers: { Authorization: "Bearer " + token }
        })
        .then(response => {
          this.expenseList = response.data.data;
          this.showLoader = false;
          // console.log("getTeacherList=====>",this.expenseList)
        })
        .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.expenseList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      //   this.editedItem.dob =
      //     this.editedItem.dob != undefined
      //       ? (this.editedItem.dob = this.editedItem.dob.substring(0, 10))
      //       : (this.editedItem.dob = "");
      this.editedItem.date =
        this.editedItem.date != undefined
          ? (this.editedItem.date = this.editedItem.date.substring(0, 10))
          : (this.editedItem.date = "");

      this.dialog = true;
    },
    profile(item) {
      this.editedIndex = this.expenseList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
    },
    deleteItem(item) {
      let deleteExpense = {
        expenseId: item._id
      };
      //  console.log("deleteUers",deleteTeachers)
      http()
        .delete(
          "/deleteExpense",
          confirm("Are you sure you want to delete this?") && {
            params: deleteExpense
          }
        )
        .then(response => {
          // console.log("deleteUers",deleteTeachers)
          if ((this.snackbar = true)) {
            this.text = "Successfully delete Existing Expense";
          }
          this.getExpenseList();
        })
        .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() {
      if (this.$refs.form.validate()) {
        if (this.imageUrl) {
          var str = this.imageUrl;
          const [baseUrl, imageUrl] = str.split(/,/);
          this.addExpense.upload = imageUrl;
        }
        this.loading = true;
        http()
          .post("/createExpense", this.addExpense)
          .then(response => {
            this.getExpenseList();
            if ((this.snackbar = true)) {
              this.text = "New Expense added successfully";
            }

            this.clear();
            this.loading = false;
          })
          .catch(error => {
            // console.log(error);
            if ((this.snackbar = true)) {
              this.text = error.response.data.message;
            }
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    save() {
      this.loading = true;
      this.editedItem.expenseId = this.editedItem._id;
      if (this.imageUrl) {
        var str = this.imageUrl;
        const [baseUrl, imageUrl] = str.split(/,/);
        this.editedItem.upload = imageUrl;
      }
      http()
        .put("/updateExpense", this.editedItem)
        .then(response => {
          if ((this.snackbar = true)) {
            this.text = "Successfully Edit Expense";
          }
          this.loading = false;
          this.getExpenseList();
          this.close();
        })
        .catch(error => {
          console.log(error);
          this.loading = false;
        });
    }
  },
  mounted() {
    this.getExpenseList();
  },
  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: gray;
  color: white !important;
}
.activebtn {
  color: black !important;
}
</style>