<template>
  <v-container fluid class="body-color">
    <!-- ****** Edit INVOICE ****** -->
    <v-dialog v-model="editInvoiceDialog" persistent>
      <v-card flat class="text-xs-center">
        <v-layout>
          <v-flex xs12 class="Card-style pa-2">
            <label class="title text-xs-center">Edit Invoice</label>
            <v-icon size="24" class="right" @click="editInvoiceDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <editInvoice :editData="editData" @update-editInvoice="updateDoneInvoice" />
      </v-card>
    </v-dialog>

    <!-- ****PAYMENT INVOICE DIALOG -->
    <v-dialog v-model="paymentInvoiceDialog" persistent>
      <v-card flat class="text-xs-center">
        <v-layout>
          <v-flex xs12 class="Card-style pa-2">
            <label class="title text-xs-center">Payment Template</label>
            <v-icon size="24" class="right" @click="paymentInvoiceDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <paymentTemplate :editPayment="editPayment" @update-Payment="updatePayment" />
      </v-card>
    </v-dialog>

    <!-- ****** PROFILE VIEW SECTION DATA ******  -->

    <v-dialog v-model="dialog1" max-width="800px" persistent>
      <v-card flat class="text-xs-center">
        <v-layout>
          <v-flex xs12 class="Card-style pa-2">
            <label class="title text-xs-center">View Payments</label>
            <v-icon size="24" class="right" @click="dialog1 = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <table class="feeTypeTable tableRsponsive">
          <tr style="color: black">
            <th>#</th>
            <th>Date</th>
            <th>Paid By</th>
            <th>Payment Amount</th>
            <th>Weaver</th>
            <th>Action</th>
          </tr>
          <tr v-if="editedItem.paymentStatus != 'NOT_PAID'">
            <td style="width:40px ; color:black" class="tdFeeType">1</td>
            <td style="width:120px; color:black" class="tdFeeType">{{dates( editedItem.date) }}</td>
            <td style="width:120px; color:black" class="tdFeeType">{{ editedItem.paymentMethod }}</td>
            <td style="width:120px; color:black" class="tdFeeType">{{ editedItem.totalPaidAmount }}</td>
            <td style="width:120px; color:black" class="tdFeeType">{{ editedItem.totalDiscount}}</td>
            <td class="text-xs-center td td-row">
              <router-link
                :to="{ name:'View Payment Invoice',params: { viewPaymentInvoiceId:editedItem._id } }"
              >
                <v-tooltip top>
                  <img
                    slot="activator"
                    style="cursor:pointer; width:25px; height:25px; "
                    class="mr-3"
                    src="/static/icon/view.png"
                  />
                  <span>View</span>
                </v-tooltip>
              </router-link>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer;width:20px; height:20px; "
                  class="mr-3"
                  @click="deletePayment(editedItem)"
                  src="/static/icon/delete.png"
                />
                <span>Delete</span>
              </v-tooltip>
            </td>
          </tr>
          <tr v-if="editedItem.paymentStatus == 'NOT_PAID'">
            <td style="width:40px ; color:black" class="tdFeeType'">-</td>
            <td style="width:120px; color:black" class="tdFeeType">-</td>
            <td style="width:120px; color:black" class="tdFeeType">-</td>
            <td style="width:120px; color:black" class="tdFeeType">-</td>
            <td style="width:120px; color:black" class="tdFeeType">-</td>
            <td class="text-xs-center td td-row"></td>
          </tr>
        </table>
      </v-card>
    </v-dialog>

    <!-- ****** Invoice 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="addInvoiceDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addInvoiceDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Invoice
      </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="invoiceList"
      :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">{{ props.item.studentId.name }}</td>
          <td class="text-xs-center td td-row">{{ props.item.classId.classNum }}</td>
          <td class="text-xs-center td td-row">{{ props.item.totalAmount }}</td>
          <td class="text-xs-center td td-row">{{ props.item.totalDiscount}}</td>
          <td
            class="text-xs-center td td-row"
          >{{ props.item.totalPaidAmount ? props.item.totalPaidAmount : 0}}</td>
          <td
            class="text-xs-center td td-row"
          >{{ props.item.totalPaidAmount ? props.item.totalSubTotal - props.item.totalPaidAmount : props.item.totalSubTotal }}</td>
          <td class="text-xs-center td td-row" v-if="props.item.paymentStatus === 'NOT_PAID'">
            <span
              class="red lighten-1 py-1 px-2 white--text paymentStatus"
            >{{ props.item.paymentStatus }}</span>
          </td>
          <td class="text-xs-center td td-row" v-if="props.item.paymentStatus === 'FULLY_PAID'">
            <span
              class="green lighten-1 py-1 px-2 white--text paymentStatus"
            >{{ props.item.paymentStatus }}</span>
          </td>
          <td class="text-xs-center td td-row" v-if="props.item.paymentStatus === 'PARTIALLY_PAID'">
            <span
              class="yellow darken-3 py-1 px-2 white--text paymentStatus"
            >{{ props.item.paymentStatus }}</span>
          </td>
          <td class="text-xs-center td td-row">{{ dates(props.item.date) }}</td>
          <td class="text-xs-center td td-row">
            <router-link :to="{ name:'View Invoice',params: { viewInvoiceId:props.item._id } }">
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:25px; height:25px; "
                  class="mr-3"
                  src="/static/icon/view.png"
                />
                <span>View</span>
              </v-tooltip>
            </router-link>
            <span v-if="props.item.paymentStatus === 'NOT_PAID'">
              <!-- <router-link :to="{ name: 'Edit Invoice',params: { invoiceid: editData._id } }">
                <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>
              </router-link>-->
              <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; "
                  class="mr-3"
                  @click="deleteItem(props.item)"
                  src="/static/icon/delete.png"
                />
                <span>Delete</span>
              </v-tooltip>
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:18px; "
                  class="mr-3"
                  @click="paymentItem(props.item)"
                  src="/static/schoolIcons/Account.png"
                />
                <span>Payment</span>
              </v-tooltip>
            </span>
            <span v-if="props.item.paymentStatus === 'PARTIALLY_PAID'">
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:18px; "
                  class="mr-3"
                  @click="paymentItem(props.item)"
                  src="/static/schoolIcons/Account.png"
                />
                <span>Payment</span>
              </v-tooltip>
            </span>
            <v-tooltip top>
              <img
                slot="activator"
                style="cursor:pointer; width:18px; height:17px;"
                @click="profile(props.item)"
                src="/static/icon/eye1.png"
              />
              <span>View Payment</span>
            </v-tooltip>
          </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 INVOICE ****** -->
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ text }}</v-snackbar>
    <v-dialog v-model="addInvoiceDialog" v-if="addInvoiceDialog" persistent>
      <v-card flat class="text-xs-center">
        <v-layout>
          <v-flex xs12 class="Card-style pa-2">
            <label class="title text-xs-center">Add Invoice</label>
            <v-icon size="24" class="right" @click="closeAddInvoiceModel">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-flex xs12 sm12>
          <v-container fluid grid-list-md>
            <v-layout wrap>
              <v-flex xs12 sm12 md5>
                <v-card flat>
                  <v-toolbar dark class="card-styles" flat>
                    <v-spacer></v-spacer>
                    <h3>Invoice</h3>
                    <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.classNum"
                          item-text="classNum"
                          item-value="_id"
                          @change="getAllStudents()"
                          :rules="classRules"
                          required
                        ></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 Student"
                          v-model="invoiceData.studentId"
                          item-text="name"
                          item-value="_id"
                          :rules="inchargeRules"
                          @change="selectAllStudent()"
                          required
                        ></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"
                            :rules="dateRules"
                            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"
                          :rules="paymentStatusRules"
                          required
                        ></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"
                          :rules="paymentMethodRules"
                          label="Select Payment Method"
                          required
                        ></v-select>
                      </v-flex>
                    </v-layout>
                    <v-layout>
                      <v-flex xs12 sm11>
                        <v-card-actions>
                          <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-card-actions>
                      </v-flex>
                    </v-layout>
                  </v-form>
                </v-card>
              </v-flex>
              <v-flex xs12 sm12 md7>
                <v-card>
                  <v-toolbar dark class="card-styles" flat>
                    <v-spacer></v-spacer>
                    <h3>Fee Type List</h3>
                    <v-spacer></v-spacer>
                  </v-toolbar>
                  <v-layout>
                    <v-flex xs4 sm2 class="mt-4 hidden-xs-only hidden-sm-only">
                      <label class="right title">Fee Type:</label>
                    </v-flex>
                    <v-flex xs8 sm4>
                      <v-select
                        :items="feeTypes"
                        v-model="feeType.feeTypeName"
                        item-text="feeType"
                        item-value="feeType"
                        label="Select Fee Type"
                        required
                      ></v-select>
                    </v-flex>
                    <v-flex xs4 sm6>
                      <v-btn round dark class="right add-button" @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-show="showFeeType"
                      v-for="(feeType, index) in feeTypeData"
                      :key="index"
                      v-on:keyup="getAmmountDetails(feeType)"
                    >
                      <td style="width:40px" class="tdFeeType">{{ index + 1 }}</td>
                      <td
                        style="width:120px"
                        class="tdFeeType"
                        :rules="feeTypeNameRules"
                      >{{ feeType.feeTypeName }}</td>
                      <td class="tdFeeType">
                        <v-text-field
                          placeholder="fill your Amount"
                          v-model="feeType.amount"
                          type="number"
                          :rules="amountRules"
                          required
                        ></v-text-field>
                      </td>
                      <td class="tdFeeType">
                        <v-text-field
                          placeholder="fill your Discount"
                          v-model="feeType.discount"
                          type="number"
                          :rules="discountRules"
                          required
                        ></v-text-field>
                      </td>
                      <td class="tdFeeType" :rules="subtotalRules">{{ feeType.subTotal }}</td>
                      <td class="tdFeeType" 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 class="tdFeeType" v-if="invoiceData.paymentStatus == ''">
                        <v-text-field
                          placeholder="fill your Paid Amount"
                          v-model="feeType.paidAmount"
                          type="number"
                          :disabled="disabled"
                        ></v-text-field>
                      </td>
                      <td
                        class="tdFeeType"
                        v-if="invoiceData.paymentStatus != 'NOT_PAID' && invoiceData.paymentStatus != ''"
                      >
                        <v-text-field
                          placeholder="fill your Paid Amount"
                          v-model="feeType.paidAmount"
                          type="number"
                        ></v-text-field>
                      </td>
                      <td class="tdFeeType">
                        <v-icon color="error" @click="deleteSelectFee(index,feeType)">delete</v-icon>
                      </td>
                    </tr>
                    <tfoot>
                      <tr>
                        <td colspan="2" class="tdFeeType">Total:</td>
                        <td class="tdFeeType">{{ feeType.amount }}</td>
                        <td class="tdFeeType">{{ feeType.discount }}</td>
                        <td class="tdFeeType">{{ feeType.subTotal }}</td>
                        <td class="tdFeeType">{{ feeType.paidAmount }}</td>
                        <!-- <td class="tdFeeType">
                          <v-icon color="error" @click="deleteSelectFee(index)">delete</v-icon>
                        </td>-->
                      </tr>
                    </tfoot>
                  </table>
                </v-card>
              </v-flex>
            </v-layout>
          </v-container>
        </v-flex>
      </v-card>
    </v-dialog>
    <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 editInvoice from "./editInvoice";
