<template>
    <div>
        <theme-table class="mb-3" :noneActions="true">
            <span slot="main-title">
                {{ $t("Loan Request") }}
            </span>
            <div slot="body">
                <div class="menu">
                    <div class="row mb-3" v-for="(row, index) in form.AddRemoveRows" :key="row.id">
                        <div class="col">
                            <Multiselect
                                class="text-nowrap"
                                style="min-width: 100px"
                                v-model="row.collateral_detail_id"
                                :placeholder="$t('Collateral')"
                                label="title"
                                :searchable="true"
                                :options="getAvailableUsers(index)"
                            />
                        </div>
                        <div class="col" >
                            <div class="d-flex">
                                <input type="text" class="form-control me-2" disabled value="ដាក់ទ្រព្យឥណទាន"/>
                                <button v-if="index != 0" type="button" class="text-center btn btn-outline-danger"
                                    v-on:click="removeRow(index)"><i class="fa-solid fa-minus"></i></button>
                                <button v-else type="button" class="text-center btn btn-outline-success" @click="addRow"
                                    :disabled="form.AddRemoveRows.length >= 6"><i class="fa-solid fa-plus"></i></button>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Client Name") }}<sup class="text-danger">*</sup></label>
                                <Multiselect v-model="form.client_id" :placeholder="$t('Client Name')" label="name"
                                    :class="{ 'is-invalid': form.errors.has('name'), }" :searchable="true"
                                    :options="clients" @search="getClient" @change="changCategoryHome" />
                                <div class="valid text-danger" v-if="form.errors.has('name')"
                                    v-html="form.errors.get('name')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("CO Name") }}<sup class="text-danger">*</sup></label>
                                <Multiselect v-model="form.co_id" :placeholder="$t('CO')" label="name" :class="{
                                    'is-invalid': form.errors.has('name'),
                                }" :searchable="true" :options="coes" @search="getCO" />
                                <div class="valid text-danger" v-if="form.errors.has('name')"
                                    v-html="form.errors.get('name')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Condition Pay") }}<sup class="text-danger">*</sup></label>
                                <Multiselect v-model="form.condition_pay" @input="funChangeCondition"
                                    :placeholder="$t('Condition Pay')" trackBy="condition_pay" value="id"
                                    label="condition_pay" :class="{'is-invalid':form.errors.has('condition_pay')}" :searchable="true" :options="[
                                        {
                                            value: 1,
                                            condition_pay: '1.បង់ប្រាក់ថេរ',
                                        },
                                        {
                                            value: 2,
                                            condition_pay: '2.បង់ប្រាក់ដើមថេរ',
                                        },
                                        {
                                            value: 3,
                                            condition_pay:
                                                '3.បង់ប្រាក់ដើមនិងការប្រាក់ថេរ',
                                        },
                                        {
                                            value: 4,
                                            condition_pay: '4.បង់តែការប្រាក់',
                                        },
                                    ]" />
                                <div class="valid text-danger" v-if="form.errors.has('term_type')" v-html="form.errors.get('term_type')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Term Type") }}<sup class="text-danger">*</sup></label>
                                <Multiselect v-model="form.term_type" @input="funChangeTermType"
                                    :placeholder="$t('Term Type')" trackBy="term_type" value="id" label="term_type" :class="{
                                        'is-invalid': form.errors.has('term_type'),
                                    }" :searchable="true" :options="[
                                        { value: 1, term_type: 'ថ្ងៃ' },
                                        { value: 2, term_type: 'សប្ដាហ៍' },
                                        { value: 3, term_type: 'កន្លះខែ' },
                                        { value: 4, term_type: 'ខែ' },
                                    ]" />
                                <div class="valid text-danger" v-if="form.errors.has('term_type')"
                                    v-html="form.errors.get('term_type')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Term Condition") }}<sup class="text-danger">*</sup></label>
                                <Multiselect v-model="form.term_condi_id" :placeholder="$t('Term Condition')"
                                    trackBy="name_km" @input="changeTermCondition" value="id" label="name_km"
                                    :class="{ 'is-invalid': form.errors.has('term_condi_id') }" :searchable="true"
                                    :options="termcondition" />
                                <div class="valid text-danger" v-if="form.errors.has('term_condi_id')"
                                    v-html="form.errors.get('term_condi_id')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Period") }}<sup class="text-danger">*</sup></label>
                                <input type="text" class="form-control" @keypress="isNumber($event)" @click="clickPeriod"
                                    v-model="form.period" :placeholder="$t('Period')" :class="{
                                        'is-invalid':
                                            form.errors.has('periodInMonth'),
                                    }" />
                                <div class="valid text-danger" v-if="form.errors.has('period')"
                                    v-html="form.errors.get('period')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Disbursement via") }}<sup
                                        class="text-danger">*</sup></label>
                                <Multiselect v-model="form.chart_of_acc_id" :placeholder="$t('Disbursement via')"
                                    label="chart_code_name" :class="{
                                        'is-invalid':
                                            form.errors.has('chart_of_acc_id'),
                                    }" :searchable="true" :options="withdraw_via" />
                                <div class="valid text-danger" v-if="form.errors.has('chart_of_acc_id')"
                                    v-html="form.errors.get('chart_of_acc_id')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Installment Date") }}<sup
                                        class="text-danger">*</sup></label>
                                <date-picker v-model="form.installment_date" valueType="format" @input="funChangeStartDate"
                                    :format="format" :class="{
                                        'is-invalid':
                                            form.errors.has('installment_date'),
                                    }"></date-picker>
                                <div class="text-danger" v-if="form.errors.has('installment_date')"
                                    v-html="form.errors.get('installment_date')" />
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Start Payment") }}<sup class="text-danger">*</sup></label>
                                <date-picker v-model="form.start_date" valueType="format"
                                    :format="format" :class="{
                                        'is-invalid': form.errors.has('start_date'),
                                    }"></date-picker>
                                <div class="text-danger" v-if="form.errors.has('start_date')"
                                    v-html="form.errors.get('start_date')" />
                            </div>
                        </div>
                        <div class="col-xl-2 col-12" v-if="form.term_type==3">
                            <div class="mb-3">
                                <label class="form-label">{{ $t('Date Payment') }}</label>
                                <date-picker v-model="form.date_payment" valueType="format" :format="format" :class="{'is-invalid': form.errors.has('date_payment') }"></date-picker>
                                <div class="text-danger" v-if="form.errors.has('date_payment')" v-html="form.errors.get('date_payment')" />
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Loan Out") }}<sup class="text-danger">*</sup> <strong>({{
                                        symbol_currency }})</strong></label>
                                <input type="text" class="form-control" @keypress="isNumber($event)" @blur="funLoanOut"
                                    @click="clickLoanOut" v-model="form.loan_out" :placeholder="$t('Loan Out')" :class="{
                                        'is-invalid': form.errors.has('loan_out'),
                                    }" />
                                <div class="valid text-danger" v-if="form.errors.has('loan_out')"
                                    v-html="form.errors.get('loan_out')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Interest") }} <strong>(%)</strong></label>
                                <input type="text" v-model="form.interest" @click="clickInterest" class="form-control"
                                    @keypress="isNumber($event)" :placeholder="$t('Interest')" :class="{
                                        'is-invalid': form.errors.has('interest'),
                                    }" />
                                <div class="valid text-danger" v-if="form.errors.has('interest')"
                                    v-html="form.errors.get('interest')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Operating Services") }} <strong>(%)</strong></label>
                                <input type="text" class="form-control" @keypress="isNumber($event)"
                                    v-model="form.operating_service" @click="operatingService"
                                    :placeholder="$t('Operating Services')" :class="{
                                        'is-invalid':
                                            form.errors.has('operating_service'),
                                    }" />
                                <div class="valid text-danger" v-if="form.errors.has('operating_service')"
                                    v-html="form.errors.get('operating_service')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Service") }} <strong>(%)</strong></label>
                                <input type="text" class="form-control" @keypress="isNumber($event)" v-model="form.service"
                                    @click="clickService" @input="funService" :placeholder="$t('Service')" :class="{
                                        'is-invalid': form.errors.has('service'),
                                    }" />
                                <div class="valid text-danger" v-if="form.errors.has('service')"
                                    v-html="form.errors.get('service')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Total Service") }} <strong>({{ symbol_currency
                                        }})</strong></label>
                                <input type="text" class="form-control" v-model="form.total_service" :placeholder="$t('Total Service')"
                                    :class="{
                                        'is-invalid':
                                            form.errors.has('total_service'),
                                    }" />
                                <div class="valid text-danger" v-if="form.errors.has('total_service')"
                                    v-html="form.errors.get('total_service')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Insurance") }} <strong>(%)</strong></label>
                                <input type="text" class="form-control" @keypress="isNumber($event)"
                                    v-model="form.insurance" @click="clickInsurance" @input="funInsurance"
                                    :placeholder="$t('Insurance')" />
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Total Insurance") }} <strong>({{ symbol_currency
                                        }})</strong></label>
                                <input type="text" class="form-control" disabled :value="form.total_insurance | numberFomartValue
                                    " :placeholder="$t('Total Insurance')" />
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Credit Type") }}<sup class="text-danger">*</sup>
                                    <strong></strong></label>
                                <Multiselect v-model="form.credit_type" :placeholder="$t('Credit Type')" :class="{
                                    'is-invalid': form.errors.has('credit_type'),
                                }" trackBy="credit_type" value="id" label="credit_type" :searchable="true" :options="[
                                    { value: 1, credit_type: 'អាជីវកម្ម' },
                                    {
                                        value: 2,
                                        credit_type: 'ប្រើប្រាស់ផ្ទាល់ខ្លួន',
                                    },
                                    { value: 3, credit_type: 'អតិថិជនថ្មី' },
                                    { value: 4, credit_type: 'អតិថិជនចាស់' },
                                ]" />
                                <div class="valid text-danger" v-if="form.errors.has('form.credit_type')"
                                    v-html="form.errors.get('form.credit_type')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                            <div class="mb-3">
                                <label class="form-label">{{ $t("Purpose") }}</label>
                                <textarea rows="1" type="text" class="form-control" v-model="form.desc"
                                    :placeholder="$t('Purpose')" :class="{'is-invalid': form.errors.has('desc')}" :rows="1"></textarea>
                                <div class="valid text-danger" v-if="form.errors.has('desc')"
                                    v-html="form.errors.get('desc')"></div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12 ms-auto" v-show="generateTrue == true">
                            <div class="mt-4">
                                <button type="button" class="btn btn-success w-100" @click="generateTerm(form.period)">{{$t("Generate") }}</button>
                            </div>
                        </div>
                        <div class="col-xl-2 col-lg-6 col-md-6 col-12 ms-auto" v-show="clearFalse == true">
                            <div class="mt-4">
                                <button type="button" class="btn btn-danger w-100" @click="clearRow()">{{$t("Clear Row") }}</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </theme-table>
        <theme-table :noneActions="true">
            <span slot="main-title">
                {{ $t("Payment Schedule") }}
            </span>
            <div slot="body">
                <div class="menu">

                    <div class="row">
                        <div class="col-12">
                            <div class="table-responsive " :class="form.rows == '' ? '' : 'table_scroll'">
                                <table class="table table-bordered">
                                    <thead class="text-nowrap fixed_table sticky-top">
                                        <tr>
                                            <th>{{ $t("#") }}</th>
                                            <th>{{ $t("Payment Date") }}</th>
                                            <th style="width: 80px;">
                                                {{ $t("Qty Day") }}
                                            </th>
                                            <th>{{ $t("Principal") }}</th>
                                            <th>{{ $t("Interest") }}</th>
                                            <th>{{ $t("Operating Services") }}</th>
                                            <th>{{ $t("Payment") }}</th>
                                            <th>{{ $t("Loan Balance") }}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="(row, index) in form.rows" :key="index">
                                            <td>{{ index + 1 }}</td>
                                            <td>
                                                <input type="text" :value="row.payment_date | onlyDate
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                {{ calculateDaysBetweenPaymentDates(index) }}
                                            </td>
                                            <td>
                                                <input type="text" :value="row.principal
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="row.interestPerMonth
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="row.operatService
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="row.payment_per_month
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="row.loan_balance
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                        </tr>
                                        <tr v-show="generateTrue == false">
                                            <td colspan="3" class="text-end">
                                                {{ $t("Total") }}
                                            </td>
                                            <td>
                                                <input type="text" :value="totalPrincipal
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="totalInterest
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="totalOperatService
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td>
                                                <input type="text" :value="totalPayment
                                                    | numberFomartValue
                                                    " class="form-control" disabled />
                                            </td>
                                            <td></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="d-flex justify-content-end">
                    <button type="submit" :disabled="form.busy" v-show="form.rows.length > 0" class="btn btn-success"
                        @click="submitData">
                        <i class="fa-solid fa-floppy-disk"></i>
                        {{ $t("Submit") }}
                    </button>
                </div>
            </div>
        </theme-table>

    </div>


