<template>
  <v-app id="pages-dasboard">
    <!-- ****** Edit multiple INVOICE ****** -->
    <v-container fluid grid-list-md>
      <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>
        <v-container fluid>
          <v-layout wrap>
            <v-flex xs12 sm12 md5 class="mt-4">
              <v-card flat>
                <v-toolbar dark class="fixcolors" flat>
                  <v-spacer></v-spacer>
                  <v-toolbar-title>
                    <h3>Invoice</h3>
                  </v-toolbar-title>
                  <v-spacer></v-spacer>
                </v-toolbar>
                <v-form ref="form" v-model="valid" lazy-validation class="py-4">
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Select Class:</label>
                      <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Class:</label>
                    </v-flex>
                    <v-flex xs6 class="ml-3">
                      <v-select
                        :items="addclass"
                        label="Select Class"
                        v-model="invoiceData.classId"
                        item-text="classNum"
                        item-value="_id"
                        @change="getAllStudents()"
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Select Student:</label>
                      <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Student:</label>
                    </v-flex>
                    <v-flex xs6 class="ml-3">
                      <v-select
                        :items="studentList"
                        label="Select Incharge"
                        v-model="invoiceData.studentId"
                        item-text="name"
                        item-value="_id"
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <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="menu1"
                        :close-on-content-click="false"
                        v-model="menu1"
                        :nudge-right="40"
                        lazy
                        :return-value.sync="invoiceData.date"
                        transition="scale-transition"
                        offset-y
                        full-width
                        min-width="290px"
                      >
                        <v-text-field
                          slot="activator"
                          v-model="invoiceData.date"
                          placeholder="Select date"
                        ></v-text-field>
                        <v-date-picker
                          v-model="invoiceData.date"
                          @input="$refs.menu1.save(invoiceData.date)"
                        ></v-date-picker>
                      </v-menu>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right hidden-xs-only hidden-sm-only">Payment Status:</label>
                      <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Payment:</label>
                    </v-flex>
                    <v-flex xs6 class="ml-3">
                      <v-select
                        :items="paymentStatus"
                        v-model="invoiceData.paymentStatus"
                        item-text="name"
                        item-value="value"
                        label="Select Payment Status"
                        @change="getPayMethodList"
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <v-layout v-show="showPayMethods">
                    <v-flex xs4 class="pt-4 subheading">
                      <label class="right">Payment Method:</label>
                    </v-flex>
                    <v-flex xs6 class="ml-3">
                      <v-select
                        :items="paymentMethods"
                        v-model="invoiceData.paymentMethod"
                        label="Select Payment Method"
                      ></v-select>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm10 offset-sm1>
                      <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-form>
              </v-card>
            </v-flex>
            <v-flex xs12 sm12 md7 class="mt-4">
              <v-card>
                <v-toolbar dark class="fixcolors" flat>
                  <v-spacer></v-spacer>
                  <v-toolbar-title>
                    <h3>Fee Type List</h3>
                  </v-toolbar-title>
                  <v-spacer></v-spacer>
                </v-toolbar>
                <v-layout>
                  <v-flex xs4 sm2 class="mt-4">
                    <label class="right title">Fee Type:</label>
                  </v-flex>
                  <v-flex xs4 sm4>
                    <v-select
                      :items="feeTypes"
                      v-model="feeType.feeTypeName"
                      item-text="feeType"
                      item-value="feeType"
                      label="Select Fee Type"
                    ></v-select>
                  </v-flex>
                  <v-flex xs4 sm6>
                    <v-btn color="black" dark class="right mt-3" @click="selectFeeType">ADD</v-btn>
                  </v-flex>
                </v-layout>
                <table class="feeTypeTable tableRsponsive">
                  <tr class="info white--text">
                    <th>#</th>
                    <th>Fee Type</th>
                    <th>Amount</th>
                    <th>Discount(%)</th>
                    <th>Subtotal</th>
                    <th>Paid Amount</th>
                    <th>Action</th>
                  </tr>
                  <tr
                    v-for="(feeType, index) in feeTypeData"
                    :key="index"
                    v-on:keyup="getAmmountDetails(feeType)"
                  >
                    <td style="width:40px">{{ index + 1 }}</td>
                    <td style="width:120px">{{ feeType.feeTypeName }}</td>
                    <td>
                      <v-text-field
                        placeholder="fill your Amount"
                        v-model="feeType.amount"
                        type="number"
                      ></v-text-field>
                    </td>
                    <td>
                      <v-text-field
                        placeholder="fill your Discount"
                        v-model="feeType.discount"
                        type="number"
                      ></v-text-field>
                    </td>
                    <td>{{ feeType.subTotal }}</td>
                    <td v-if="invoiceData.paymentStatus === 'NOT_PAID'">
                      <v-text-field
                        placeholder="fill your Paid Amount"
                        v-model="feeType.paidAmount"
                        type="number"
                        :disabled="disabled"
                      ></v-text-field>
                    </td>
                    <td v-if="invoiceData.paymentStatus != 'NOT_PAID'">
                      <v-text-field
                        placeholder="fill your Paid Amount"
                        v-model="feeType.paidAmount"
                        type="number"
                      ></v-text-field>
                    </td>
                    <td>
                      <v-icon color="error" @click="deleteSelectFee(index)">delete</v-icon>
                    </td>
                  </tr>
                  <tfoot>
                    <tr>
                      <td colspan="2">Total:</td>
                      <td>{{ feeType.amount }}</td>
                      <td>{{ feeType.discount }}</td>
                      <td>{{ feeType.subTotal }}</td>
                      <td>{{ feeType.paidAmount }}</td>
                    </tr>
                  </tfoot>
                </table>
              </v-card>
            </v-flex>
          </v-layout>
        </v-container>
      </v-flex>
    </v-container>
    <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 moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    showPayMethods: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    // dialog: false,
    // dialog1: false,
    valid: true,
    validEdit: true,
    // isActive: true,
    // newActive: false,
    showFeeType: false,
    disabled: true,
    details: [],
    feeTypes: [],
    menu1: false,
    invoiceData: {},
    paymentMethods: ["Cash", "Cheque"],
    feeType: {
      amount: "0.00",
      discount: "0.00",
      paidAmount: "0.00",
      subTotal: "0.00",
      feeTypeName: ""
    },
    feeTypeData: [],
    pagination: {
      rowsPerPage: 15
    },
    token: "",
    editedItem: {},
    invoiceParticularData: {},
    addclass: [],
    studentList: [],
    paymentStatus: [
      {
        name: "Not Paid",
        value: "NOT_PAID"
      },
      {
        name: "Partially Paid",
        value: "PARTIALLY_PAID"
      },
      {
        name: "Fully Paid",
        value: "FULLY_PAID"
      }
    ]
  }),
  // watch: {
  //   menu1(val) {
  //     val && this.$nextTick(() => (this.$refs.picker.activePicker = "YEAR"));
  //   }
  // },
  methods: {
    save(date) {
      this.$refs.menu1.save(date);
    },
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    deleteItem(item) {
      let deleteInvoice = {
        invoiceId: item._id
      };
      http()
        .delete(
          "/deleteInvoice",
          confirm("Are you sure you want to delete this?") && {
            params: deleteInvoice
          }
        )
        .then(response => {
          if ((this.snackbar = true)) {
            this.text = "Successfully delete Existing Invoice";
          }
          this.getInvoiceList();
        })
        .catch(error => {
          // console.log(error);
        });
    },
    submit() {
      //   console.log("this.feeType", this.feeType);
      let feeTypeId = "";
      for (let i = 0; i < this.feeTypes.length; i++) {
        if (this.feeTypes[i].feeType === this.feeType.feeTypeName) {
          feeTypeId = this.feeTypes[i]._id;
        }
      }
      if (this.$refs.form.validate()) {
        let invoiceData = {
          invoiceId: this.invoiceData._id,
          classId: this.invoiceData.classNum,
          studentId: this.invoiceData.sectionId,
          date: this.invoiceData.date,
          paymentStatus: this.invoiceData.paymentStatus,
          paymentMethod: this.invoiceData.paymentMethod,
          feeType: this.feeTypeData,
          totalAmount: this.feeType.amount,
          totalDiscount: this.feeType.discount,
          totalSubTotal: this.feeType.subTotal,
          totalPaidAmount: this.feeType.paidAmount
        };
        if (invoiceData.paymentStatus == "NOT_PAID") {
          delete invoiceData.totalPaidAmount;
        }
        if (feeTypeId == "") {
          delete invoiceData.feeType[0].feeTypeId;
        }
        if (this.invoiceData.paymentStatus == "NOT_PAID") {
          delete invoiceData.paymentMethod;
        }
        http()
          .put("/updateInvoice", invoiceData)
          .then(response => {
            this.getInvoiceList();
            this.snackbar = true;
            this.text = "New Invoice added successfully";
            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();
    },
    getInvoiceList() {
      http()
        .get("/getParticularInvoice", {
          params: { invoiceId: this.$route.params.invoiceid },
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.invoiceParticularData = response.data.data;
          this.invoiceData = this.invoiceParticularData;
          this.invoiceData.date = this.invoiceParticularData.date.slice(0, 10);
          this.feeTypeData = this.invoiceParticularData.feeType;
          (this.feeType.amount = response.data.data.totalAmount),
            (this.feeType.discount = response.data.data.totalDiscount),
            (this.feeType.subTotal = response.data.data.totalSubTotal),
            (this.showLoader = false);
        })
        .catch(err => {
          this.showLoader = false;
        });
    },
    selectFeeType() {
      this.showFeeType = true;
      this.feeTypeData.push({ feeTypeName: this.feeType.feeTypeName });
    },
    deleteSelectFee: function(index) {
      this.feeTypeData.splice(index, 1);
      for (let i = 0; i < this.feeTypeData.length; i++) {
        this.feeType = this.feeTypeData[i];
      }
      if (this.feeTypeData.length == 0) {
        this.feeType = {
          amount: "0.00",
          discount: "0.00",
          paidAmount: "0.00",
          subTotal: "0.00",
          feeTypeList: ""
        };
      }
    },
    getAllClasses() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.addclass = response.data.data;
        })
        .catch(err => {
          // console.log("err====>", err);
        });
    },
    getAllStudents() {
      http()
        .get("/getStudentsList", {
          params: { classId: this.invoiceData.classNum },
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.studentList = response.data.data;
        })
        .catch(err => {
          // console.log("err====>", err);
        });
    },
    getfeeType() {
      http()
        .get("/getFeesList", {
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          this.feeTypes = response.data.data;
        })
        .catch(err => {
          // console.log("err====>", err);
        });
    },
    getAmmountDetails(feeTyp) {
      let feeType = {
        amount: "",
        discount: "",
        subTotal: "",
        subParticularTotal: "",
        paidAmount: ""
      };
      for (let i = 0; i < this.feeTypeData.length; i++) {
        // *********** AMOUNT ***********
        feeType.amount =
          Number(feeType.amount) + Number(this.feeTypeData[i].amount);
        console.log("feeType.amount ", feeType.amount);
        this.feeType.amount = feeType.amount;
        this.feeType.subTotal = feeType.amount;
        this.feeTypeData[i].subTotal = this.feeTypeData[i].amount;
        // *********** DISCOUNT ***********
        if (this.feeTypeData[i].discount) {
          feeType.discount =
            Number(feeType.discount) + Number(this.feeTypeData[i].discount);
          console.log("feeType.discount", feeType.discount);
          this.feeType.discount = feeType.discount;
          feeType.subParticularTotal =
            this.feeTypeData[i].amount -
            (this.feeTypeData[i].amount * this.feeTypeData[i].discount) / 100;
          console.log("feeType.subTotal", feeType.subTotal);
          this.feeTypeData[i].subTotal = feeType.subParticularTotal.toFixed(2);
        }
        // *********** SUBTOTAL ***********
        feeType.subTotal =
          Number(feeType.subTotal) + Number(this.feeTypeData[i].subTotal);
        this.feeType.subTotal = feeType.subTotal.toFixed(2);
        // *********** PAID-AMOUNT ***********
        feeType.paidAmount =
          Number(feeType.paidAmount) + Number(this.feeTypeData[i].paidAmount);
        this.feeType.paidAmount = feeType.paidAmount.toFixed(2);
      }
    },
    getPayMethodList() {
      if (this.invoiceData.paymentStatus == "PARTIALLY_PAID") {
        this.showPayMethods = true;
      } else if (this.invoiceData.paymentStatus == "FULLY_PAID") {
        this.showPayMethods = true;
      } else {
        this.showPayMethods = false;
      }
    }
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getInvoiceList();
    this.getAllClasses();
    this.getfeeType();
  },
  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;
}
table {
  border-collapse: collapse;
  border: 1px solid #e2e7eb;
}

th,
td {
  border: 1px solid #e2e7eb;
  padding: 10px;
  text-align: center;
}
table.feeTypeTable {
  table-layout: auto !important;
  width: 100% !important;
}
@media screen and (max-width: 380px) {
    .tableRsponsive {
        display: block;
        position: relative;
        overflow: scroll;
    }
}
</style> 