import paymentTemplate from "./paymentTemplate.vue";
import moment from "moment";

export default {
  components: {
    editInvoice: editInvoice,
    paymentTemplate: paymentTemplate,
  },
  data: () => ({
    snackbar: false,
    showPayMethods: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 5000,
    text: "",
    color: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    dialog: false,
    dialog1: false,
    valid: true,
    validEdit: true,
    isActive: true,
    newActive: false,
    showFeeType: true,
    addInvoiceDialog: false,
    editInvoiceDialog: false,
    paymentInvoiceDialog: false,
    disabled: true,
    details: [],
    feeTypes: [],
    invoiceData: [],
    editData: [],
    invoiceList: [],
    editPayment: {
      studentId: {
        name: "",
        rollNo: "",
      },
      classId: {
        classNum: "",
      },
    },
    menu1: false,
    paymentMethods: ["Cash", "Cheque"],
    feeType: {
      amount: "0.00",
      discount: "0.00",
      subTotal: "0.00",
      paidAmount: "0.00",
      feeTypeName: "",
    },

    feeTypeData: [],
    editFeeTypeData: [],
    paymentFeeTypeData: [],
    pagination: {
      rowsPerPage: 10,
    },
    classRules: [(v) => !!v || " Class Name is required"],
    inchargeRules: [(v) => !!v || "Student Name is required"],
    dateRules: [(v) => !!v || " Date is required"],
    paymentStatusRules: [(v) => !!v || "Payment Status is required"],
    paymentMethodsRules: [(v) => !!v || "payment Method is required"],
    feeTypeRules: [(v) => !!v || "Fee Type  is required"],
    feeTypeNameRules: [(v) => !!v || "Fee Type Name is required"],
    amountRules: [(v) => !!v || "Amount is required"],
    discountRules: [(v) => !!v || "Discount is required"],
    subtotalRules: [(v) => !!v || "Subtotal is required"],
    paymentRules: [(v) => !!v || "Payment is required"],
    paidAmountRules: [(v) => !!v || "Paid Amount is required"],
    paymentMethodRules: [],
    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: "Total", value: "subtotal", sortable: false, align: "center" },
      {
        text: "Discount",
        value: "discount",
        sortable: false,
        align: "center",
      },
      {
        text: "Paid Amount",
        value: "paidAmount",
        sortable: false,
        align: "center",
      },
      {
        text: "Balance",
        value: "Balance",
        sortable: false,
        align: "center",
      },
      {
        text: "Status",
        value: "paymentStatus",
        sortable: false,
        align: "center",
      },
      {
        text: "Date",
        value: "date",
        sortable: false,
        align: "center",
      },
      { text: "Action", value: "", sortable: false, align: "center" },
    ],

    studentId: {
      name: "",
    },
    token: "",
    editedItem: {},
    invoiceData: {
      paymentStatus: "",
      students: [],
    },
    addclass: [],
    studentList: [],
    paymentStatus: [
      {
        name: "Not Paid",
        value: "NOT_PAID",
      },
      {
        name: "Partially Paid",
        value: "PARTIALLY_PAID",
      },
      {
        name: "Fully Paid",
        value: "FULLY_PAID",
      },
    ],
  }),
  watch: {
    addInvoiceDialog: function (val) {
      if (!val) {
        this.invoiceData = [];
        this.menu1 = false;
        this.feeType = [];
        this.feeTypeData = [];
      }
    },
  },
  methods: {
    save(date) {
      this.$refs.menu1.save(date);
    },
    dates: function (date) {
      return moment(date).format("MMMM DD, YYYY");
    },
    profile(item) {
      // console.log("item", item);
      this.editedIndex = this.invoiceList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog1 = true;
    },
    editItem(item) {
      this.editedIndex = this.invoiceList.indexOf(item);
      this.editData = Object.assign({}, item);
      this.editData.date = this.editData.date.slice(0, 10);
      // console.log("invoiceData", this.editData);
      this.editFeeTypeData = this.editData.feeType;
      this.editInvoiceDialog = true;
    },
    paymentItem(item) {
      // console.log("item", item);
      this.editedIndex = this.invoiceList.indexOf(item);
      this.editPayment = Object.assign({}, item);
      this.editPayment.date = this.editPayment.date.slice(0, 10);
      if (this.editPayment.paymentStatus == "NOT_PAID") {
        for (let i = 0; i < this.editPayment.feeType.length; i++) {
          this.editPayment.feeType[i].paidAmount = "0.00";
        }
      }
      // console.log("this.editPayment", this.editPayment);
      this.paymentFeeTypeData = this.editPayment.feeType;
      this.paymentInvoiceDialog = true;
    },
    deleteItem(item) {
      let deleteInvoice = {
        invoiceId: item._id,
      };
      http()
        .delete(
          "/deleteInvoice",
          confirm("Are you sure you want to delete this?") && {
            params: deleteInvoice,
          }
        )
        .then((response) => {
          this.snackbar = true;
          this.text = "Successfully delete Existing Invoice";
          this.color = "green";
          this.dialog1 = false;
          this.getInvoiceList();
        })
        .catch((error) => {
          // console.log(error);
        });
    },
    deletePayment(editedItem) {
      let deleteInvoice = {
        invoiceId: editedItem._id,
      };
      http()
        .put(
          "/removePayment",
          deleteInvoice,
          confirm("Are you sure you want to delete this?") && {
            headers: {
              Authorization: "Bearer " + this.token,
            },
          }
        )
        .then((response) => {
          this.snackbar = true;
          this.text = "Successfully delete Existing Invoice";
          this.color = "green";
          this.dialog1 = false;
          this.getInvoiceList();
        })
        .catch((error) => {
          // console.log(error);
        });
    },
    close() {
      this.dialog = false;
    },
    closeAddInvoiceModel() {
      this.addInvoiceDialog = false;
      this.invoiceData = [];
      this.menu1 = false;
      this.feeType = [];
      this.feeTypeData = [];
    },
    // totalAmount() {
    //   // console.log("this.feeType.paidAmount ", this.feeType.paidAmount);
    //   // console.log(
    //   //   "this.feeType.subTotalAAAAAAAAAAAAAAA ",
    //   //   this.feeType.subTotal
    //   // );

    //   if (this.feeType.paidAmount < this.feeType.subTotal) {
    //     console.log("this.feeType.subTotalBBBBBBBBBBB ", this.feeType.subTotal);

    //     this.feeType.paidAmount = this.feeType.subTotal;
    //     console.log(
    //       "this.feeType.paidAmount BBBBBBBBBBB",
    //       this.feeType.paidAmount
    //     );
    //   }
    // },
    submit() {
      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 = {
          classId: this.invoiceData.classNum,
          students: this.invoiceData.students,
          date: this.invoiceData.date,
          paymentStatus: this.invoiceData.paymentStatus,
          paymentMethod: this.invoiceData.paymentMethod,
          feeType: this.feeTypeData,
          totalAmount: this.feeType.amount.toString(),
          totalDiscount: this.feeType.discount.toString(),
          totalSubTotal: this.feeType.subTotal.toString(),
          totalPaidAmount: this.feeType.paidAmount,
        };

        if (invoiceData.paymentStatus == "NOT_PAID") {
          delete invoiceData.paymentMethod;
        }
        if (this.feeType.paidAmount != "0.00") {
          if (this.feeType.subTotal == this.feeType.paidAmount) {
            invoiceData.paymentStatus = "FULLY_PAID";
            // console.log("FULLY_PAID");
          }
          if (invoiceData.totalPaidAmount) {
            if (this.feeType.subTotal != this.feeType.paidAmount) {
              invoiceData.paymentStatus = "PARTIALLY_PAID";
              // console.log("PARTIALLY_PAID");
            }
          }
        }

        if (invoiceData.totalSubTotal == "0.00") {
          invoiceData.paymentStatus = "FULLY_PAID";
        } else if (invoiceData.totalSubTotal != "0.00") {
          if (this.feeType.paidAmount === "0.00") {
            invoiceData.paymentStatus = "NOT_PAID";
            delete invoiceData.paymentMethod;
          }
        }
        http()
          .post("/createInvoice", invoiceData)
          .then((response) => {
            this.getInvoiceList();
            this.snackbar = true;
            this.text = "New Invoice added successfully";
            this.color = "green";
            this.clear();
            this.feeTypeData = [];
            if (this.feeTypeData.length == 0) {
              this.feeType = {
                amount: "0.00",
                discount: "0.00",
                paidAmount: "0.00",
                subTotal: "0.00",
                feeTypeList: "",
              };
            }
            this.loading = false;
            this.addInvoiceDialog = false;
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.errors[0].messages[0];
            this.color = "error";
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    getInvoiceList() {
      this.showLoader = true;
      http()
        .get("/getInvoicesList", {
          params: { schoolId: this.$store.state.schoolId },
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.invoiceList = response.data.data;
          this.showLoader = false;
        })
        .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);
          }
        });
    },
    selectFeeType() {
      this.showFeeType = true;
      this.feeTypeData.push({ feeTypeName: this.feeType.feeTypeName });
    },
    deleteSelectFee: function (index, feeTyp) {
      //   console.log("---index----", index);
      this.feeTypeData.splice(index, 1);
      this.getAmmountDetails(feeTyp);
      if (this.feeTypeData.length == 0) {
        this.feeType = {
          amount: "0.00",
          discount: "0.00",
          paidAmount: "0.00",
          subTotal: "0.00",
          feeTypeName: "",
        };
      }
    },
    getAllClasses() {
      http()
        .get("/getClassesList", {
          params: { schoolId: this.$store.state.schoolId },
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.addclass = response.data.data;
        })
        .catch((err) => {
          // console.log("err====>", err);
          // this.$router.replace({ path: "/" });
        });
    },
    getAllStudents() {
      this.showLoader = true;
      http()
        .get("/getStudentsList", {
          params: {
            classId: this.invoiceData.classNum,
            schoolId: this.$store.state.schoolId,
          },
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.studentList = response.data.data.filter((item) => item.status);
          this.studentList.unshift({
            name: "Select All",
            _id: "Select All",
          });
          //   console.log("=======studentist====", this.studentList);
          this.showLoader = false;
        })
        .catch((err) => {
          this.showLoader = false;
          // console.log("err====>", err);
          // this.$router.replace({ path: "/" });
        });
    },
    getfeeType() {
      http()
        .get("/getFeesList", {
          params: {
            schoolId: this.$store.state.schoolId,
          },
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.feeTypes = response.data.data;
        })
        .catch((err) => {
          // console.log("err====>", err);
          // this.$router.replace({ path: "/" });
        });
    },

    getAmmountDetails(feeTyp) {
      let feeType = {
        amount: "0.00",
        discount: "0.00",
        subTotal: "0.00",
        subParticularTotal: "0.00",
        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";
        }
        // else if (this.feeTypeData[i].discount == "") {
        //   this.feeType.discount =
        //     Number(feeType.discount) + Number(this.feeTypeData[i].discount);
        // }

        // *********** 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.invoiceData.paymentStatus == "PARTIALLY_PAID") {
        this.showPayMethods = true;
        this.paymentMethodRules = [(v) => !!v || "Payment Method is required"];
      } else if (this.invoiceData.paymentStatus == "FULLY_PAID") {
        this.showPayMethods = true;
        this.paymentMethodRules = [(v) => !!v || "Payment Method is required"];
      } else if (this.invoiceData.paymentStatus == "NOT_PAID") {
        for (let i = 0; i < this.feeTypeData.length; i++) {
          this.feeTypeData[i].paidAmount = "0.00";
          this.feeType.paidAmount = "0.00";
        }
        this.paymentMethodRules = "";
        this.showPayMethods = false;
      } else {
        this.showPayMethods = false;
      }
    },
    selectAllStudent() {
      this.invoiceData.students = [];
      if (this.invoiceData.studentId === "Select All") {
        for (let i = 1; i < this.studentList.length; i++) {
          this.invoiceData.students.push(this.studentList[i]._id);
          //   console.log("data", this.invoiceData.students);
          // data.push(this.studentList[i]._id);
          // console.log("data", data);
        }
      } else {
        this.invoiceData.students.push(this.invoiceData.studentId);
      }
    },
    displaySearch() {
      this.show = false;
      this.showSearch = true;
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
    updateDoneInvoice() {
      this.editInvoiceDialog = false;
      this.getInvoiceList();
    },
    updatePayment() {
      this.paymentInvoiceDialog = false;
      this.getInvoiceList();
      this.snackbar = true;
      this.text = "Payment added successfully";
      this.color = "green";
    },
  },
  mounted() {
    this.token = this.$store.state.token;
    this.getInvoiceList();
    this.getAllClasses();
    this.getfeeType();
    this.getAllStudents();
  },
};
</script>


<style scoped>
table {
  border-collapse: collapse;
  border: 1px solid #e2e7eb;
}

th,
.tdFeeType {
  border: 1px solid #e2e7eb;
  padding: 10px;
  text-align: center;
}
table.feeTypeTable {
  table-layout: auto !important;
  width: 100% !important;
}
.card-style {
  background: #7f62f8 !important;
  border-color: #7f62f8 !important;
  border-radius: 12px;
  text-align: center !important;
  padding-top: 10px !important;
}
/* .add-button {
  background: #feb83c !important;
  border-color: #feb83c !important;
  text-transform: none !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}
.clear-button {
  background: #fa7676 !important;
  border-color: #fa7676 !important;
  text-transform: none !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
} */
.card-styles {
  background: #7f62f8 !important;
  border-color: #7f62f8 !important;
}
.v-card__actions .v-btn {
  margin: 0 15px !important;
  min-width: 96px !important;
}
</style>