<template>
  <v-container fluid class="body-color">
    <!-- ****** Edit  Payment History  ****** -->
    <v-dialog v-model="editPaymentDialog" max-width="400px">
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Edit Payment History</label>
            <v-icon size="24" class="right" @click="editPaymentDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-form ref="form">
          <v-container fluid>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs3 class="pt-4 subheading">
                  <label class="right">Amount:</label>
                </v-flex>
                <v-flex xs8 sm7 class="ml-3">
                  <v-text-field
                    v-model="editedItem.totalPaidAmount"
                    placeholder="please fill this field"
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12 sm12>
              <v-layout>
                <v-flex xs3 class="pt-4 subheading">
                  <label class="right">Method:</label>
                </v-flex>
                <v-flex xs8 sm7 class="ml-3">
                  <v-select
                    :items="paymentMethod"
                    v-model="editedItem.paymentMethod"
                    label="please fill this field"
                    required
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-layout>
              <v-flex xs12>
                <v-layout>
                  <v-spacer></v-spacer>
                  <v-btn round dark @click="save" class="add-button">Update Payment History</v-btn>
                  <v-spacer></v-spacer>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-form>
      </v-card>
    </v-dialog>

    <!-- ****** PAYMENT HISTORY TABLE ****** -->
    <v-toolbar color="transparent" flat>
      <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-show="showSearch">
        <v-layout>
          <v-text-field 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="paymentHistory"
      :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">{{ props.item.studentId.name }}</td>
          <td class="td td-row text-xs-center">{{ props.item.classId.classNum }}</td>
          <td class="td td-row text-xs-center">{{ props.item.feeType.feeTypeName }}</td>
          <td class="td td-row text-xs-center">{{ props.item.paymentMethod }}</td>
          <td class="td td-row text-xs-center">{{ props.item.feeType.paidAmount }}</td>
          <td class="td td-row text-xs-center">{{ dates(props.item.date) }}</td>
          <td class="td td-row text-xs-center">
            <span>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:18px; "
                  class="mr-5"
                  @click="editItem(props.item)"
                  src="/static/icon/edit1.png"
                />
                <span>Edit</span>
              </v-tooltip>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer;width:20px; height:20px; "
                  class="mr-5"
                  @click="deleteItem(props.item)"
                  src="/static/icon/delete1.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>
    <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";
import moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    showLoader: false,
    search: "",
    show: true,
    showSearch: false,
    pagination: {
      rowsPerPage: 10
    },
    paymentMethod: ["Cash", "Cheque"],
    headers: [
      {
        text: "No",
        align: "",
        sortable: false,
        value: "No"
      },
      {
        text: "Student",
        value: "name",
        sortable: false,
        align: "center"
      },
      { text: "Class", value: "class", sortable: false, align: "center" },
      {
        text: "Fee Type",
        value: "feeTypeName",
        sortable: false,
        align: "center"
      },
      {
        text: "Method",
        value: "paymentMethod",
        sortable: false,
        align: "center"
      },
      {
        text: "Paid Amount",
        value: "totalPaidAmount",
        sortable: false,
        align: "center"
      },
      {
        text: "Date",
        value: "date",
        sortable: false,
        align: "center"
      },
      { text: "Action", value: "", sortable: false, align: "center" }
    ],
    paymentHistory: [],
    addPaymentHistoryDialog: "",
    editPaymentDialog: false,
    editedItem: {}
  }),
  methods: {
    editItem(item) {
      this.editedIndex = this.paymentHistory.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.editPaymentDialog = true;
    },
    deleteItem(item) {
      let deleteGrade = {
        invoiceId: item._id,
        feeTypeId: item.feeType._id,
      };
      http()
        .put(
          "/deleteFeeType", 
          confirm("Are you sure you want to delete this?") && 
             deleteGrade,
          {
            headers: {
              Authorization: "Bearer " + this.token
            }
          }
        )
        .then(response => {
          this.snackbar = true;
          //   this.text = "Successfully Delete Salary ";
          this.text = response.data.message;
          this.color = "green";
          this.getPaymentHistory();
        })
        .catch(error => {
          console.log("error", error);
          this.snackbar = true;
          this.text = error.response.data.message;
          this.color = "red";
        });
    },

    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    getPaymentHistory() {
      this.showLoader = true;
      var token = this.$store.state.token;
      http()
        .get("/getPaymentHistory", {
          params: {
            paymentStatus: "FULLY_PAID",
            schoolId: this.$store.state.schoolId
          },
          headers: { Authorization: "Bearer " + token }
        })
        .then(response => {
          this.paymentHistory = 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);
            this.$store.dispatch("Role", null);
          }
        });
    },
    save() {
      var updatePayment = {
        invoiceId: this.editedItem._id,
        feeTypeId: this.editedItem.feeType._id,
        paidAmount: this.editedItem.totalPaidAmount,
        paymentMethod: this.editedItem.paymentMethod
      };
      http()
        .put("/updateFeeType", updatePayment, {
          headers: {
            Authorization: "Bearer " + this.token
          }
        })
        .then(response => {
          this.getPaymentHistory();
          this.snackbar = true;
          this.text = response.data.message;
          this.color = "green";
          this.editPaymentDialog = false;
        })
        .catch(error => {
          console.log("error", error);
          this.snackbar = true;
          this.color = "red";
        });
    },
    displaySearch() {
      (this.show = false), (this.showSearch = true);
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getPaymentHistory();
  }
};
</script>