<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 md5 class="mt-4">
            <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 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="editData.classId"
                      item-text="classNum"
                      item-value="_id"
                      @change="getAllStudents(editData.classId)"
                    ></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"
                      v-model="editData.studentId"
                      :label="editData.studentId.name"
                      item-text="name"
                      item-value="_id"
                      @change="getStudentId(editData.studentId)"
                    ></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="editData.date"
                      transition="scale-transition"
                      offset-y
                      full-width
                      min-width="290px"
                    >
                      <v-text-field
                        slot="activator"
                        v-model="editData.date"
                        placeholder="Select date"
                      ></v-text-field>
                      <v-date-picker
                        v-model="editData.date"
                        @input="$refs.menu1.save(editData.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="editData.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="editData.paymentMethod"
                      :rules="paymentMethodRules"
                      label="Select Payment Method"
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-layout>
                  <v-flex xs12 sm11>
                    <v-card-actions>
                      <v-spacer></v-spacer>
                      <v-btn
                        @click="update(editData)"
                        round
                        dark
                        :loading="loading"
                        class="add-button"
                      >Update</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="card-styles" flat>
                <v-spacer></v-spacer>
                <v-toolbar-title>
                  <h3>Fee Type List</h3>
                </v-toolbar-title>
                <v-spacer></v-spacer>
              </v-toolbar>
              <v-layout wrap>
                <v-flex xs12>
                  <v-layout wrap>
                    <v-flex xs12 sm2 class="mt-3">
                      <label class="right title hidden-sm-only hidden-xs-only">Fee Type:</label>
                      <label
                        class="left pl-2 title hidden-xl-only hidden-lg-only hidden-md-only"
                      >Fee Type:</label>
                    </v-flex>
                    <v-flex xs12 sm4>
                      <v-select
                        :items="feeTypes"
                        v-model="feeType.feeTypeName"
                        item-text="feeType"
                        item-value="feeType"
                        label="Select Fee Type"
                        class="px-2"
                      ></v-select>
                    </v-flex>
                    <v-flex xs12 sm6>
                      <v-btn
                        dark
                        class="right mt-3 hidden-sm-only hidden-xs-only"
                        color="open-dialog-button"
                        @click="selectFeeType"
                      >ADD</v-btn>
                      <v-btn
                        dark
                        class="mt-3 hidden-xl-only hidden-lg-only hidden-md-only"
                        color="open-dialog-button"
                        @click="selectFeeType"
                      >ADD</v-btn>
                    </v-flex>
                  </v-layout>
                </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 editData.feeType"
                  :key="index"
                  v-on:keyup="getAmmountDetails(feeType,editData.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="editData.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="editData.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(feeType,editData.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>{{ editData.totalAmount }}</td>
                    <td>{{ editData.totalDiscount }}</td>
                    <td>{{ editData.totalSubTotal }}</td>
                    <td>{{ editData.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: ["editData"],
  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: [],
    paymentMethodRules: [],
    paymentStatus: [
      {
        name: "Not Paid",
        value: "NOT_PAID"
      },
      {
        name: "Partially Paid",
        value: "PARTIALLY_PAID"
      },
      {
        name: "Fully Paid",
        value: "FULLY_PAID"
      }
    ],
    editDataObj: {}
  }),
  // 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(editData) {
      // console.log("editData-----------", editData);
      if (editData.classId._id) {
        this.editDataObj.classNum = editData.classId._id;
      }
      if (editData.studentId._id) {
        this.editDataObj.studentId = editData.studentId._id;
      }
      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 editInvoiceData = {
          invoiceId: editData._id,
          classId: this.editDataObj.classNum,
          studentId: this.editDataObj.studentId,
          date: editData.date,
          paymentStatus: editData.paymentStatus,
          paymentMethod: editData.paymentMethod,
          feeType: editData.feeType,
          totalAmount: this.feeType.amount,
          totalDiscount: this.feeType.discount,
          totalSubTotal: this.feeType.subTotal,
          totalPaidAmount: this.feeType.paidAmount
        };
        // console.log(editInvoiceData, editInvoiceData);
        if (feeTypeId == "") {
          delete editInvoiceData.feeType[0].feeTypeId;
        }
        if (editInvoiceData.paymentStatus == "NOT_PAID") {
          delete editInvoiceData.paymentMethod;
        }
        if (this.feeType.paidAmount != "0.00") {
          if (this.feeType.subTotal == this.feeType.paidAmount) {
            editInvoiceData.paymentStatus = "FULLY_PAID";
            // console.log("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";
          }
        }
        // console.log("editInvoiceData", editInvoiceData);

        http()
          .put("/updateInvoice", editInvoiceData)
          .then(response => {
            // this.getInvoiceList();
            this.snackbar = true;
            this.text = "Edit Invoice successfully";
            this.loading = false;
            color: "red";
            this.$emit("update-editInvoice");
          })
          .catch(error => {
            console.log(error);
            this.snackbar = true;
            this.text = error.response.data.message;
            color: "red";
            this.loading = false;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
    },
    selectFeeType() {
      this.showFeeType = true;
      this.editData.feeType.push({ feeTypeName: this.feeType.feeTypeName });
    },
    deleteSelectFee: function(feeTyp, feeTypeList, index) {
      this.editData.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;
        })
        .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(classId) {
      // console.log("classId", classId);
      this.editDataObj.classNum = classId;
      this.editDataObj.studentId = "";
      this.studentList = [];
      this.showLoader = true;
      http()
        .get("/getStudentsList", {
          params: { classId: classId },
          headers: { Authorization: "Bearer " + this.token }
        })
        .then(response => {
          for (let i = 0; i < response.data.data.length; i++) {
            this.studentList.push({
              name: response.data.data[i].name,
              _id: response.data.data[i]._id
            });
          }
          this.showLoader = false;
        })
        .catch(err => {
          // console.log("err====>", err);
          this.showLoader = false;
        });
    },
    getStudentId(studentId) {
      // console.log("studentId", studentId);
      this.editDataObj.studentId = studentId;
    },
    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.editData.paymentStatus == "PARTIALLY_PAID") {
        this.showPayMethods = true;
        this.paymentMethodRules = [v => !!v || "Payment Method is required"];
      } else if (this.editData.paymentStatus == "FULLY_PAID") {
        this.showPayMethods = true;
        this.paymentMethodRules = [v => !!v || "Payment Method is required"];
      } else if (this.editData.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;
      }
    }
  },
  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> 