<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Loan Create') }}
        </span>
        <div slot="body">
            <div class="menu">
                <div class="row px-2 mb-2" v-for="(row, index) in form.AddRemoveRows" :key="row.id">
                    <!-- <div class="col px-1">
                        <input type="text" class="form-control nopadding text-center" v-model="row.number" :placeholder="$t('Collateral Number')" />
                    </div> -->
                    <div class="col px-1">
                        <date-picker v-model="row.date_made" valueType="format" :format="format" :class="{'is-invalid': form.errors.has('date_made') }" :placeholder="$t('Date')"></date-picker>
                    </div>
                    <div class="col px-1">
                        <Multiselect class="text-nowrap" style="min-width: 100px" v-model="row.collateral_id" :placeholder="$t('Collateral')" label="title" :searchable="true" :options="getFilteredCollateral(index)"/>
                    </div>
                    <div class="col px-1">
                        <div class="d-flex">
                            <select style="min-width: 100px" v-model="row.status" class="form-select text-center me-2" :disabled="true">
                                <option value="1">ដាក់ទ្រព្យកម្ចី</option>
                            </select>
                            <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 >= 5"><i class="fa-solid fa-plus"></i></button>
                        </div>
                    </div>
                </div>
                <div class="row pt-2">
                    <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')" label="name" :class="{ 'is-invalid': form.errors.has('name') }" :searchable="true" :options="clients" @search="getClient" @change="funFindCollateral" />
                            <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:'បង់ប្រាក់ថេរ'},
                                    { value: 2, condition_pay:'បង់ប្រាក់ដើមថេរ'},
                                    { value: 3, condition_pay:'បង់ប្រាក់ដើមនិងការប្រាក់ថេរ'},
                                    { value: 4, condition_pay:'បង់តែការប្រាក់'},
                                    //{ value: 5, condition_pay:'ការប្រាក់ថយចុះ'},
                                ]"
                            />
                            <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"
                                :placeholder="$t('Term Condition')"
                                trackBy="term_condi"
                                @change="changeTermCondition"
                                value="id"
                                label="term_condi"
                                :class="{ 'is-invalid': form.errors.has('term_condi') }"
                                :searchable="true"
                                :options="[
                                    { value: 1, term_condi:'ចន្ទ័-សុក្រ'},
                                    { value: 2, term_condi:'ចន្ទ័-សៅរ៍'},
                                    { value: 3, term_condi:'ចន្ទ័-អាទិត្យ'}
                                ]"
                            />
                            <div class="valid text-danger" v-if="form.errors.has('term_condi')" v-html="form.errors.get('term_condi')"></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)" @input="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('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 text-nowrap">{{ $t('Start Payment') }}<sup class="text-danger">*</sup></label>
                            <date-picker v-model="form.start_date" @input="StartPayment" 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-lg-6 col-md-6 col-12">
                        <div class="mb-3">
                            <label class="form-label">{{ $t('Loan Out') }}<sup class="text-danger">*</sup></label>
                            <input
                                type="text"
                                class="form-control"
                                @keypress="isNumber($event)"
                                @change="funChangeLoan"
                                @input="inputLoanOut"
                                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') }} %</label>
                            <input type="text" v-model="form.interest" @click="clickInterest" @input="inputInterest" 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') }} %</label>
                            <input
                                type="text"
                                class="form-control"
                                @keypress="isNumber($event)"
                                v-model="form.risk"
                                @click="operatingService"
                                :placeholder="$t('Operating Services')"
                                :class="{ 'is-invalid': form.errors.has('risk') }"
                            />
                            <div class="valid text-danger" v-if="form.errors.has('risk')" v-html="form.errors.get('risk')"></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('Security Services') }} %</label>
                            <input
                                type="text"
                                class="form-control"
                                @keypress="isNumber($event)"
                                v-model="form.maintenance"
                                @click="clickMaintenance"
                                :placeholder="$t('Security Services')"
                                :class="{ 'is-invalid': form.errors.has('maintenance') }"
                            />
                            <div class="valid text-danger" v-if="form.errors.has('maintenance')" v-html="form.errors.get('maintenance')"></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') }} %</label>
                            <input
                                type="text"
                                class="form-control"
                                @keypress="isNumber($event)"
                                v-model="form.service"
                                @click="clickService"
                                @input="funService"
                                :disabled="isDisabledService('service')"
                                :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') }}</label>
                            <input type="text" class="form-control" v-model="form.total_service"  @click="clickService" @input="funTotalService" :disabled="isDisabledService('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') }}</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') }}</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('Risk') }} %</label>
                            <input
                                type="text"
                                class="form-control"
                                @keypress="isNumber($event)"
                                v-model="form.service_collection"
                                @click="clickRisk"
                                @input="funRisk"
                                :placeholder="$t('Risk')"
                                :class="{ 'is-invalid': form.errors.has('service_collection') }"
                            />
                            <div class="valid text-danger" v-if="form.errors.has('service_collection')" v-html="form.errors.get('service_collection')"></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 Risk') }}</label>
                            <input type="text" class="form-control" disabled :value="form.total_collection | numberFomartValue" :placeholder="$t('Total Risk')" />
                        </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('Type Loan') }}<sup class="text-danger">*</sup></label>
                            <Multiselect
                                v-model="form.type_loan"
                                :placeholder="$t('Type Loan')"
                                trackBy="type_loan"
                                value="id"
                                label="type_loan"
                                :class="{ 'is-invalid': form.errors.has(['type_loan']) }"
                                :searchable="true"
                                :options="[
                                    { value: 1, type_loan: 'ID-M' },
                                    { value: 2, type_loan: 'ID-C' },
                                    { value: 3, type_loan: 'ID-L' },
                                ]"
                            />
                            <div class="valid text-danger" v-if="form.errors.has(['type_loan'])" v-html="form.errors.get(['type_loan'])"></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') }"></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" v-show="generateTrue == true">
                        <div class="mb-3">
                            <label class="form-label"><strong>{{$t('Generate')}}</strong></label>
                            <input type="button" class="form-control btn btn-success" @click="generateTerm(form.period)" value="Generate" />
                        </div>
                    </div>
                    <div class="col-xl-2 col-lg-6 col-md-6 col-12" v-show="clearFalse == true">
                        <div class="mb-3">
                            <label class="form-label"><strong>{{$t('Clear Row')}}</strong></label>
                            <input type="button" class="form-control btn btn-danger" @click="clearRow()" value="Clear Row" />
                        </div>
                    </div>
                </div>
                <div class="row pt-2">
                    <div class="col-12">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead class="text-nowrap fixed_table">
                                    <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("Security 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.riskPerMonth | numberFomartValue" class="form-control" disabled /></td>
                                        <!-- <td><input type="text" :value="row.maintenancePerMonth | 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="totalRisk | numberFomartValue" class="form-control" disabled /></td>
                                        <!-- <td><input type="text" :value="totalMaintenance | 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>
</template>

<script>
    import moment from "moment";
    import ThemeTable from "../../components/ThemeTable.vue";
import axios from "axios";
    export default {
        components: {
            ThemeTable,
        },
        props: ["id"],
        data() {
            return {
                moment        : moment,
                format        : "YYYY-MM-DD",
                term          : "",
                formatLoanOut : 0,
                clearFalse    : false,
                generateTrue  : true,
                clients       : [],
                coes          : [],
                holidays      : [],
                // collaterals   : [],
                withdraw_via  : [],
                findColalteral: [],
                checkedOptionService:null,
                form: new Form({
                    id        : "",
                    desc      : "",
                    type_loan : 1,
                    client_id : "",
                    co_id     : "",
                    installment_date  : new Date().toISOString(),
                    start_date        : new Date().toISOString(),
                    chart_of_acc_id   : "",
                    loan_status_id    : 0,
                    // Value of...
                    loan_out          : 0,
                    interest          : 0,
                    risk              : 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,
                    // Condition of...
                    period            : 0,
                    amount_payment    : 0,
                    currency_id       : "",
                    condition_pay     : "",
                    term_type         : "",
                    term_condi        : "",
                    level_loan        : "",
                    loan_code         : "",
                    rows              : [],
                    AddRemoveRows     : [{id: "",date_made : new Date().toISOString(),collateral_id: "",status: 1}],
                }),
            };
        },
        created() {
            this.getCO();
            this.getClient();
            // this.getCollateral();
            this.getHolidays();
            this.getWithdrawVia();
            this.getLoans();
        },
        methods: {
            funFindCollateral(client_id = null){
                if (client_id !== null) {
                    this.form.AddRemoveRows.collateral_id = "";
                }
                this.funGetCollateralByClient(client_id);
            },
            funGetCollateralByClient(client_id) {
                axios
                    .get("admin-api/find-collateral", { params: { client_id: client_id } })
                    .then((res) => {
                        this.findColalteral = res.data;
                    })
                    .catch((error) => {
                        console.error("Error fetching custom +:", error);
                    });
            },
            getFilteredCollateral(index) {
                // collect selected collateral_ids except current row
                const selectedIds = this.form.AddRemoveRows
                    .map((row, i) => i !== index ? row.collateral_id : null)
                    .filter(Boolean);

                // return available options
                return this.findColalteral.filter(
                    item => !selectedIds.includes(item.id)
                );
            },

            // ******************* 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.date      : នៅពេលHoliday ចាប់ទិន្នន័យពីការវាយបញ្ចូល(tbholidays)
            //          Change to => el.start.date: នៅពេលHoliday ចាប់Auto(api-calendar)
            //------------------------------------------------------------------------//
            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.date === loanDate); // (1)

                    while (index != -1) {
                        loanDate = moment(loanDate).add(1, "day").format("YYYY-MM-DD");
                        index = this.holidays.findIndex((el) => el.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.date === loanDate); // (1)
                    while (index != -1) {
                        loanDate = moment(loanDate).add(1, "day").format("YYYY-MM-DD");
                        index = this.holidays.findIndex((el) => el.date === loanDate); // (1)
                    }
                }

                if(this.form.term_condi == 1){ // ចន្ទ័-សុក្រ
                    loanDate = this.checkWeekendWithHoliday(loanDate);
                }else if(this.form.term_condi == 2){// ចន្ទ័-សៅរ៍
                    loanDate = this.checkMonToSaturday(loanDate);
                }
                return loanDate;
            },
            checkWeekendWithHoliday(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.date === dateTime.format("YYYY-MM-DD")); // (1)
                    while (index != -1) {
                        dateTime = moment(dateTime).add(1, "day");
                        index = this.holidays.findIndex((el) => el.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.date === dateTime.format("YYYY-MM-DD")); // (1)
                    while (index != -1) {
                        dateTime = moment(dateTime).add(1, "day");
                        index = this.holidays.findIndex((el) => el.date === dateTime.format("YYYY-MM-DD")); // (1)
                    }
                    day = dateTime.day();
                }
                return dateTime.format("YYYY-MM-DD");
            },
            getCO() {
                axios.get("admin-api/com-co").then((res) => {
                    this.coes = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            getClient() {
                axios.get("admin-api/client-and-code").then((res) => {
                    this.clients = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            // getCollateral() {
            //     axios.get("/admin-api/com-collaterals").then((res) => {
            //         this.collaterals = res.data;
            //     }).catch((err) => console.log(err));
            // },
            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) {
                        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.form.currency_id = res.data.currency_id;
                }).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 : new Date().toISOString(),collateral_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;
            },
            StartPayment() {
                this.clearRow();
            },
            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():'';
            },
            changeTermCondition(){
                this.clearRow();
            },
            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;
            },
           funChangeLoan(e){
                this.form.loan_out = e.target.value;
                this.formatLoanOut = e.target.value;
                this.form.total_service = Math.ceil(this.formatLoanOut * this.form.service) / 100;

                if(this.form.currency_id == 1){
                    this.form.total_service = Math.round(this.form.total_service/100)*100;
                }
                else{
                    this.form.total_service = parseFloat(this.form.total_service).toFixed(2);
                }
            },
            inputLoanOut(e){
                this.clearRow();
                this.form.loan_out = e.target.value;
                this.formatLoanOut =  e.target.value;
                this.form.total_service = Math.ceil(this.formatLoanOut * this.form.service) / 100;

                if(this.form.currency_id == 1){
                    this.form.total_service = Math.round(this.form.total_service/100)*100;
                }else{
                    this.form.total_service = parseFloat(this.form.total_service).toFixed(2);
                }
            },
            // Administrative Service
            isDisabledService(option) {
                return this.checkedOptionService !== null && this.checkedOptionService !== option;
            },
            handleChangeService(option) {
                if (this.form[option] !== null && this.form[option] !== "") {
                    this.checkedOptionService = option;
                } else {
                    this.checkedOptionService = null
                }
            },
            funService(event) {
                if (this.formatLoanOut <= 0) {
                    this.$toast.warning("Please input loan out first!");
                    this.form.service = 0;
                    this.form.total_service = 0;
                } else {
                    this.form.service = event.target.value;
                    this.form.total_service = parseFloat((this.formatLoanOut * this.form.service) / 100 .toFixed(2));
                    this.handleChangeService('service')
                }
            },
            funTotalService(event){
               if(event){
                if(this.formatLoanOut <= 0){
                    this.$toast.warning("Please input loan out first!");
                    this.form.service = 0;
                    this.form.total_service = 0;
                }else{
                    this.form.total_service = event.target.value;
                    this.form.service = parseFloat(((this.form.total_service * 100) / this.formatLoanOut).toFixed(2));
                    this.handleChangeService('total_service')
                }
               }
            },
            clickInterest() {
                this.clearRow();
                this.form.interest = this.form.interest == 0 ? "" : this.form.interest;
            },
            operatingService() {
                this.form.risk = this.form.risk == 0 ? "" : this.form.risk;
            },
            clickMaintenance(){
                this.form.maintenance = this.form.maintenance == 0 ? "" : this.form.maintenance;
            },

            inputInterest(event){
                this.form.interest = event.target.value;
                var varAmountBePaid= (this.formatLoanOut / this.form.period) + (this.formatLoanOut * this.form.interest / 100);
                this.form.amount_payment = Math.ceil(varAmountBePaid/100)*100;
                this.formatPayment = Math.ceil(varAmountBePaid/100)*100;
            },
            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;
            },
            funRisk(e) {
                this.form.service_collection = e.target.value;
                this.form.total_collection = (this.formatLoanOut * this.form.service_collection) / 100;
            },
            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;

                if (this.form.currency_id == 1) {
                    // ************ បង់ប្រាក់ថេរ ************ //
                    if (this.form.condition_pay == 1) {
                        var checkInterest = this.form.interest;
                        if (checkInterest == 0) {
                            var amountInstallment = this.formatLoanOut;
                            var paymentEachMonth  = this.formatLoanOut / periodInMonth;
                            var rateInterest      = this.form.interest / 100;
                            var rateRisk          = this.form.risk / 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 {
                                    var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                                }
                                paymentTermDay = payment_date;

                                var paymentInterest   = amountInstallment;
                                var paymentRisk       = amountInstallment;
                                var paymentMaintenance= amountInstallment;

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

                                if (i != periodInMonth) {
                                    var payment_interest    = paymentInterest * rateInterest;
                                    var payment_risk        = paymentRisk * rateRisk;
                                    var payment_maintenance = paymentMaintenance * rateMaintenance;

                                    var obJect = {
                                        payment_date       : payment_date,
                                        principal          : paymentEachMonth,
                                        interestPerMonth   : payment_interest,
                                        riskPerMonth       : payment_risk,
                                        maintenancePerMonth: payment_maintenance,
                                        payment_per_month  : Math.ceil(paymentEachMonth + payment_interest + payment_risk + payment_maintenance),
                                        loan_balance       : loan_balance,
                                    };
                                    this.form.rows.push(obJect);
                                }
                                else {
                                    var payment_interest    = Math.fround(amountInstallment) * Math.fround(rateInterest);
                                    var payment_risk        = Math.fround(amountInstallment) * Math.fround(rateRisk);
                                    var payment_maintenance = Math.fround(amountInstallment) * Math.fround(rateMaintenance);

                                    var obJect = {
                                        payment_date        : payment_date,
                                        principal           : Math.fround(paymentEachMonth),
                                        interestPerMonth    : payment_interest,
                                        riskPerMonth        : payment_risk,
                                        maintenancePerMonth : payment_maintenance,
                                        payment_per_month   : Math.ceil(paymentEachMonth + payment_interest + payment_risk +payment_maintenance),
                                        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 rateRisk          = this.form.risk / 100;
                            var rateMaintenance   = this.form.maintenance / 100;
                            var calcRisk          = rateRisk * this.formatLoanOut;
                            var calcMaintenance   = rateMaintenance * this.formatLoanOut;
                            var monthStep = 0;

                            for (var i = 1; i <= periodInMonth; i++) {
                                var payment               = Math.round((this.formatLoanOut * rateInterest) / (1 - Math.pow(1 + rateInterest, -periodInMonth)));
                                var payment_per_month     = Math.round(payment / 100) * 100;
                                var interest_per_month    = Math.round((amountInstallment * rateInterest)/100)*100;
                                var risk_per_month        = Math.round(calcRisk/100)*100;
                                var maintenance_per_month = Math.round(calcMaintenance/100) * 100;

                                var principal             = payment_per_month - interest_per_month;
                                var loan_balance          = amountInstallment - principal;
                                amountInstallment         = amountInstallment - principal;
                                if (this.term == "day") {
                                    var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                                } 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           : principal,
                                        interestPerMonth    : interest_per_month,
                                        riskPerMonth        : risk_per_month,
                                        maintenancePerMonth : maintenance_per_month,
                                        payment_per_month   : payment_per_month + risk_per_month + 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,
                                        riskPerMonth        : risk_per_month,
                                        maintenancePerMonth : maintenance_per_month,
                                        payment_per_month   : parseFloat(payment_per_month) + parseFloat(amountInstallment) + parseFloat(risk_per_month) + 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 rateRisk         = this.form.risk / 100;
                        var rateMaintenance  = this.form.maintenance / 100;
                        // var calcRisk         = rateRisk * this.formatLoanOut;
                        var calcMaintenance  = 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 {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }

                            paymentTermDay = payment_date;

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

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

                            if (i != periodInMonth) {
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : paymentEachMonth,
                                    interestPerMonth    : paymentInterest,
                                    riskPerMonth        : paymentRisk,
                                    maintenancePerMonth : paymentMaintenance,
                                    payment_per_month   : paymentEachMonth + paymentRisk + paymentInterest + paymentMaintenance,
                                    loan_balance        : loan_balance,
                                };
                                this.form.rows.push(obJect);
                            } else {
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : amountInstallment + paymentEachMonth,
                                    interestPerMonth    : paymentInterest,
                                    riskPerMonth        : paymentRisk,
                                    maintenancePerMonth : paymentMaintenance,
                                    payment_per_month   : paymentEachMonth + paymentRisk + 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 rateRisk           = this.form.risk / 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 {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            interestAmount      = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                            RiskAmount          = Math.ceil((amountInstallment * rateRisk) / 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,
                                    riskPerMonth       : RiskAmount,
                                    maintenancePerMonth: MaintenanceAmount,
                                    payment_per_month  : paymentEachMonth + interestAmount + RiskAmount + MaintenanceAmount,
                                    loan_balance       : loan_balance,
                                };
                                this.form.rows.push(obJect);
                            }
                            else {
                                var obJect = {
                                    payment_date       : payment_date,
                                    principal          : amountInstallments + paymentEachMonth,
                                    interestPerMonth   : interestAmount,
                                    riskPerMonth       : RiskAmount,
                                    maintenancePerMonth: MaintenanceAmount,
                                    payment_per_month  : paymentEachMonth + interestAmount + RiskAmount + 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 rateRisk          = this.form.risk / 100;
                        var rateMaintenance   = this.form.maintenance / 100;
                        var monthStep         = 0;
                        var interestAmount    = 0;
                        var RiskAmount        = 0;
                        var MaintenanceAmount = 0;

                        for (var i = 1; i <= periodInMonth; i++) {
                            if (this.term == "day") {
                                var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                            } else {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            interestAmount     = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                            RiskAmount         = Math.ceil((amountInstallment * rateRisk) / 100) * 100;
                            MaintenanceAmount  = Math.ceil((amountInstallment * rateMaintenance) / 100) * 100;
                            paymentTermDay     = payment_date;
                            var paymentInterest= amountInstallment;
                            var loan_balance   = amountInstallment;
                            amountInstallment  = amountInstallment;

                            if (i != periodInMonth) {
                                var obJect = {
                                    payment_date       : payment_date,
                                    principal          : 0,
                                    interestPerMonth   : interestAmount,
                                    riskPerMonth       : RiskAmount,
                                    maintenancePerMonth: MaintenanceAmount,
                                    payment_per_month  : interestAmount + RiskAmount + MaintenanceAmount,
                                    loan_balance       : loan_balance,
                                };
                                this.form.rows.push(obJect);
                            } else {
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : amountInstallment,
                                    interestPerMonth    : interestAmount,
                                    riskPerMonth        : RiskAmount,
                                    maintenancePerMonth : MaintenanceAmount,
                                    payment_per_month   : interestAmount + RiskAmount + MaintenanceAmount + parseFloat(amountInstallment),
                                    loan_balance        : 0,
                                };
                                this.form.rows.push(obJect);
                            }
                            if (this.term == "weeks") {
                                monthStep += 2;
                            } else {
                                monthStep++;
                            }
                        }
                    }
                }
                else {
                    if (this.form.condition_pay == 1) {
                        var checkInterest = this.form.interest;
                        if (checkInterest == 0) {
                            this.$toast.warning("Please Input Interest First !");
                            // var amountInstallment = this.formatLoanOut;
                            // var paymentEachMonth = this.formatLoanOut / periodInMonth;
                            // var rateInterest = this.form.interest / 100;
                            // var rateRisk = this.form.risk / 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 {
                            //         var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            //     }
                            //     paymentTermDay = payment_date;

                            //     var paymentInterest    = amountInstallment;
                            //     var paymentRisk        = 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,
                            //             riskPerMonth      : paymentRisk * rateRisk,
                            //             payment_per_month : paymentEachMonth + paymentRisk * rateRisk + paymentInterest * rateInterest,
                            //             loan_balance      : loan_balance,
                            //         };
                            //         this.form.rows.push(obJect);
                            //     } else {
                            //         var obJect = {
                            //             payment_date      : payment_date,
                            //             principal         : paymentEachMonth,
                            //             interestPerMonth  : paymentInterest * rateInterest,
                            //             riskPerMonth      : paymentRisk * rateRisk,
                            //             payment_per_month : paymentEachMonth + paymentRisk * rateRisk + 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 rateRisk = this.form.risk / 100;
                            var rateMaintenance = this.form.maintenance / 100;
                            // var calcInterest = rateInterest*this.formatLoanOut;
                            var calcRisk = rateRisk * this.formatLoanOut;
                            var calcMaintenance = rateMaintenance * this.formatLoanOut;
                            var monthStep = 0;
                            for (var i = 1; i <= periodInMonth; i++) {

                                var payment        = parseFloat((this.formatLoanOut * rateInterest) / (1 - Math.pow(1 + rateInterest, -periodInMonth))).toFixed(2);
                                var amount_payment     = parseFloat(payment).toFixed(2);
                                var interest_per_month    = parseFloat(amountInstallment * rateInterest).toFixed(2);
                                var risk_per_month        = parseFloat(calcRisk).toFixed(2);

                                var principal             = amount_payment - interest_per_month;
                                var loan_balance          = amountInstallment - principal;
                                amountInstallment         = amountInstallment - principal;

                                if (this.term == "day") {
                                    var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                                } 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).toFixed(2),
                                        interestPerMonth    : parseFloat(interest_per_month).toFixed(2),
                                        riskPerMonth        : parseFloat(risk_per_month),
                                        maintenancePerMonth : 0,// no maintenancePerMonth
                                        payment_per_month   : (parseFloat(amount_payment) + parseFloat(risk_per_month)).toFixed(2),
                                        loan_balance        : parseFloat(loan_balance).toFixed(2),
                                    };
                                    this.form.rows.push(obJect);
                                } else{
                                    var interest = parseFloat((amountInstallment + principal) * rateInterest).toFixed(2);
                                    var obJect = {
                                        payment_date        : payment_date,
                                        principal           : (parseFloat(amountInstallment) + parseFloat(principal)).toFixed(2),
                                        interestPerMonth    : parseFloat(interest).toFixed(2),
                                        riskPerMonth        : parseFloat(risk_per_month).toFixed(2),
                                        maintenancePerMonth: 0,// no maintenancePerMonth
                                        payment_per_month   : (parseFloat(amount_payment) + parseFloat(amountInstallment) + parseFloat(risk_per_month)).toFixed(2),
                                        loan_balance        : 0,
                                    };
                                    this.form.rows.push(obJect);
                                }

                                // var interest_per_month = parseFloat(amountInstallment) * parseFloat(rateInterest);
                                // interest_per_month = parseFloat(interest_per_month).toFixed(2);
                                // var risk_per_month = 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(risk_per_month) + parseFloat(maintenance_per_month) + parseFloat(payment);
                                // var total_principal = parseFloat(payment_per_month) - parseFloat(interest_per_month) - parseFloat(risk_per_month) - 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 {
                                //     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),
                                //         riskPerMonth        : parseFloat(risk_per_month),
                                //         maintenancePerMonth : parseFloat(maintenance_per_month),
                                //         payment_per_month   : parseFloat(principal) + parseFloat(interest_per_month) + parseFloat(risk_per_month) + 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),
                                //         riskPerMonth        : parseFloat(risk_per_month),
                                //         maintenancePerMonth : parseFloat(maintenance_per_month),
                                //         payment_per_month   : parseFloat(principal) + parseFloat(amountInstallment) + parseFloat(interest_per_month) + parseFloat(risk_per_month) + 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 = Math.ceil(((this.formatLoanOut / periodInMonth)/100)*100).toFixed(2);
                        var rateInterest = this.form.interest / 100;
                        var rateRisk = this.form.risk / 100;
                        var rateMaintenance = parseFloat(this.form.maintenance / 100).toFixed(2);
                        var calcRisk = rateRisk * 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 {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            paymentTermDay = payment_date;

                            var paymentInterest    = amountInstallment * rateInterest;
                            paymentInterest        = parseFloat(paymentInterest).toFixed(2);
                            var paymentRisk        = 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),
                                    riskPerMonth        : parseFloat(paymentRisk),
                                    maintenancePerMonth : parseFloat(paymentMaintenance),
                                    payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentRisk) + parseFloat(paymentMaintenance),
                                    loan_balance        : loan_balance,
                                };
                                this.form.rows.push(obJect);
                            }
                            else {
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : parseFloat(paymentEachMonth) + parseFloat(amountInstallment),
                                    interestPerMonth    : paymentInterest,
                                    riskPerMonth        : parseFloat(paymentRisk),
                                    maintenancePerMonth : parseFloat(paymentMaintenance),
                                    payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentMaintenance) + parseFloat(paymentRisk) + 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 = Math.ceil(((this.formatLoanOut / periodInMonth)/100)*100).toFixed(2);
                        var rateInterest = this.form.interest / 100;
                        var rateRisk = this.form.risk / 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 {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            interestAmount = parseFloat(amountInstallment * rateInterest).toFixed(2);
                            RiskAmount = parseFloat(amountInstallment * rateRisk).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),
                                    riskPerMonth        : parseFloat(RiskAmount),
                                    maintenancePerMonth : parseFloat(MaintenanceAmount),
                                    payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(interestAmount) + parseFloat(RiskAmount) + 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),
                                    riskPerMonth        : parseFloat(RiskAmount),
                                    maintenancePerMonth : parseFloat(MaintenanceAmount),
                                    payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(interestAmount) + parseFloat(MaintenanceAmount) + parseFloat(RiskAmount) + parseFloat(amountInstallments),
                                    loan_balance        : 0,
                                };
                                this.form.rows.push(obJect);
                            }
                            if (this.term == "weeks") {
                                monthStep += 2;
                            } else {
                                monthStep++;
                            }
                        }
                    }
                    else if(this.form.condition_pay == 4){
                        var amountInstallment = this.formatLoanOut;
                        // var paymentEachMonth = this.formatLoanOut / periodInMonth;
                        var rateInterest = this.form.interest / 100;
                        var rateRisk = this.form.risk / 100;
                        var rateMaintenance = this.form.maintenance / 100;
                        var monthStep = 0;
                        var interestAmount = 0;
                        var RiskAmount = 0;
                        var MaintenanceAmount = 0;
                        var MaintenanceAmount = 0;
                        for (var i = 1; i <= periodInMonth; i++) {
                            if (this.term == "day") {
                                var payment_date = this.checkHoliday(this.term, paymentTermDay, monthStep);
                            } else {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            paymentTermDay    = payment_date;
                            interestAmount    = amountInstallment * rateInterest;
                            RiskAmount        = amountInstallment * rateRisk;
                            MaintenanceAmount = amountInstallment * rateMaintenance;

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

                            if (i != periodInMonth) {
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : 0,
                                    interestPerMonth    : interestAmount,
                                    riskPerMonth        : RiskAmount,
                                    maintenancePerMonth : MaintenanceAmount,
                                    payment_per_month   : interestAmount + RiskAmount + MaintenanceAmount,
                                    loan_balance        : loan_balance,
                                };
                                this.form.rows.push(obJect);
                            }
                            else {
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : parseFloat(amountInstallment),
                                    interestPerMonth    : parseFloat(interestAmount),
                                    riskPerMonth        : parseFloat(RiskAmount),
                                    maintenancePerMonth : parseFloat(MaintenanceAmount),
                                    payment_per_month   : parseFloat(interestAmount) + parseFloat(RiskAmount) + parseFloat(MaintenanceAmount) + parseFloat(amountInstallment),
                                    loan_balance        : 0,
                                };
                                this.form.rows.push(obJect);
                            }
                            if (this.term == "weeks") {
                                monthStep += 2;
                            } else {
                                monthStep++;
                            }
                        }
                    }else{
                        var amountInstallment = this.formatLoanOut;
                        var paymentEachMonth = Math.floor(this.formatLoanOut / periodInMonth).toFixed(2);
                        var rateInterest = this.form.interest / 100;
                        var rateRisk = parseFloat(this.form.risk / 100).toFixed(2);
                        var rateMaintenance = parseFloat(this.form.maintenance / 100).toFixed(2);
                        var calcRisk = parseFloat(rateRisk) * 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 {
                                var payment_date = this.checkHoliday(this.term, this.form.start_date, monthStep);
                            }
                            paymentTermDay = payment_date;

                            var paymentInterest    = amountInstallment * rateInterest;
                            paymentInterest        = parseFloat(paymentInterest).toFixed(2);
                            var paymentRisk        = parseFloat(calcRisk).toFixed(2);
                            var paymentMaintenance = parseFloat(calcMaintenance).toFixed(2);
                            var loan_balance  = amountInstallment - paymentEachMonth;
                            amountInstallment = amountInstallment - paymentEachMonth;

                            if(i==1){
                                var obJect = {
                                    payment_date        : payment_date,
                                    principal           : parseFloat(paymentEachMonth) ,
                                    interestPerMonth    : paymentInterest,
                                    riskPerMonth        : parseFloat(paymentRisk),
                                    maintenancePerMonth : parseFloat(paymentMaintenance),
                                    payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentMaintenance) + parseFloat(paymentRisk),
                                    loan_balance        : loan_balance,
                                };
                            this.form.rows.push(obJect);
                            }
                            // if(i != periodInMonth){
                            //     var obJect = {
                            //         payment_date        : payment_date,
                            //         principal           : parseFloat(paymentEachMonth) ,
                            //         interestPerMonth    : paymentInterest,
                            //         riskPerMonth        : parseFloat(paymentRisk),
                            //         maintenancePerMonth : parseFloat(paymentMaintenance),
                            //         payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentMaintenance) + parseFloat(paymentRisk),
                            //         loan_balance        : loan_balance,
                            //     };
                            //     this.form.rows.push(obJect);
                            // }
                            // else{
                            //      var obJect = {
                            //         payment_date        : payment_date,
                            //         principal           : parseFloat(paymentEachMonth),
                            //         interestPerMonth    : parseFloat(paymentInterest),
                            //         riskPerMonth        : parseFloat(paymentRisk),
                            //         maintenancePerMonth : parseFloat(paymentMaintenance),
                            //         payment_per_month   : parseFloat(paymentEachMonth) + parseFloat(paymentInterest) + parseFloat(paymentRisk) + parseFloat(paymentMaintenance),
                            //         loan_balance        : 0,
                            //     };
                            //     this.form.rows.push(obJect);
                            // }
                            if (this.term == "weeks") {
                                monthStep += 2;
                            } else {
                                monthStep++;
                            }
                        }
                    }
                }
            },
            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);
                        if (res.data.data.loan_status_id == 1) {
                            window.location.reload();
                        } else {
                            this.$router.push({ name: "Loan" });
                        }
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                    this.form.loan_out = 0;
                }).catch((error) => {
                    console.log(error);
                    this.$toast.warning(res.data.message);
                });
            },
        },
        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;
            },
            totalRisk: function () {
                var sum = 0;
                this.form.rows.forEach(function (row) {
                    sum += parseFloat(row.riskPerMonth);
                });
                return sum;
            },
            totalMaintenance: function () {
                var sum = 0;
                this.form.rows.forEach(function (row) {
                    sum += parseFloat(row.maintenancePerMonth);
                });
                return sum;
            },
            totalPayment: function () {
                var sum = 0;
                this.form.rows.forEach(function (row) {
                    sum += parseFloat(row.payment_per_month);
                });
                return sum;
            },
        },
    };
</script>
