<template>
  <v-app id="pages-dasboard">
    <!-- ****** Edit multiple INVOICE ****** -->

    <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 grid-list-md>
        <v-layout wrap>
          <v-flex xs12 sm12 md4>
            <v-card flat class="mb-4">
              <v-toolbar dark class="card-styles" flat>
                <v-spacer></v-spacer>
                <h3>Profile</h3>
                <v-spacer></v-spacer>
              </v-toolbar>
              <!-- Profile User-->
              <v-card-text>
                <v-container>
                  <v-layout wrap>
                    <v-flex xs12>
                      <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="!editPayment.profilePicUrl" />
                            <img
                              :src="editPayment.profilePicUrl"
                              v-else-if="editPayment.profilePicUrl"
                            />
                          </v-avatar>
                        </v-flex>
                      </v-layout>
                      <v-layout>
                        <v-flex xs12 sm12>
                          <h3 class="text-xs-center">
                            <b>{{ editPayment.studentId.name }}</b>
                          </h3>
                          <p class="text-xs-center grey--text">Student</p>
                        </v-flex>
                      </v-layout>
                      <v-layout style="border: 1px solid lightgrey;">
                        <v-flex xs6 sm6 class="pa-0">
                          <h4 class="right">
                            <b>Roll No :</b>
                          </h4>
                        </v-flex>
                        <v-flex sm6 xs6 class="pa-0">
                          <h4>{{ editPayment.studentId.rollNo }}</h4>
                        </v-flex>
                      </v-layout>
                      <v-layout style="border: 1px solid lightgrey;">
                        <v-flex xs6 sm6 class="pa-0">
                          <h4 class="right">
                            <b>Class :</b>
                          </h4>
                        </v-flex>
                        <v-flex sm6 xs6 class="pa-0">
                          <h4>{{ editPayment.classId.classNum }}</h4>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                </v-container>
              </v-card-text>
            </v-card>
            <!-- Account Fee Type List User-->
            <v-card flat>
              <v-toolbar dark class="card-styles" 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">Payment Method:</label>
                  </v-flex>
                  <v-flex xs7 class="ml-3">
                    <v-select
                      :items="paymentMethods"
                      v-model="editPayment.paymentMethod"
                      label="Select Payment Method"
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-card-actions>
                  <v-spacer class="hidden-xs-only"></v-spacer>
                  <v-btn
                    color="open-dialog-button"
                    dark
                    class="right add-button"
                    @click="update(editPayment)"
                  >Add Payment</v-btn>
                </v-card-actions>
              </v-form>
            </v-card>
          </v-flex>
          <v-flex xs12 sm12 md8>
            <v-card>
              <v-toolbar dark class="card-styles" flat>
                <v-spacer></v-spacer>
                <v-toolbar-title>
                  <h3>Fee Type List</h3>
                </v-toolbar-title>
                <v-spacer></v-spacer>
              </v-toolbar>
              <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 editPayment.feeType"
                  :key="index"
                  v-on:keyup="getAmmountDetails(feeType,editPayment.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-text-field
                      placeholder="fill your Paid Amount"
                      v-model="feeType.paidAmount"
                      type="number"
                    ></v-text-field>
                  </td>
                  <td v-if="!editPayment.feeType">
                    <v-icon
                      color="error"
                      @click="deleteSelectFee(feeType,editPayment.feeType,index)"
                    >delete</v-icon>
                  </td>
                </tr>
                <tfoot v-if="feeType.amount != 0.00">
                  <tr>
                    <td colspan="2">Total:</td>
                    <td>{{ feeType.amount }}</td>
                    <td>{{ feeType.discount }}</td>
                    <td>{{ feeType.subTotal }}</td>
                    <td>{{ feeType.paidAmount }}</td>
                  </tr>
                </tfoot>
                <tfoot v-else-if="feeType.amount == 0.00">
                  <tr>
                    <td colspan="2">Total:</td>
                    <td>{{ editPayment.totalAmount }}</td>
                    <td>{{ editPayment.totalDiscount }}</td>
                    <td>{{ editPayment.totalSubTotal }}</td>
                    <td>{{ editPayment.totalPaidAmount }}</td>
                  </tr>
                </tfoot>
              </table>
            </v-card>
          </v-flex>
        </v-layout>
      </v-container>
    </v-flex>
    <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 {
  props: ["editPayment"],
  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");
    },
    update(editPayment) {
      // console.log("editPayment-----------", editPayment);
      let feeTypeId = "";
      for (let i = 0; i < this.feeTypes.length; i++) {
        if (this.feeTypes[i].feeType === this.feeType.feeTypeName) {
          feeTypeId = this.feeTypes[i]._id;
        }
      }
      // console.log(editPayment);
      let editInvoiceData = {
        invoiceId: editPayment._id,
        classId: editPayment.classNum,
        studentId: editPayment.sectionId,
        date: editPayment.date,
        paymentStatus: editPayment.paymentStatus,
        paymentMethod: editPayment.paymentMethod,
        feeType: editPayment.feeType,
        totalAmount: this.feeType.amount.toString(),
        totalDiscount: this.feeType.discount.toString(),
        totalSubTotal: this.feeType.subTotal.toString(),
        totalPaidAmount: this.feeType.paidAmount,
      };
      if (feeTypeId == "") {
        delete editInvoiceData.feeType[0].feeTypeId;
      }
      if (editInvoiceData.paymentStatus == "NOT_PAID") {
        delete editInvoiceData.paymentMethod;
      }
      if (editInvoiceData.totalPaidAmount == "0") {
        if (editInvoiceData.paymentStatus == "NOT_PAID") {
          delete editInvoiceData.totalPaidAmount;
        }
      }
      if (editInvoiceData.totalPaidAmount != "0.00") {
        if (this.feeType.subTotal == this.feeType.paidAmount) {
          editInvoiceData.paymentStatus = "FULLY_PAID";
        }
        if (editInvoiceData.totalPaidAmount) {
          if (this.feeType.subTotal != this.feeType.paidAmount) {
            editInvoiceData.paymentStatus = "PARTIALLY_PAID";
            // console.log("PARTIALLY_PAID");
          }
        }
      }

      if (editInvoiceData.totalSubTotal == "0.00") {
        editInvoiceData.paymentStatus = "FULLY_PAID";
      } else if (editInvoiceData.totalSubTotal != "0.00") {
        if (this.feeType.paidAmount === "0.00") {
          editInvoiceData.paymentStatus = "NOT_PAID";
        }
      }
      http()
        .put("/updateInvoice", editInvoiceData)
        .then((response) => {
          // this.getInvoiceList();
          this.snackbar = true;
          this.text = "Payment added successfully";
          this.loading = false;
          this.$emit("update-Payment");
        })
        .catch((error) => {
          console.log(error);
          this.snackbar = true;
          this.text = error.response.data.message;
          this.loading = false;
        });
    },
    clear() {
      this.$refs.form.reset();
    },
    deleteSelectFee: function (feeTyp, feeTypeList, index) {
      this.editPayment.feeType.splice(index, 1);
      this.getAmmountDetails(feeTyp, feeTypeList);
      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;
          this.getAllStudents();
        })
        .catch((error) => {
          // 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);
            this.$store.dispatch("Role", null);
          }
        });
    },
    getAllStudents() {
      http()
        .get("/getStudentsList", {
          params: { classId: this.editPayment.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, feeTypeList) {
      this.feeTypeData = feeTypeList;
      let feeType = {
        amount: "",
        discount: "",
        subTotal: "",
        subParticularTotal: "",
        paidAmount: "",
      };
      for (let i = 0; i < this.feeTypeData.length; i++) {
        // *********** AMOUNT ***********
        if (this.feeTypeData[i].amount) {
          feeType.amount =
            Number(feeType.amount) + Number(this.feeTypeData[i].amount);
          this.feeType.amount = feeType.amount;
          this.feeType.subTotal = feeType.amount;
          this.feeTypeData[i].subTotal = this.feeTypeData[i].amount;
        } else if (this.feeTypeData[0].amount == "") {
          this.feeType.amount = "0.00";
          this.feeTypeData[i].subTotal = "0.00";
          this.feeType.subTotal = "0.00";
        } else if (this.feeTypeData[i].amount == "") {
          this.feeType.amount =
            Number(feeType.amount) + Number(this.feeTypeData[i].amount);
          this.feeTypeData[i].subTotal =
            Number(feeType.amount) + Number(this.feeTypeData[i].amount);
          this.feeType.subTotal =
            Number(feeType.amount) + Number(this.feeTypeData[i].amount);
        }
        // *********** DISCOUNT ***********
        if (this.feeTypeData[i].discount) {
          if (
            Number(this.feeTypeData[i].discount) < this.feeTypeData[i].amount
          ) {
            feeType.discount =
              Number(feeType.discount) + Number(this.feeTypeData[i].discount);
            this.feeType.discount = feeType.discount;
            feeType.subParticularTotal =
              this.feeTypeData[i].amount - this.feeTypeData[i].discount;
            this.feeTypeData[i].subTotal = feeType.subParticularTotal.toFixed(
              2
            );
          } else if (
            Number(this.feeTypeData[i].discount) >= this.feeTypeData[i].amount
          ) {
            this.feeTypeData[i].discount = this.feeTypeData[i].amount;
            feeType.discount =
              Number(feeType.discount) + Number(this.feeTypeData[i].discount);
            this.feeType.discount = feeType.discount.toString();
            feeType.subParticularTotal =
              this.feeTypeData[i].amount - this.feeTypeData[i].discount;
            this.feeTypeData[
              i
            ].subTotal = feeType.subParticularTotal.toString();
          }
        } else if (this.feeTypeData[0].discount == "") {
          this.feeType.discount = "0.00";
        }

        // *********** SUBTOTAL ***********
        if (this.feeTypeData[i].subTotal) {
          feeType.subTotal =
            Number(feeType.subTotal) + Number(this.feeTypeData[i].subTotal);
          this.feeType.subTotal = feeType.subTotal.toFixed(2);
        }

        // *********** PAID-AMOUNT ***********
        if (this.feeTypeData[i].paidAmount) {
          feeType.paidAmount =
            Number(feeType.paidAmount) + Number(this.feeTypeData[i].paidAmount);
          this.feeType.paidAmount = feeType.paidAmount.toFixed(2);
        } else if (this.feeTypeData[0].paidAmount == "") {
          this.feeType.paidAmount = "0.00";
        } else if (this.feeTypeData[i].paidAmount == "") {
          this.feeType.paidAmount = feeType.paidAmount =
            Number(feeType.paidAmount) + Number(this.feeTypeData[i].paidAmount);
        }

        // if paid Amount fill large of subtotal value so this condition are fixed filled subtotal value.
        if (feeType.paidAmount > feeType.subTotal) {
          this.feeTypeData[i].paidAmount = this.feeTypeData[i].subTotal;
          this.feeType.paidAmount = feeType.subTotal;
        }
      }
    },
    // getPayMethodList() {
    //   if (this.editPayment.paymentStatus == "PARTIALLY_PAID") {
    //     this.showPayMethods = true;
    //   } else if (this.editPayment.paymentStatus == "FULLY_PAID") {
    //     this.showPayMethods = true;
    //   } else {
    //     this.showPayMethods = false;
    //   }
    // }
  },
  mounted() {
    this.token = this.$store.state.token;
    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> 