<template>
  <v-container fluid class="body-color">
    <!-- ****** EDIT EXPENSE  ****** -->
    <v-dialog v-model="editExpenseDialog" max-width="600px" scrollable>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Expense Profile</label>
            <v-icon size="24" class="right" @click="editExpenseDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text style="height: 600px;">
          <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="140px" v-if="!editedItem.fileUrl && !imageUrl">
                <img src="/static/icon/user.png" />
              </v-avatar>
              <img
                :src="editedItem.fileUrl"
                v-else-if="editedItem.fileUrl && !imageUrl"
                style="border-radius:50%; 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 sm12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Name:</label>
                </v-flex>
                <v-flex xs7 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 wrap>
            <v-flex xs12>
              <v-layout>
                <v-flex xs4 class="pt-4 subheading">
                  <label class="right">Date:</label>
                </v-flex>
                <v-flex xs7 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 wrap>
              <v-flex xs12 sm12>
                <v-layout>
                  <v-flex xs4 class="pt-4 subheading">
                    <label class="right">Amount:</label>
                  </v-flex>
                  <v-flex xs7 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 wrap>
                <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>
                </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 xs7 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-spacer></v-spacer>
                <v-btn round dark :loading="loading" @click="save" class="add-button">Save</v-btn>
              </v-card-actions>
            </v-flex>
          </v-layout>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- ****** PROFILE VIEW EXPENSE DETAILS ******  -->

    <v-dialog v-model="viewExpenseDialog" max-width="600px" scrollable>
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Expense</label>
            <v-icon size="24" class="right" @click="viewExpenseDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <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>
    <!-- ****** EXPENSE 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="addExpenseDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addExpenseDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Expense
      </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="expenseList"
      :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="text-xs-center td td-row">
            <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 class="text-xs-center td td-row">{{ props.item.name}}</td>
          <td class="text-xs-center td td-row">{{ dates(props.item.date) }}</td>
          <td class="text-xs-center td td-row">{{ props.item.user }}</td>
          <td class="text-xs-center td td-row">{{ props.item.amount }}</td>
          <td class="text-xs-center td td-row">{{ props.item.note }}</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 Expense Data ****** -->
    <v-dialog v-model="addExpenseDialog" max-width="600px" v-if="addExpenseDialog">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Expense</label>
            <v-icon size="24" class="right" @click="closeAddExpenseModel">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-flex xs12 sm12>
          <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">
                  <v-avatar size="80px">
                    <img src="/static/icon/user.png" v-if="!imageUrl" />
                  </v-avatar>
                  <img
                    :src="imageUrl"
                    height="150"
                    v-if="imageUrl"
                    style="border-radius:50%; width:150px"
                  />
                </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 sm6 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 sm6 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 sm6 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-layout>
              <v-layout>
                <v-flex xs12 sm12>
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right">File:</label>
                    </v-flex>
                    <v-flex xs8 sm6 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-layout>
                <v-flex xs12 sm12>
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right">Note:</label>
                    </v-flex>
                    <v-flex xs8 sm6 class="ml-3">
                      <v-textarea
                        name="input-7-1"
                        v-model="addExpense.note"
                        placeholder="fill your Note"
                        type="text"
                        multi-line
                        required
                      ></v-textarea>
                    </v-flex>
                  </v-layout>
                </v-flex>
              </v-layout>
              <v-layout>
                <v-flex xs11>
                  <v-layout>
                    <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-layout>
                </v-flex>
              </v-layout>
            </v-container>
          </v-form>
        </v-flex>
      </v-card>
    </v-dialog>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ text }}</v-snackbar>
  </v-container>
</template>

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

export default {
  data: () => ({
    component: "report-generate",
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 5000,
    text: "",
    color: "",
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    menu: false,
    menu1: false,
    menu2: false,
    menu3: false,
    editExpenseDialog: false,
    viewExpenseDialog: false,
    valid: true,
    show: true,
    addExpenseDialog: false,
    showSearch: false,
    pagination: {
      rowsPerPage: 10,
    },
    imageData: {},
    token: "",
    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: {},
  }),
  watch: {
    menu(val) {
      val && this.$nextTick(() => (this.$refs.picker.activePicker = "YEAR"));
    },
    menu1(val) {
      val && this.$nextTick(() => (this.$refs.picker.activePicker = "YEAR"));
    },
    addExpenseDialog: function (val) {
      if (!val) {
        this.addExpense = [];
        this.menu1 = false;
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
  },
  methods: {
    save(date) {
      this.$refs.menu.save(date);
    },
    save(date) {
      this.$refs.menu1.save(date);
    },
    pickFile() {
      this.$refs.image.click();
    },
    dates: function (date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    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 = "";
      }
    },
    getExpenseList() {
      http()
        .get("/getExpensesList", {
          params: { schoolId: this.$store.state.schoolId },
          headers: { Authorization: "Bearer " + this.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.date =
        this.editedItem.date != undefined
          ? (this.editedItem.date = this.editedItem.date.substring(0, 10))
          : (this.editedItem.date = "");

      this.editExpenseDialog = true;
    },
    profile(item) {
      this.editedIndex = this.expenseList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.viewExpenseDialog = 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)
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.getExpenseList();
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    close() {
      this.editExpenseDialog = false;
    },
    closeAddExpenseModel() {
      this.addExpenseDialog = false;
      this.addExpense = [];
      this.menu1 = false;
      this.imageName = "";
      this.imageFile = "";
      this.imageUrl = "";
    },
    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;
        // this.addExpense = this.$store.state.schoolId;
        http()
          .post("/createExpense", this.addExpense)
          .then((response) => {
            this.getExpenseList();
            this.snackbar = true;
            this.text = response.data.message;
            this.color = "green";
            this.clear();
            this.imageUrl = "";
            this.loading = false;
            this.addExpenseDialog = false;
          })
          .catch((error) => {
            // console.log(error);
            this.snackbar = true;
            this.color = "error";
            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) => {
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.loading = false;
          this.getExpenseList();
          this.close();
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "error";
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getExpenseList();
  },
};
</script>