</template>

<script>
import moment from "moment";
import ThemeTable from "../../components/ThemeTable.vue";
export default {
    components: {
        ThemeTable,
    },
    props: ["id"],
    data() {
        return {
            moment: moment,
            format: "YYYY-MM-DD",
            term: "",
            formatLoanOut: 0,
            clearFalse: false,
            generateTrue: true,
            clients: [],
            coes: [],
            termcondition: [],
            holidays: [],
            // collaterals: [],
            collateralcustomdetail: [],
            withdraw_via: [],
            symbol_currency: "",
            form: new Form({
                id: "",
                desc: "",
                client_id: "",
                co_id: "",
                credit_type  : "",
                date_payment : "",
                installment_date: new Date().toISOString(),
                start_date: "",
                chart_of_acc_id: "",
                loan_status_id: 0,

                // Value of...
                loan_out: 0,
                term_condi_id: 0,
                interest: 0,
                operating_service: 0,
                maintenance: 0,
                service: 0,
                insurance: 0,
                saving: 0,
                total_service: 0,
                total_insurance: 0,
                total_saving: 0,
                total_collection: 0,
                service_collection: 0,
                total_to_client: 0,
                balance_principal: 0,
                interest_amount: 0,
                // Condition of...
                period: "",
                amount_payment: 0,
                currency_id: "",
                condition_pay: "",
                term_type: "",
                level_loan: "",
                loan_code: "",
                rows: [],

                client_type: 1, // Default
                type_loan  : 1,// Default
                AddRemoveRows: [{ id: "", date_made: "", collateral_detail_id: "", status: 1 }],
            }),
        };
    },
    created() {
        this.getCO();
        this.getTermCondition();
        this.getClient();
        this.getHolidays();
        this.getWithdrawVia();
        this.getLoans();
    },
    methods: {
        // ******************* 1.ថ្ងៃឈប់សម្រាក់ចាប់ទិន្នន័យពីការវាយបញ្ចូល(tbholidays) *******************//
        // getHolidays(){
        //     axios.get("admin-api/com-holidays").then(
        //         function (response) {
        //             this.holidays = response.data;
        //         }.bind(this)
        //     );
        // },
        // ******************* 2.ថ្ងៃឈប់សម្រាក់ចាប់ទិន្នន័យAuto(api-calendar) *******************//
        getHolidays() {
            axios.get("https://calendarpublicholidaykm-kh-apidata.somnabhost.com/api/get-api-calendar/som424").then(
                function (response) {
                    this.holidays = response.data.items;
                }.bind(this)
            );
        },

        //---------------------------------------------------------------------------- //
        // *** Note:(1) ផ្លាស់ប្តូរទៅតាមHoliday auto(api-calendar) or from table holidays(tbholidays)
        //---------------------------------------------------------------------------//
        //          Change to => el.start.date      : នៅពេលHoliday ចាប់ទិន្នន័យពីការវាយបញ្ចូល(tbholidays)
        //          Change to => el.start.date: នៅពេលHoliday ចាប់Auto(api-calendar)
        //------------------------------------------------------------------------//
        getCO() {
            axios
                .get("admin-api/com-co")
                .then((res) => {
                    this.coes = res.data;
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        getTermCondition() {
            axios
                .get("admin-api/com-get-term-condition")
                .then((res) => {
                    this.termcondition = res.data;
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        changeTermCondition() {
            this.clearRow();
        },
        getClient() {
            axios
                .get("admin-api/com-client-name-code")
                .then((res) => {
                    this.clients = res.data;
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        changCategoryHome(client_id = null) {
            if (client_id !== null) {
                this.form.AddRemoveRows.collateral_detail_id = "";
            }
            this.funGetProjectByClient(client_id);
        },
        funGetProjectByClient(client_id) {
            axios
                .get("admin-api/com-collaterals-detail", { params: { client_id: client_id } })
                .then((res) => {
                    this.collateralcustomdetail = res.data;
                })
                .catch((error) => {
                    console.error("Error fetching custom collaterals:", error);
                });
        },
        getAvailableUsers(index) {
            if (this.form.client_id == null || this.form.client_id == "") {
                return [];
            } else {
                const selectedIds = this.form.AddRemoveRows.map((c, i) => (i !== index ? c.collateral_detail_id : null)) // exclude current index
                    .filter((collateral_detail_id) => collateral_detail_id); // remove null/empty

                return this.collateralcustomdetail.filter((collateral) => !selectedIds.includes(collateral.collateral_detail_id));
            }
        },
        getWithdrawVia() {
            axios
                .get("accounting/com-cash-bank")
                .then((res) => {
                    this.withdraw_via = res.data;
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        isNumber: function (evt) {
            evt = evt ? evt : window.evt;
            var charCode = evt.which ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode !== 46) {
                evt.preventDefault();
            } else {
                return true;
            }
        },
        getLoans() {
            axios
                .get("admin-api/loans/create", {
                    params: { id: this.id },
                })
                .then((res) => {
                    if (res.data.status == 1 && res.data.data) {

                        this.form.fill(res.data.data);
                        this.formatLoanOut = res.data.data.loan_out;
                        this.form.loan_status_id = res.data.data.loan_status_id;
                        this.is_create = false;
                    } else {
                        this.is_create = true;
                    }
                    this.form.date_payment = "";

                    this.form.currency_id = res.data.currency_id;
                    this.symbol_currency = res.data.currency_id == 1 ? "៛" : "$";
                })
                .catch((error) => {
                    if (error.message == "Request failed with status code 403") {
                        this.$router.push({ name: "permissionTest" });
                    } else {
                        console.log(error.message);
                    }
                });
        },

        calculateDaysBetweenPaymentDates(index) {
            if (index === 0) {
                const currentDate = moment(this.form.rows[index].payment_date);
                const previousDate = moment(this.form.installment_date);
                return currentDate.diff(previousDate, "days");
            } else {
                const currentDate = moment(this.form.rows[index].payment_date);
                const previousDate = moment(this.form.rows[index - 1].payment_date);
                return currentDate.diff(previousDate, "days");
            }
        },
        addRow: function () {
            this.form.AddRemoveRows.push({ id: "", date_made: "", collateral_detail_id: "", status: 1 });
        },
        removeRow: function (index) {
            this.form.AddRemoveRows.splice(index, 1);
        },
        funtypeOfPayment() {
            if (this.form.term_type == 1) {
                this.term = "day";
            } else if (this.form.term_type == 2) {
                this.term = "week";
            } else if (this.form.term_type == 3) {
                this.term = "weeks";
            } else if (this.form.term_type == 4) {
                this.term = "M";
            }
        },
        clickPeriod() {
            this.clearRow();
            this.form.period = this.form.period == 0 ? "" : this.form.period;
        },
        funChangeCondition() {
            this.clearRow();
        },

        funChangeStartDate(date) {
            this.clearRow();
            if (this.form.term_type != "") {
                if (this.form.term_type == 1) {
                    var days = 1;
                } else if (this.form.term_type == 2) {
                    var days = 7;
                } else if (this.form.term_type == 3) {
                    var days = 14;
                } else {
                    var days = 30;
                }
                return (this.form.start_date = new Date(new Date(date).setDate(new Date(date).getDate() + days)).toISOString());
            }
        },
        funChangeTermType(val_term_type) {
            this.clearRow();
            const installmentDate = this.form.installment_date;
            if (val_term_type == 1) {
                var days = 1;
            } else if (val_term_type == 2) {
                var days = 7;
            } else if (val_term_type == 3) {
                var days = 14;
            } else {
                var days = 30;
            }
            return (this.form.start_date = installmentDate != "" ? new Date(new Date(installmentDate).setDate(new Date(installmentDate).getDate() + days)).toISOString() : "");
        },
        funLoanOut() {
            this.formatLoanOut = parseFloat(this.form.loan_out.replace(/[^\d\.]/g, ""));
            if (isNaN(this.formatLoanOut)) {
                this.formatLoanOut = 0;
            }
            this.form.loan_out = this.formatLoanOut.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
        },
        clickLoanOut() {
            this.clearRow();
            this.form.loan_out = this.form.loan_out == 0 ? "" : this.form.loan_out;
        },
        clickInterest() {
            this.clearRow();
            this.form.interest = this.form.interest == 0 ? "" : this.form.interest;
            this.form.interest_amount = 0;
        },
        operatingService() {
            this.clearRow();
            this.form.operating_service = this.form.operating_service == 0 ? "" : this.form.operating_service;
        },
        clickService() {
            this.clearRow();
            this.form.service = this.form.service == 0 ? "" : this.form.service;
        },
        funService(e) {
            this.form.service = e.target.value;
            this.form.total_service = (this.formatLoanOut * this.form.service) / 100;
        },
        clickInsurance() {
            this.form.insurance = this.form.insurance == 0 ? "" : this.form.insurance;
        },
        funInsurance(e) {
            this.form.insurance = e.target.value;
            this.form.total_insurance = (this.formatLoanOut * this.form.insurance) / 100;
        },
        clickRisk() {
            this.form.service_collection = this.form.service_collection == 0 ? "" : this.form.service_collection;
        },
        clearRow() {
            this.form.rows = [];
            this.clearFalse = false;
            this.generateTrue = true;
        },
        generateTerm(periodInMonth) {
            this.funtypeOfPayment();
            this.clearFalse = true;
            this.generateTrue = false;
            var paymentTermDay = this.form.start_date;
            var amountBePaid = this.formatPayment;

            if (this.form.currency_id == 1) {
                // Riels(៛)
                // ************ បង់ប្រាក់ថេរ ************ //
                if (this.form.condition_pay == 1) {
                    var monthStep         = 0;
                    var amountInstallment = this.formatLoanOut;
                    var rateInterest      = this.form.interest / 100;
                    var operating_service = this.form.operating_service / 100;
                    var rateMaintenance   = this.form.maintenance / 100;

                    var calOperatService = operating_service * this.formatLoanOut;
                    var calcMaintenance = rateMaintenance * this.formatLoanOut;

                    var paymentEachMonth = this.formatLoanOut / periodInMonth;
                    let principal = 0;
                    let payment_per_month = 0;

                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }

                        paymentTermDay = payment_date;

                        var payment = Math.round((this.formatLoanOut * rateInterest) / (1 - Math.pow(1 + rateInterest, -periodInMonth)));
                        var interest_per_month = Math.round((amountInstallment * rateInterest) / 100) * 100;
                        var operat_service = Math.round(calOperatService / 100) * 100;
                        var maintenance_per_month = Math.round(calcMaintenance / 100) * 100;

                        if (this.form.interest == 0) {
                            payment_per_month = paymentEachMonth;
                            principal = paymentEachMonth;
                        } else {
                            payment_per_month = Math.round(payment / 100) * 100;
                            principal = payment_per_month - interest_per_month;
                        }
                        var loan_balance = amountInstallment - principal;
                        amountInstallment = amountInstallment - principal;
                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date: payment_date,
                                principal: principal,
                                interestPerMonth: interest_per_month,
                                operatService: operat_service,
                                maintenancePerMonth: maintenance_per_month,
                                payment_per_month: payment_per_month + operat_service + maintenance_per_month,
                                loan_balance: loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var interest = Math.round(((amountInstallment + principal) * rateInterest) / 100) * 100;
                            var obJect = {
                                payment_date: payment_date,
                                principal: parseFloat(amountInstallment) + parseFloat(principal),
                                interestPerMonth: interest,
                                operatService: operat_service,
                                maintenancePerMonth: maintenance_per_month,
                                payment_per_month: parseFloat(payment_per_month) + parseFloat(amountInstallment) + parseFloat(operat_service) + parseFloat(maintenance_per_month),
                                loan_balance: 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
                // ************ បង់ប្រាក់ដើមថេរ ************ //
                else if (this.form.condition_pay == 2) {
                    var amountInstallment = this.formatLoanOut;
                    var EachMonth = this.formatLoanOut / periodInMonth;
                    var paymentEachMonth = Math.ceil(EachMonth / 100) * 100;
                    var rateInterest = this.form.interest / 100;
                    var rateOperatService = this.form.operating_service / 100;
                    var rateMaintenance = this.form.maintenance / 100;
                    var calcRisk = rateOperatService * this.formatLoanOut;
                    var calcMaintenance = rateMaintenance * this.formatLoanOut;
                    var paymentOperatService = Math.ceil((amountInstallment * rateOperatService) / 100) * 100;
                    var monthStep = 0;
                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }

                        paymentTermDay = payment_date;

                        var paymentInterest = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                        var paymentMaintenance = Math.ceil((amountInstallment * rateMaintenance) / 100) * 100;

                        var loan_balance = amountInstallment - paymentEachMonth;
                        amountInstallment = amountInstallment - paymentEachMonth;

                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date: payment_date,
                                principal: paymentEachMonth,
                                interestPerMonth: paymentInterest,
                                operatService: paymentOperatService,
                                maintenancePerMonth: paymentMaintenance,
                                payment_per_month: paymentEachMonth + paymentOperatService + paymentInterest + paymentMaintenance,
                                loan_balance: loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var obJect = {
                                payment_date: payment_date,
                                principal: amountInstallment + paymentEachMonth,
                                interestPerMonth: paymentInterest,
                                operatService: paymentOperatService,
                                maintenancePerMonth: paymentMaintenance,
                                payment_per_month: paymentEachMonth + paymentOperatService + paymentInterest + paymentMaintenance + amountInstallment,
                                loan_balance: 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
                // ************ បង់ប្រាក់ដើមនិងការប្រាក់ថេរ ************ //
                else if (this.form.condition_pay == 3) {
                    var amountInstallment = this.formatLoanOut;
                    var amountInstallments = this.formatLoanOut;
                    var paymentEachMonth = Math.ceil(this.formatLoanOut / periodInMonth / 100) * 100;
                    var rateInterest = this.form.interest / 100;
                    var rateOperatService = this.form.operating_service / 100;
                    var rateMaintenance = this.form.maintenance / 100;
                    var monthStep = 0;

                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }
                        interestAmount = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                        operatAmount = Math.ceil((amountInstallment * rateOperatService) / 100) * 100;
                        MaintenanceAmount = Math.ceil((amountInstallment * rateMaintenance) / 100) * 100;
                        paymentTermDay = payment_date;
                        var paymentInterest = amountInstallment;
                        var loan_balance = amountInstallments - paymentEachMonth;
                        amountInstallments = amountInstallments - paymentEachMonth;
                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date: payment_date,
                                principal: paymentEachMonth,
                                interestPerMonth: interestAmount,
                                operatService: operatAmount,
                                maintenancePerMonth: MaintenanceAmount,
                                payment_per_month: paymentEachMonth + interestAmount + operatAmount + MaintenanceAmount,
                                loan_balance: loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var obJect = {
                                payment_date: payment_date,
                                principal: amountInstallments + paymentEachMonth,
                                interestPerMonth: interestAmount,
                                operatService: operatAmount,
                                maintenancePerMonth: MaintenanceAmount,
                                payment_per_month: paymentEachMonth + interestAmount + operatAmount + MaintenanceAmount + amountInstallments,
                                loan_balance: 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
                // ************ បង់តែការប្រាក់ ************ //
                else {
                    var amountInstallment = this.formatLoanOut;
                    var rateInterest = this.form.interest / 100;
                    var rateOperatService = this.form.operating_service / 100;
                    var rateMaintenance = this.form.maintenance / 100;
                    var monthStep = 0;
                    var interestAmount = 0;
                    var operatAmount = 0;
                    var MaintenanceAmount = 0;
                    var amount_interest = 0;

                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }
                        interestAmount = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                        operatAmount = Math.ceil((amountInstallment * rateOperatService) / 100) * 100;
                        MaintenanceAmount = Math.ceil((amountInstallment * rateMaintenance) / 100) * 100;
                        paymentTermDay = payment_date;
                        var paymentInterest = amountInstallment;
                        var loan_balance = amountInstallment;
                        amountInstallment = amountInstallment;

                        var interest_amount = parseFloat(this.form.interest_amount);
                        if (interest_amount == 0 && this.form.interest > 0) {
                            amount_interest = interestAmount;
                        } else {
                            amount_interest = interest_amount;
                        }

                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date: payment_date,
                                principal: 0,
                                interestPerMonth: amount_interest,
                                operatService: operatAmount,
                                maintenancePerMonth: MaintenanceAmount,
                                payment_per_month: amount_interest + operatAmount + MaintenanceAmount,
                                loan_balance: loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var obJect = {
                                payment_date: payment_date,
                                principal: amountInstallment,
                                interestPerMonth: amount_interest,
                                operatService: operatAmount,
                                maintenancePerMonth: MaintenanceAmount,
                                payment_per_month: amount_interest + operatAmount + MaintenanceAmount + amountInstallment,
                                loan_balance: 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
            }
            else {
                // Dollar($)
                if (this.form.condition_pay == 1) {
                    var checkInterest = this.form.interest;
                    if (checkInterest == 0) {
                        var amountInstallment = this.formatLoanOut;
                        var paymentEachMonth = Math.ceil((this.formatLoanOut / periodInMonth / 100) * 100).toFixed(2);
                        var rateInterest = this.form.interest / 100;
                        var rateOperatService = this.form.operating_service / 100;
                        var monthStep = 0;
                        for (var i = 1; i <= periodInMonth; i++) {
                            if (this.term == "day") {
                                var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                            }
                            else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                                if(i==1) {
                                    var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                                }
                                else if(i==2) {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                                else if(i%2!=0) {
                                    for(var j=1;j<=i-j;j++)
                                    {
                                        payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                    }
                                }
                                else if(i%2==0) {
                                    for(var j=1;j<=i-j;j++)
                                    {
                                        payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                    }
                                }
                            }
                            else {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            paymentTermDay = payment_date;

                            var paymentInterest = amountInstallment;
                            var paymentOperatService = amountInstallment;
                            var paymentMaintenance = amountInstallment;
                            var loan_balance = amountInstallment - paymentEachMonth;
                            amountInstallment = amountInstallment - paymentEachMonth;

                            if (i != periodInMonth) {
                                var obJect = {
                                    payment_date: payment_date,
                                    principal: paymentEachMonth,
                                    interestPerMonth: paymentInterest * rateInterest,
                                    operatService: paymentOperatService * rateOperatService,
                                    payment_per_month: paymentEachMonth + paymentOperatService * rateOperatService + paymentInterest * rateInterest,
                                    loan_balance: loan_balance,
                                };
                                this.form.rows.push(obJect);
                            } else {
                                var obJect = {
                                    payment_date: payment_date,
                                    principal: paymentEachMonth,
                                    interestPerMonth: paymentInterest * rateInterest,
                                    operatService: paymentOperatService * rateOperatService,
                                    payment_per_month: paymentEachMonth + paymentOperatService * rateOperatService + paymentInterest * rateInterest,
                                    loan_balance: 0,
                                };
                                this.form.rows.push(obJect);
                            }
                            if (this.term == "weeks") {
                                monthStep += 2;
                            } else {
                                monthStep++;
                            }
                        }
                    }
                    else {
                        var amountInstallment = this.formatLoanOut;
                        var rateInterest = this.form.interest / 100;
                        var rateOperatService = this.form.operating_service / 100;
                        var rateMaintenance = this.form.maintenance / 100;
                        // var calcInterest = rateInterest*this.formatLoanOut;
                        var calcRisk = rateOperatService * this.formatLoanOut;
                        var calcMaintenance = rateMaintenance * this.formatLoanOut;
                        var monthStep = 0;
                        let payment_per_month = 0;
                        for (var i = 1; i <= periodInMonth; i++) {
                            var interest_per_month = Math.ceil(amountInstallment * rateInterest);
                            interest_per_month = parseFloat(interest_per_month).toFixed(2);
                            var operating_service = parseFloat(calcRisk).toFixed(2);
                            var maintenance_per_month = parseFloat(calcMaintenance).toFixed(2);
                            var payment = Math.fround((this.formatLoanOut * rateInterest) / (1 - Math.pow(1 + rateInterest, -periodInMonth)), 2);
                            payment = parseFloat(payment).toFixed(2);
                            payment_per_month = parseFloat(operating_service) + parseFloat(maintenance_per_month) + parseFloat(payment);
                            var total_principal = parseFloat(payment_per_month) - parseFloat(interest_per_month) - parseFloat(operating_service) - parseFloat(maintenance_per_month);
                            var principal = Math.ceil(total_principal / 10) * 10;

                            var loan_balance = parseFloat(amountInstallment) - parseFloat(principal);
                            amountInstallment = parseFloat(amountInstallment) - parseFloat(principal);
                            if (this.term == "day") {
                                var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                            }
                            else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                                if(i==1) {
                                    var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                                }
                                else if(i==2) {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                                else if(i%2!=0) {
                                    for(var j=1;j<=i-j;j++)
                                    {
                                        payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                    }
                                }
                                else if(i%2==0) {
                                    for(var j=1;j<=i-j;j++)
                                    {
                                        payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                    }
                                }
                            }
                            else {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            paymentTermDay = payment_date;
                            if (i != periodInMonth) {
                                var obJect = {
                                    payment_date: payment_date,
                                    principal: parseFloat(principal),
                                    interestPerMonth: parseFloat(interest_per_month),
                                    operatService: parseFloat(operating_service),
                                    maintenancePerMonth: parseFloat(maintenance_per_month),
                                    payment_per_month: parseFloat(principal) + parseFloat(interest_per_month) + parseFloat(operating_service) + parseFloat(maintenance_per_month),
                                    loan_balance: parseFloat(loan_balance),
                                };
                                this.form.rows.push(obJect);
                            } else {
                                var obJect = {
                                    payment_date: payment_date,
                                    principal: parseFloat(principal) + parseFloat(amountInstallment),
                                    interestPerMonth: parseFloat(interest_per_month),
                                    operatService: parseFloat(operating_service),
                                    maintenancePerMonth: parseFloat(maintenance_per_month),
                                    payment_per_month: parseFloat(principal) + parseFloat(amountInstallment) + parseFloat(interest_per_month) + parseFloat(operating_service) + parseFloat(maintenance_per_month),
                                    loan_balance: 0,
                                };
                                this.form.rows.push(obJect);
                            }
                            if (this.term == "weeks") {
                                monthStep += 2;
                            } else {
                                monthStep++;
                            }
                        }
                    }
                }
                else if (this.form.condition_pay == 2) {

                    var amountInstallment = this.formatLoanOut;
                    var paymentEachMonth  = parseFloat(this.formatLoanOut / periodInMonth).toFixed(2);
                    var rateInterest      = this.form.interest / 100;
                    var rateOperatService = parseFloat(this.form.operating_service / 100).toFixed(2);
                    var rateMaintenance   = parseFloat(this.form.maintenance / 100).toFixed(2);
                    var calcRisk          = parseFloat(rateOperatService) * this.formatLoanOut;
                    var calcMaintenance   = parseFloat(rateMaintenance) * this.formatLoanOut;

                    var monthStep = 0;
                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }
                        paymentTermDay = payment_date;
                        var paymentInterest      = parseFloat(amountInstallment * rateInterest).toFixed(2);
                        paymentInterest          = parseFloat(paymentInterest).toFixed(2);
                        var paymentOperatService = parseFloat(calcRisk).toFixed(2);
                        var paymentMaintenance   = parseFloat(calcMaintenance).toFixed(2);
                        var loan_balance  = amountInstallment - paymentEachMonth;
                        amountInstallment = amountInstallment - paymentEachMonth;

                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date       : payment_date,
                                principal          : parseFloat(paymentEachMonth),
                                interestPerMonth   : parseFloat(paymentInterest),
                                operatService      : parseFloat(paymentOperatService),
                                maintenancePerMonth: parseFloat(paymentMaintenance),
                                payment_per_month  : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentOperatService) + parseFloat(paymentMaintenance),
                                loan_balance       : loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var obJect = {
                                payment_date       : payment_date,
                                principal          : parseFloat(paymentEachMonth) + parseFloat(amountInstallment),
                                interestPerMonth   : parseFloat(paymentInterest),
                                operatService      : parseFloat(paymentOperatService),
                                maintenancePerMonth: parseFloat(paymentMaintenance),
                                payment_per_month  : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentMaintenance) + parseFloat(paymentOperatService) + parseFloat(amountInstallment),
                                loan_balance       : 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
                else if (this.form.condition_pay == 3) {

                    var amountInstallment = this.formatLoanOut;
                    var amountInstallments= this.formatLoanOut;
                    var paymentEachMonth  = parseFloat(this.formatLoanOut / periodInMonth).toFixed(2);
                    var rateInterest      = this.form.interest / 100;
                    var rateOperatService = this.form.operating_service / 100;
                    var rateMaintenance   = this.form.maintenance / 100;
                    var monthStep = 0;
                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }
                        interestAmount     = parseFloat(amountInstallment * rateInterest).toFixed(2);
                        operatAmount       = parseFloat(amountInstallment * rateOperatService).toFixed(2);
                        MaintenanceAmount  = parseFloat(amountInstallment * rateMaintenance).toFixed(2);
                        paymentTermDay     = payment_date;
                        var paymentInterest= amountInstallment;
                        var loan_balance   = amountInstallments - paymentEachMonth;
                        amountInstallments = amountInstallments - paymentEachMonth;
                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date       : payment_date,
                                principal          : parseFloat(paymentEachMonth),
                                interestPerMonth   : parseFloat(interestAmount),
                                operatService      : parseFloat(operatAmount),
                                maintenancePerMonth: parseFloat(MaintenanceAmount),
                                payment_per_month  : parseFloat(paymentEachMonth) + parseFloat(interestAmount) + parseFloat(operatAmount) + parseFloat(MaintenanceAmount),
                                loan_balance       : loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var obJect = {
                                payment_date       : payment_date,
                                principal          : parseFloat(paymentEachMonth) + parseFloat(amountInstallments),
                                interestPerMonth   : parseFloat(interestAmount),
                                operatService      : parseFloat(operatAmount),
                                maintenancePerMonth: parseFloat(MaintenanceAmount),
                                payment_per_month  : parseFloat(paymentEachMonth) + parseFloat(interestAmount) + parseFloat(MaintenanceAmount) + parseFloat(operatAmount) + parseFloat(amountInstallments),
                                loan_balance       : 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
                else {
                    var amountInstallment = this.formatLoanOut;
                    var rateInterest = this.form.interest / 100;
                    var rateOperatService = this.form.operating_service / 100;
                    var rateMaintenance = this.form.maintenance / 100;
                    var monthStep = 0;
                    var interestAmount = 0;
                    var operatAmount = 0;
                    var MaintenanceAmount = 0;
                    var MaintenanceAmount = 0;
                    var amount_interest = 0;

                    for (var i = 1; i <= periodInMonth; i++) {
                        if (this.term == "day") {
                            var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                        }
                        else if(this.term == "weeks" && this.form.date_payment!=='' && this.form.date_payment!==null){
                            if(i==1) {
                                var payment_date = this.checkHolidayStart(this.term, this.form.start_date);
                            }
                            else if(i==2) {
                                payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                            }
                            else if(i%2!=0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidayFisrt(this.term, this.form.start_date, j)
                                }
                            }
                            else if(i%2==0) {
                                for(var j=1;j<=i-j;j++)
                                {
                                    payment_date = this.checkHolidaySecond(this.term, this.form.date_payment, j)
                                }
                            }
                        }
                        else {
                            var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                        }
                        paymentTermDay = payment_date;
                        interestAmount = amountInstallment * rateInterest;
                        operatAmount = amountInstallment * rateOperatService;
                        MaintenanceAmount = amountInstallment * rateMaintenance;

                        var paymentInterest = amountInstallment;
                        var loan_balance = amountInstallment;
                        amountInstallment = amountInstallment;

                        var interest_amount = parseFloat(this.form.interest_amount);
                        if (interest_amount == 0 && this.form.interest > 0) {
                            amount_interest = interestAmount;
                        } else {
                            amount_interest = interest_amount;
                        }

                        if (i != periodInMonth) {
                            var obJect = {
                                payment_date: payment_date,
                                principal: 0,
                                interestPerMonth: amount_interest,
                                operatService: operatAmount,
                                maintenancePerMonth: MaintenanceAmount,
                                payment_per_month: amount_interest + operatAmount + MaintenanceAmount,
                                loan_balance: loan_balance,
                            };
                            this.form.rows.push(obJect);
                        } else {
                            var obJect = {
                                payment_date: payment_date,
                                principal: parseFloat(amountInstallment),
                                interestPerMonth: parseFloat(amount_interest),
                                operatService: parseFloat(operatAmount),
                                maintenancePerMonth: parseFloat(MaintenanceAmount),
                                payment_per_month: parseFloat(amount_interest) + parseFloat(operatAmount) + parseFloat(MaintenanceAmount) + parseFloat(amountInstallment),
                                loan_balance: 0,
                            };
                            this.form.rows.push(obJect);
                        }
                        if (this.term == "weeks") {
                            monthStep += 2;
                        } else {
                            monthStep++;
                        }
                    }
                }
            }
        },

        checkHoliday(term, start_date, monthStep) {
            if (term == "M" || term == "week" || term == "weeks") {
                var loanDate = moment(start_date).add(monthStep, term).format("YYYY-MM-DD");
                var index    = this.holidays.findIndex((el) => el.start.date === loanDate); // (1)

                while (index != -1) {
                    loanDate = moment(loanDate).add(1, "day").format("YYYY-MM-DD");
                    index = this.holidays.findIndex((el) => el.start.date === loanDate); // (1)
                }
            } else if (term == "day") {
                var loanDate = moment(start_date).add(monthStep == 0 ? 0 : 1, term).format("YYYY-MM-DD");
                var index    = this.holidays.findIndex((el) => el.start.date === loanDate); // (1)
                while (index != -1) {
                    loanDate = moment(loanDate).add(1, "day").format("YYYY-MM-DD");
                    index    = this.holidays.findIndex((el) => el.start.date === loanDate); // (1)
                }
            }
            if (this.form.term_condi_id == 1) {
                // ចន្ទ័-ព្រហស្បត្តិ៍ (Monday - Thursday)
                loanDate = this.checkMonToThursday(loanDate);
            } else if (this.form.term_condi_id == 2) {
                // ចន្ទ័-សុក្រ (Monday - Friday)
                loanDate = this.checkMonToFriday(loanDate);
            } else if (this.form.term_condi_id == 3) {
                // ចន្ទ័-សៅរ៍ (Monday - Saturday)
                loanDate = this.checkMonToSaturday(loanDate);
            } else if (this.form.term_condi_id == 4) {
                // ចន្ទ័-អាទិត្យ (Monday - Sunday)
                loanDate = this.checkMondayToSunday(loanDate);
            } else if (this.form.term_condi_id == 5) {
                // សៅរ៍-អាទិត្យ (Saturday - Sunday)
                loanDate = this.checkSatToSunday(loanDate);
            }
            return loanDate;
        },
        // ចន្ទ័-ព្រហស្បតិ៍
        checkMonToThursday(loanDate) {
            var dateTime = moment(loanDate);
            var day = dateTime.day();
            while (day == 5 || day == 6 || day == 0) {
                dateTime = moment(dateTime).add(1, "day");
                var index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
                while (index != -1) {
                    dateTime = moment(dateTime).add(1, "day");
                    index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
                }
                day = dateTime.day();
            }
            return dateTime.format("YYYY-MM-DD");
        },
        // ចន្ទ័-សុក្រ
        checkMonToFriday(loanDate) {
            var dateTime = moment(loanDate);
            var day = dateTime.day();
            while (day == 6 || day == 0) {
                dateTime = moment(dateTime).add(1, "day");
                var index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD")); // (1)
                while (index != -1) {
                    dateTime = moment(dateTime).add(1, "day");
                    index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD")); // (1)
                }
                day = dateTime.day();
            }
            return dateTime.format("YYYY-MM-DD");
        },
        // ចន្ទ័-សៅរ៍
        checkMonToSaturday(loanDate) {
            var dateTime = moment(loanDate);
            var day = dateTime.day();
            while (day == 0) {
                dateTime = moment(dateTime).add(1, "day");
                var index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD")); // (1)
                while (index != -1) {
                    dateTime = moment(dateTime).add(1, "day");
                    index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD")); // (1)
                }
                day = dateTime.day();
            }
            return dateTime.format("YYYY-MM-DD");
        },
        // ចន្ទ័-អាទិត្យ
        checkMondayToSunday(loanDate) {
            var dateTime = moment(loanDate);
            var index    = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
            while (index != -1) {
                dateTime = moment(dateTime).add(1, "day");
                index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
            }
            return dateTime.format("YYYY-MM-DD");
        },
        // សៅរ៍-អាទិត្យ
        checkSatToSunday(loanDate) {
            var dateTime = moment(loanDate);
            var day      = dateTime.day();
            while (day !== 0 && day !== 6) {
                dateTime = moment(dateTime).add(1, "day");
                // Skip holidays
                var index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
                while (index != -1) {
                    dateTime = moment(dateTime).add(1, "day");
                    index = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
                }
                day = dateTime.day();
            }
            return dateTime.format("YYYY-MM-DD");
        },


        // Check term_type months.
        checkHolidayStart(term, start_date) {
            if(term == "weeks"){
                var loanDate = moment(start_date).format("YYYY-MM-DD");
                var index    = this.holidays.findIndex((el) => el.start.date === loanDate);
                while (index != -1) {
                    var newloanDate = moment(loanDate).add(1, "day");
                    loanDate = this.checkWeekend(newloanDate);
                    index    = this.holidays.findIndex((el) => el.start.date === loanDate);
                }
            }
            if (this.form.term_condi_id == 1) {
                // ចន្ទ័-ព្រហស្បត្តិ៍ (Monday - Thursday)
                loanDate = this.checkMonToThursday(loanDate);
            } else if (this.form.term_condi_id == 2) {
                // ចន្ទ័-សុក្រ (Monday - Friday)
                loanDate = this.checkMonToFriday(loanDate);
            } else if (this.form.term_condi_id == 3) {
                // ចន្ទ័-សៅរ៍ (Monday - Saturday)
                loanDate = this.checkMonToSaturday(loanDate);
            } else if (this.form.term_condi_id == 4) {
                // ចន្ទ័-អាទិត្យ (Monday - Sunday)
                loanDate = this.checkMondayToSunday(loanDate);
            } else if (this.form.term_condi_id == 5) {
                // សៅរ៍-អាទិត្យ (Saturday - Sunday)
                loanDate = this.checkSatToSunday(loanDate);
            }
            return loanDate;
        },
        checkHolidayFisrt(term, start_date,j) {
            if(term == "weeks"){
                var loanDate = moment(start_date).add(j, 'months').format("YYYY-MM-DD");
                var index    = this.holidays.findIndex((el) => el.start.date === loanDate);
                while (index != -1) {
                    var newloanDate = moment(loanDate).add(1, "day");
                    loanDate = this.checkWeekend(newloanDate);
                    index    = this.holidays.findIndex((el) => el.start.date === loanDate);
                }
            }
            loanDate = this.checkWeekendWithHoliday(loanDate);
            return loanDate;
        },
        checkHolidaySecond(term, date_payment,j) {
            if(term == "weeks"){
                var loanDate = moment(date_payment).add(j-1, 'months').format("YYYY-MM-DD");
                var index    = this.holidays.findIndex((el) => el.start.date === loanDate);
                while (index != -1) {
                    var newloanDate = moment(loanDate).add(1, "day");
                    loanDate = this.checkWeekend(newloanDate);
                    index = this.holidays.findIndex((el) => el.start.date === loanDate);
                }
            }
            loanDate = this.checkWeekendWithHoliday(loanDate);
            return loanDate;
        },
        checkWeekendWithHoliday(loanDate) {
            var dateTime = moment(loanDate);
            var index    = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
            while (index != -1) {
                dateTime = moment(dateTime).add(1, "day");
                index    = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
            }
            if (this.form.term_condi_id == 1) {
                // ចន្ទ័-ព្រហស្បត្តិ៍ (Monday - Thursday)
                dateTime = this.checkMonToThursday(dateTime);
            } else if (this.form.term_condi_id == 2) {
                // ចន្ទ័-សុក្រ (Monday - Friday)
                dateTime = this.checkMonToFriday(dateTime);
            } else if (this.form.term_condi_id == 3) {
                // ចន្ទ័-សៅរ៍ (Monday - Saturday)
                dateTime = this.checkMonToSaturday(dateTime);
            } else if (this.form.term_condi_id == 4) {
                // ចន្ទ័-អាទិត្យ (Monday - Sunday)
                dateTime = this.checkMondayToSunday(dateTime);
            } else if (this.form.term_condi_id == 5) {
                // សៅរ៍-អាទិត្យ (Saturday - Sunday)
                dateTime = this.checkSatToSunday(dateTime);
            }
            return dateTime;
        },
        checkWeekend(date) {
            var dateTime = moment(date);
            var index    = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
            while (index != -1) {
                dateTime = moment(dateTime).add(1, "day");
                index    = this.holidays.findIndex((el) => el.start.date === dateTime.format("YYYY-MM-DD"));
            }
            if (this.form.term_condi_id == 1) {
                // ចន្ទ័-ព្រហស្បត្តិ៍ (Monday - Thursday)
                dateTime = this.checkMonToThursday(dateTime);
            } else if (this.form.term_condi_id == 2) {
                // ចន្ទ័-សុក្រ (Monday - Friday)
                dateTime = this.checkMonToFriday(dateTime);
            } else if (this.form.term_condi_id == 3) {
                // ចន្ទ័-សៅរ៍ (Monday - Saturday)
                dateTime = this.checkMonToSaturday(dateTime);
            } else if (this.form.term_condi_id == 4) {
                // Monday - Sunday
                dateTime = this.checkMondayToSunday(dateTime);
            } else if (this.form.term_condi_id == 5) {
                // សៅរ៍-អាទិត្យ (Saturday - Sunday)
                dateTime = this.checkSatToSunday(dateTime);
            }
            return dateTime;
        },
        // Submit Data
        submitData() {
            this.form.loan_out = this.formatLoanOut;
            this.form.balance_principal = this.formatLoanOut;
            this.form.post("admin-api/loans").then((res) => {
                if (res.data.status == 1) {
                    this.$toast.success(res.data.message);
                    const loanStatus = res.data.data.loan_status_id;
                    if (this.is_create === true) {
                        window.location.reload();
                        this.$router.push({ name: "LoanCreate" });
                    } else {
                        if (loanStatus === 7) {
                            this.$router.push({ name: "ListRequest" });
                        } else if (loanStatus === 8) {
                            this.$router.push({ name: "ListRequestBM" });
                        } else if (loanStatus === 2) {
                            this.$router.push({ name: "ListofClientDisbursed" });
                        } else {
                            this.$router.push({ name: "LoanRequest" });
                        }
                    }
                } else {
                    this.$toast.warning(res.data.message);
                }
            }).catch((error) => {
                console.log(error);
                this.$toast.warning("An error occurred while submitting the form.");
            });
        },
    },
    computed: {
        totalPrincipal: function () {
            var sum = 0;
            this.form.rows.forEach(function (row) {
                sum += parseFloat(row.principal);
            });
            return sum;
        },
        totalInterest: function () {
            var sum = 0;
            this.form.rows.forEach(function (row) {
                sum += parseFloat(row.interestPerMonth);
            });
            return sum;
        },
        totalOperatService: function () {
            var sum = 0;
            this.form.rows.forEach(function (row) {
                sum += parseFloat(row.operatService);
            });
            return sum;
        },
        totalPayment: function () {
            var sum = 0;
            this.form.rows.forEach(function (row) {
                sum += parseFloat(row.payment_per_month);
            });
            return sum;
        },
    },
};
</script>


<style scoped>

    .table_scroll{
        height: calc(100vh - 200px)
    }

</style>
