<template>
    <div class="new_item">
        <div class="container-fluid px-0">
            <div class="row">
                <div class="col-sm-12">
                    <div class="card border-0 bg-transparent">
                        <div class="card-body border-0 bg-white rounded_8">
                            <a class="page-title text-nowrap mb-3">
                                <h5 class="text-koulen">{{ $t('Loan Reschedule') }}</h5>
                            </a>
                            <div class="menu">
                                <div class="row px-3 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') }}</label>
                                            <input type="text" class="form-control" v-model="form.client_name" disabled />
                                        </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') }}</label>
                                            <input type="text" class="form-control" v-model="form.co_name" disabled />
                                        </div>
                                    </div>
                                    <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Balance Principal') }}</label>
                                            <input type="text" disabled class="form-control" @keypress="isNumber($event)" :value="form.balance_principal | numberFomartValue" :placeholder="$t('Balance Principal')" />
                                        </div>
                                    </div>
                                    <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Balance Interest') }}</label>
                                            <input type="text" disabled class="form-control" @keypress="isNumber($event)" :value="form.balance_interest | numberFomartValue" :placeholder="$t('Balance Principal')" />
                                        </div>
                                    </div>
                                    <div class="col-xl-2 col-lg-6 col-md-6 col-12 text-nowrap">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Balance Operating Services') }}</label>
                                            <input type="text" disabled class="form-control" @keypress="isNumber($event)" :value="form.balance_risk | numberFomartValue" :placeholder="$t('Balance Operating Services')" />
                                        </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" @input="funChangeStartDate" valueType="format" :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" @input="funClearStartPayment" 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('Principal Down') }}</label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)"
                                            @blur="funPrincipalDown"
                                            @click="clickPrincipalDown"
                                            :disabled="form.principal_add>0"
                                            v-model="form.principal_down" :placeholder="$t('Principal Down')"
                                            :class="{ 'is-invalid': form.errors.has('principal_down') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('principal_down')"  v-html="form.errors.get('principal_down')">
                                            </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('Principal Add') }}</label>
                                            <input type="text" class="form-control"
                                                @keypress="isNumber($event)"
                                                v-model="form.principal_add"
                                                :disabled="form.principal_down>0"
                                                @blur="funPrincipalAdd"
                                                @input="funToClient"
                                                :placeholder="$t('Principal Add')"
                                                :class="{ 'is-invalid': form.errors.has('principal_add') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('principal_add')"  v-html="form.errors.get('principal_add')">
                                            </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('Penalty Interest') }}</label>
                                            <input type="number" min="=0" :disabled="form.principal_down == 0 && form.principal_add == 0" v-model="form.penalty_interest" @input="funInputInterest" class="form-control"  @keypress="isNumber($event)" :placeholder="$t('Penalty Interest')" :class="{ 'is-invalid': form.errors.has('penalty_interest') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('penalty_interest')" v-html="form.errors.get('penalty_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('Penalty Operating Services') }}</label>
                                            <input type="number" min="=0" :disabled="form.principal_down == 0 && form.principal_add == 0" v-model="form.penalty_risk" @input="funInputRisk" class="form-control"  @keypress="isNumber($event)" :placeholder="$t('Penalty Operating Services')" :class="{ 'is-invalid': form.errors.has('penalty_risk') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('penalty_risk')" v-html="form.errors.get('penalty_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('Payment Method') }}<span v-show="this.formatPrincipalDown>0 || this.formatTotalBalance>0"><sup class="text-danger">*</sup></span></label>
                                            <Multiselect v-model="form.payment_method" :disabled="this.formatPrincipalDown==0 && this.form.penalty_interest==0" :placeholder="$t('Payment Method')" label="chart_code_name" :class="{ 'is-invalid': form.errors.has('payment_method') }" :searchable="true" :options="payment_methods" />
                                            <div class="valid text-danger" v-if="form.errors.has('payment_method')" v-html="form.errors.get('payment_method')"></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"
                                                :placeholder="$t('Condition Pay')"
                                                @input="funChangeCondition"
                                                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:'បង់តែការប្រាក់'},
                                                ]"
                                            />
                                            <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('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('Amount Principal') }}</label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)" :value="form.total_balance | numberFomartValue"
                                            :placeholder="$t('Amount Principal')" :class="{ 'is-invalid': form.errors.has('total_balance') }" disabled />
                                            <div class="valid text-danger" v-if="form.errors.has('total_balance')"  v-html="form.errors.get('total_balance')">
                                            </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" @input="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') }} %</label>
                                            <input
                                                type="text"
                                                class="form-control"
                                                @keypress="isNumber($event)"
                                                v-model="form.risk"
                                                @input="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" disabled
                                                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('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('Service') }}%</label>
                                            <input
                                                type="number"
                                                class="form-control"
                                                @keypress="isNumber($event)"
                                                v-model="form.service"
                                                @click="clickService"
                                                :placeholder="$t('Service')"
                                                @input="funService"
                                                :disabled="form.principal_add==0"
                                                :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" disabled  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('Disbursement via') }}<sup class="text-danger">*</sup></label>
                                            <Multiselect v-model="form.chart_of_acc_id" :disabled="this.form.principal_add==0" :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>
                                    <!-- type_loan -->
                                     <!-- <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('Insurance') }}%</label>
                                            <input
                                                disabled
                                                type="text"
                                                class="form-control"
                                                @keypress="isNumber($event)"
                                                v-model="form.insurance"
                                                @click="clickInsurance"
                                                :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')" :class="{ 'is-invalid': form.errors.has('total_insurance') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('total_insurance')" v-html="form.errors.get('total_insurance')">
                                            </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('Risk') }}%</label>
                                            <input
                                                disabled
                                                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('Amount To Client') }}</label>
                                            <input type="text" class="form-control" disabled :value="form.total_to_client | numberFomartValue"/>
                                        </div>
                                    </div>
                                    <div class="col-xl-6 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 px-3 pt-2">
                                    <div class="col-12">
                                        <div class="table-responsive table_scroll">
                                            <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">សរុប</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>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import moment from 'moment';
    export default {
        props:['id'],
        data() {
            return {
                moment : moment,
                format : 'YYYY-MM-DD',
                clearFalse     : false,
                generateTrue   : true,
                holidays       : [],
                withdraw_via   : [],
                payment_methods: [],
                form: new Form({
                    id: '',
                    payment_method: '',
                    client_id: '',
                    co_id: '',
                    area_id: '',
                    chart_of_acc_id: '',
                    chart_of_acc_id: '',
                    currency_id: 1,
                    start_date:'',
                    installment_date:'',
                    interest:0,
                    risk:0,
                    total_service:0,
                    re_service:0,
                    maintenance:0,
                    loan_out:0,
                    loan_code:'',
                    service:0,
                    service_collection:0,
                    total_collection:0,
                    insurance:0,
                    total_insurance:0,
                    term_type:0,
                    term_condi: "",
                    type_loan:1,
                    period:0,
                    balance_principal:0,
                    balance_interest:0,
                    balance_risk:0,
                    condition_pay:0,
                    desc:'',
                    loan_status_id:0,
                    principal_up:0,
                    principal_down:0,
                    amount_principal:0,
                    amount_payment : 0,
                    CalculatorPrincipal:0,
                    loan_balance:0,
                    rows: [],
                    principal_add:0,
                    penalty_interest:0,
                    penalty_risk:0,
                    total_balance:0,
                    client_name : '',
                    co_name : '',
                    user_id : '',
                    total_to_client: 0,
                    AddRemoveRows  : [{id: "",number: "",date_made : "",collateral_id: "",status: 1}],
                }),
                term:'',
                formatPrincipal:0,
                formatTotalBalance:0,
                formatPrincipalDown:0,
                formatPrincipalAdd:0,
                total_service : 0,
                total_insurance : 0,
            }
        },
        created() {
            this.getLoans();
            this.getHolidays();
            this.getWithdrawVia();
            this.funPaymentMethod();
        },
        methods: {
            getHolidays(){
                axios.get("admin-api/com-holidays").then(function (response) {
                    this.holidays = response.data;
                }.bind(this));
            },
            getWithdrawVia() {
                axios.get("accounting/com-cash-bank").then((res) => {
                    this.withdraw_via = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            funPaymentMethod() {
                axios.get("accounting/com-cash-bank").then((res) => {
                    this.payment_methods = 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.form.amount_payment    = 0;
                        this.form.principal_add     = 0;
                        this.form.principal_down    = 0;
                        this.form.penalty_interest  = 0;
                        this.form.penalty_risk      = 0;
                        this.form.loan_out          = res.data.data.loan_out;
                        this.total_service          = res.data.data.total_service;
                        this.total_insurance        = res.data.data.total_insurance;
                        this.formatPrincipal        = res.data.data.balance_principal;
                        this.form.balance_principal = res.data.data.balance_principal;
                        this.form.total_balance     = res.data.data.balance_principal;
                        this.form.amount_principal  = this.formatPrincipal;
                        this.form.loan_status_id    = res.data.data.loan_status_id;
                        this.form.currency_id       = res.data.data.currency_id;
                        this.form.user_id           = res.data.user_id;
                    }
                }).catch((error) => {
                    if(error.message=='Request failed with status code 403') {
                        this.$router.push({ name: 'permissionTest' });
                    } else {
                        console.log(error.message);
                    }
                });
            },
            clickPrincipalDown() {
                this.form.principal_down = this.form.principal_down==0?'':this.form.principal_down;
            },
            funPrincipalDown() {
                this.clearRow();
                this.formatPrincipalDown = parseFloat(this.form.principal_down.replace(/[^\d\.]/g, ""));
                if (isNaN(this.formatPrincipalDown)) {
                    this.formatPrincipalDown = 0
                }
                if(this.formatPrincipalDown > this.form.balance_principal){
                    this.form.principal_down = 0;
                    this.form.amount_principal = this.form.balance_principal;
                    this.$toast.warning("Principal down can't be larger balance principal!");
                }
                else {
                    this.form.CalculatorPrincipal = this.form.balance_principal-this.formatPrincipalDown;
                    this.form.amount_principal = this.form.CalculatorPrincipal;
                    this.form.total_balance = parseFloat(this.form.CalculatorPrincipal);
                    this.form.principal_down = this.formatPrincipalDown.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                }
                this.form.principal_add = 0;
                this.form.penalty_interest = 0;
                this.form.penalty_risk = 0;
                this.form.total_to_client = 0;
            },
            funPrincipalAdd() {
                this.clearRow();
                this.formatPrincipalAdd = parseFloat(this.form.principal_add.replace(/[^\d\.]/g, ""));
                if (isNaN(this.formatPrincipalAdd)) {
                    this.formatPrincipalAdd = 0
                }
                // this.form.principal_add = this.formatPrincipalAdd.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
                this.form.CalculatorPrincipal = this.formatPrincipalAdd;

                if(this.formatPrincipalAdd > this.form.balance_principal) {
                    this.form.CalculatorPrincipal = this.form.CalculatorPrincipal
                    this.form.loan_out = this.form.CalculatorPrincipal;
                }
                else {
                    this.form.principal_add = 0;
                    this.form.CalculatorPrincipal = this.form.balance_principal;
                    //this.$toast.warning("Principal add must be larger balance principal!");
                }
                this.form.amount_principal = this.form.CalculatorPrincipal;
            },
            funToClient(e) {
                var new_disburst = e.target.value;  // New Disburstment
                var var_balance_principal = parseFloat(this.formatPrincipal);  // Balance Principal
                var var_balance_interest  = parseFloat(this.form.balance_interest); // Balance Interest

                // ************ Amount Principal ************//
                if(new_disburst > var_balance_principal) {
                    this.form.total_service   = new_disburst*(this.form.service/100);    // New total service

                    this.form.total_to_client = new_disburst - var_balance_principal - var_balance_interest - this.form.total_service;
                    this.formatTotalBalance   = parseFloat(new_disburst.replace(/[^\d\.]/g, ""))
                    if (isNaN(this.formatTotalBalance)) {this.formatPrincipalAdd
                        this.formatTotalBalance = 0
                    }
                    this.form.total_balance = this.formatTotalBalance.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");

                    this.form.penalty_interest = this.form.balance_interest;        // Show penalty interest
                    this.form.penalty_risk = this.form.balance_risk;        // Show penalty risk
                    this.form.principal_down   = 0;
                    this.form.installment_date = "";
                    this.form.start_date       = "";
                    // var varAmountBePaid = (new_disburst / this.form.period) + (new_disburst * this.form.interest / 100);
                    // this.form.amount_payment   = Math.ceil(varAmountBePaid/100)*100; // Amount payment auto
                    // this.form.total_to_client= new_disburst - var_balance_principal - var_balance_interest - this.form.total_service - this.form.total_insurance;
                }
                else {
                    this.form.total_to_client  = 0;
                    this.form.penalty_interest = 0;
                    this.form.penalty_risk = 0;
                    this.form.total_balance    = this.form.balance_principal;
                }
            },
            funService(event) {
                this.form.service = event.target.value;
                this.form.total_service = (this.form.principal_add  * this.form.service) / 100; // total service for new loan

                var var_balance_principal = parseFloat(this.form.balance_principal);  // Balance Principal
                var var_penalty_interest = parseFloat(this.form.penalty_interest);  // Penalty Interest
                var var_penalty_risk = parseFloat(this.form.penalty_risk);  // Penalty Operating Service

                if(this.form.principal_add  > var_balance_principal){
                    this.form.total_to_client = this.form.principal_add - var_balance_principal- var_penalty_interest - var_penalty_risk - this.form.total_service;
                }
            },
            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();
                }
            },
            funClearStartPayment(){
                this.clearRow();
            },
            funChangeTermType(val_term_type){
                this.clearRow();
                if(this.formatTotalBalance > 0){  // If new loan disburst > 0
                    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();
            },
            funInputInterest(e){
                this.clearRow();
                var var_penalty = e.target.value;
                var var_balance_principal = parseFloat(this.form.balance_principal);  // Balance Principal
                var var_total_service = (this.form.principal_add  * this.form.service) / 100;
                var var_penalty_risk = this.form.penalty_risk;

                if(this.formatPrincipalAdd > var_balance_principal){
                    this.form.total_to_client = this.formatPrincipalAdd - var_balance_principal - var_penalty - var_penalty_risk - var_total_service;
                }
            },
            funInputRisk(e){
                this.clearRow();
                var var_risk = e.target.value;
                var var_balance_principal = parseFloat(this.form.balance_principal);  // Balance Principal
                var var_total_service = (this.form.principal_add  * this.form.service) / 100; // service
                var var_penalty_interest = this.form.penalty_interest;

                if(this.formatPrincipalAdd > var_balance_principal){
                    this.form.total_to_client = this.formatPrincipalAdd - var_balance_principal - var_penalty_interest - var_risk - var_total_service;
                }
            },
            funChangeCondition(){
                this.clearRow();
            },
            clearRow() {
                this.form.rows = [];
                this.clearFalse = false;
                this.generateTrue = true;
            },
            generateTerm(periodInMonth) {
                if(this.form.start_date == null || this.form.start_date == '' || this.form.installment_date == null || this.form.installment_date == ''){
                    this.$toast.warning("Please check field required again!");
                }
                else {
                    this.funtypeOfPayment();
                    this.clearFalse = true;
                    this.generateTrue = false;
                    var paymentTermDay = this.form.start_date;
                    // var amountBePaid   = this.formatPayment;
                    if (this.form.currency_id == 1) {
                        if (this.form.condition_pay == 1) {
                            var checkInterest = this.form.interest;
                            if (checkInterest == 0) {
                                var amountInstallment = this.form.amount_principal;
                                var paymentEachMonth = this.form.amount_principal / 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 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: Math.ceil(paymentEachMonth + paymentRisk * rateRisk + paymentInterest * rateInterest),
                                            loan_balance: loan_balance,
                                        };
                                        this.form.rows.push(obJect);
                                    } else {
                                        var obJect = {
                                            payment_date: payment_date,
                                            principal: Math.fround(paymentEachMonth),
                                            interestPerMonth: Math.fround(paymentInterest) * Math.fround(rateInterest),
                                            riskPerMonth: rateRisk,
                                            payment_per_month: Math.ceil(paymentEachMonth + (rateRisk + paymentInterest * rateInterest)),
                                            loan_balance: 0,
                                        };
                                        this.form.rows.push(obJect);
                                    }
                                    // monthStep+=2;
                                    if (this.term == "weeks") {
                                        monthStep += 2;
                                    } else {
                                        monthStep++;
                                    }
                                }
                            }
                            else {
                                var amountInstallment = this.form.amount_principal;
                                var rateInterest = this.form.interest / 100;
                                var rateRisk = this.form.risk / 100;
                                var rateMaintenance = this.form.maintenance / 100;
                                var calcRisk = rateRisk * this.form.amount_principal;
                                var calcMaintenance = rateMaintenance * this.form.amount_principal;
                                var monthStep = 0;
                                for (var i = 1; i <= periodInMonth; i++) {
                                    var payment = Math.round((this.form.amount_principal * 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.form.amount_principal;
                            var EachMonth = this.form.amount_principal / 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.form.amount_principal;
                            var calcMaintenance = rateMaintenance * this.form.amount_principal;
                            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((amountInstallment*rateRisk) / 100) * 100;
                                var paymentMaintenance = Math.ceil((amountInstallment*rateMaintenance) / 100) * 100;
                                // var paymentRisk = Math.ceil(calcRisk / 100) * 100;
                                // var paymentMaintenance = Math.ceil(calcMaintenance / 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.form.amount_principal;
                            var amountInstallments = this.form.amount_principal;
                            var paymentEachMonth = Math.ceil(this.form.amount_principal / 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);
                                }
                                paymentTermDay = payment_date;

                                interestAmount    = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                                RiskAmount        = Math.ceil((amountInstallment * rateRisk) / 100) * 100;
                                MaintenanceAmount = Math.ceil((amountInstallment * rateMaintenance) / 100) * 100;

                                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.form.amount_principal;
                            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);
                                }
                                paymentTermDay = payment_date;

                                interestAmount      = Math.ceil((amountInstallment * rateInterest) / 100) * 100;
                                RiskAmount          = Math.ceil((amountInstallment * rateRisk) / 100) * 100;
                                MaintenanceAmount   = Math.ceil((amountInstallment * rateMaintenance) / 100) * 100;

                                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 + 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) {
                                var amountInstallment = this.form.amount_principal;
                                var paymentEachMonth = this.form.amount_principal / 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 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: rpaymentRisk * rateRisk,
                                            payment_per_month: paymentEachMonth + paymentRisk * rateRisk + paymentInterest * rateInterest,
                                            loan_balance: 0,
                                        };
                                        this.form.rows.push(obJect);
                                    }
                                    // monthStep+=2;
                                    if (this.term == "weeks") {
                                        monthStep += 2;
                                    } else {
                                        monthStep++;
                                    }
                                }
                            } else {
                                var amountInstallment = this.form.amount_principal;
                                var rateInterest = this.form.interest / 100;
                                var rateRisk = this.form.risk / 100;
                                var rateMaintenance = this.form.maintenance / 100;
                                // var calcInterest = rateInterest*this.form.amount_principal;
                                var calcRisk = rateRisk * this.form.amount_principal;
                                var calcMaintenance = rateMaintenance * this.form.amount_principal;
                                var monthStep = 0;
                                for (var i = 1; i <= periodInMonth; i++) {
                                    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.form.amount_principal * 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.form.amount_principal;
                            var paymentEachMonth = Math.ceil(((this.form.amount_principal / periodInMonth)/100)*100).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.form.amount_principal;
                            var calcMaintenance = parseFloat(rateMaintenance) * this.form.amount_principal;
                            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);
                                }
                                // monthStep+=2;
                                if (this.term == "weeks") {
                                    monthStep += 2;
                                } else {
                                    monthStep++;
                                }
                            }
                        } else if (this.form.condition_pay == 3) {
                            var amountInstallment = this.form.amount_principal;
                            var amountInstallments = this.form.amount_principal;
                            var paymentEachMonth = Math.ceil(((this.form.amount_principal / 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);
                                }
                                // monthStep+=2;
                                if (this.term == "weeks") {
                                    monthStep += 2;
                                } else {
                                    monthStep++;
                                }
                            }
                        } else {
                            var amountInstallment = this.form.amount_principal;
                            // var paymentEachMonth = this.form.amount_principal / 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);
                                }
                                interestAmount = amountInstallment * rateInterest;
                                RiskAmount = amountInstallment * rateRisk;
                                MaintenanceAmount = amountInstallment * rateMaintenance;
                                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: 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++;
                                }
                            }
                        }
                    }
                    // if(amountBePaid>0 && this.form.condition_pay!=4) {
                    //     for (var i = 0; i < this.form.rows.length; i++) {
                    //         this.form.rows[i].interestPerMonth  = amountBePaid-this.form.rows[i].principal;
                    //         this.form.rows[i].payment_per_month = amountBePaid;
                    //     }
                    // }
                }
            },
            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');
                }
            },
            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");
            },
            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;
            },
            clickInterest() {
                this.clearRow();
                this.form.interest = this.form.interest==0?'':this.form.interest;
            },
            operatingService() {
                this.clearRow();
                this.form.risk = this.form.risk == 0 ? "" : this.form.risk;
            },
            clickMaintenance(){
                this.form.maintenance = this.form.maintenance == 0 ? "" : this.form.maintenance;
            },
            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.form.amount_principal * this.form.service_collection) / 100;
            },
            clickService() {
                this.form.service = this.form.service==0?'':this.form.service;
            },
            clickInsurance(){
                this.form.insurance = this.form.insurance == 0 ? "" : this.form.insurance;
            },
            submitData() {
                this.form.balance_principal = this.form.amount_principal;
                this.form.principal_down    = this.formatPrincipalDown;
                this.form.principal_add     = this.formatPrincipalAdd;
                this.form.post("admin-api/loan-reschedule").then((res) => {
                    if (res.data.status == 1) {
                        this.$toast.success(res.data.message);
                        this.$router.push({name:'Loan'})
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                }).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>
