<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Loan List') }}
        </span>
        <template slot="more-button">
            <!-- <button type="button" v-if="$can('Transfer Loan To Branch')" @click="funTransferLoanToBranch()":disabled ="this.checkBox == ''" class="btn btn-warning me-2" :title="$t('Transfer Loan To Branch')">
                <i class="fa-solid fa-shuffle fa-sm"></i>
            </button> -->
            <button type="button" v-if="$can('Move CO')" @click="funTransferLoanInBranch()" :disabled="!checkBox || checkBox.length === 0" class="btn btn-info me-2" :title="$t('Change CO In Branch')">
                <i class="fa-solid fa-magnet fa-sm"></i>
            </button>
            <button type="button" v-if="$can('Move To Write Off')" @click="funWriteOffbycheckbox()" :disabled="!checkBox || checkBox.length === 0" class="btn btn-primary me-2" :title="$t('Move To Write Off')">
                <i class="fa-solid fa-angle-right"></i>
            </button>
            <button class="btn btn-secondary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">{{$t('Filter')}}</button>
            <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="offcanvasRightLabel">{{$t('Filter')}}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Client') }}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.client_id" trackBy="name" value="id" label="name" :searchable="true" :options="clients" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Co') }}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.co_id" trackBy="name" value="id" label="name" :searchable="true" :options="coes" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t("Term Condition")}}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.term_condi_id" trackBy="name_km" value="id" label="name_km" :searchable="true" :options="termcondition" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Status') }}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.loan_status_id" trackBy="loan_status" value="id" label="loan_status" :searchable="true"
                            :options="[{ value: 2, loan_status: $t('Approved') }, { value: 3, loan_status:$t('Pay Off') }]" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Loan Code') }}</label>
                        <input type="text" @input="Searching" class="form-control border-1" v-model="params.loan_code" :placeholder="$t('Loan Code')" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Installment Date') }}</label>
                        <div class="d-flex">
                            <date-picker class="me-1" :range="true" :placeholder="$t('Installment Date')" v-model="params.date" valueType="format" format="YYYY-MM-DD"> </date-picker>
                            <button type="button" class="btn border btn-sm text-nowrap py-0" data-bs-toggle="modal" data-bs-target="#modalFilter">
                                <i class="fas fa-sm fa-filter"></i> {{ $t('Filter') }}
                            </button>
                        </div>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" class="btn btn-success" @click="funSearchData"><i class="fa fa-search"></i> {{ $t('Search') }}</button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" @click="printP" class="btn btn-primary"><i class="fa fa-print"></i> {{ $t('Print') }}</button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" @click="exportExcell" class="btn btn-danger"><i class="fa fa-file-export"></i> {{ $t('Export') }}</button>
                    </div>
                </div>
            </div>
        </template>
        <div slot="body">
            <div id="show-print">
                <div class="table-responsive table_scroll report_print">
                    <header-report :title="$t('List of Client Disbursed')" style="display:none"></header-report>
                    <table class="table table-bordered" id="excel-table">
                        <thead class="text-nowrap fixed_table">
                            <tr>

                                <th v-if="user_branch != -1">
                                    <input type="checkbox" @click="funCheckAll()" v-model="isCheckAll" />
                                </th>
                                <th>{{ $t("#") }}</th>
                                <th class="fixed_left">
                                    <SortFilter
                                        :label="$t('Client Name')"
                                        v-model="params.sort_clientname"
                                        @change="funSortsssByCode"
                                    />
                                </th>
                                <th>
                                    <SortFilter
                                        :label="$t('Loan Code')"
                                        v-model="params.sort_code"
                                        @change="funSortsssByCode"
                                    />
                                </th>
                                <th>{{ $t("CO Name") }}</th>
                                <th>{{ $t("Installment Date") }}</th>
                                <th>{{ $t("Start Date") }}</th>
                                <th>{{ $t("Loan Out") }}</th>
                                <th>{{ $t("Total Interest") }}</th>
                                <th>{{ $t("Total Operating Services") }}</th>
                                <th class="text-success">{{ $t("Total Loan Amount") }}</th>
                                <th>{{ $t("Total Service") }}</th>
                                <!-- <th>{{ $t("Total Insurance") }}</th> -->
                                <th>{{ $t("Total Received") }}</th>
                                <th>{{ $t("Balance Principal") }}</th>
                                <th>{{ $t("Total Balance") }}</th>
                                <th>{{ $t("Duration") }}</th>
                                <th>{{ $t("Term Condition") }}</th>
                                <th>{{ $t("Total Late") }}</th>
                                <th>{{ $t("Type Payment") }}</th>
                                <th>{{ $t("Status") }}</th>
                                <th>{{ $t("Branch") }}</th>
                                <th class="d-print-none">{{ $t("Action") }}</th>
                            </tr>
                        </thead>
                        <tbody class="text-nowrap">
                            <tr v-for="(loan, index) in dataLoans.data" :key="index">
                                <td v-if="user_branch != -1">
                                    <input type="checkbox" :value="loan.id" v-model="checkBox" v-if="loan.loan_status_id==2" />
                                </td>
                                <td> {{ index + 1 }} </td>
                                <td class="fixed_left">{{ loan.client_name }}</td>
                                <td>{{ loan.loan_code }}</td>
                                <td>{{ loan.co_name }}</td>
                                <td>{{ loan.installment_date | onlyDate }}</td>
                                <td>{{ loan.start_date | onlyDate }}</td>
                                <td>{{ loan.loan_out | numberFomartValue }}</td>
                                <td>
                                    {{ loan.total_interest | numberFomartValue }}
                                    <span><sup class="text-success">({{loan.interest | numberFomartValue}}%)</sup></span>
                                </td>
                                <td>
                                    {{ loan.total_operating_service | numberFomartValue }}
                                    <span><sup class="text-success">({{loan.operating_service | numberFomartValue}}%)</sup></span>
                                </td>
                                <td>{{ loan.loan_receive | numberFomartValue }}</td>
                                <td>
                                    {{ loan.total_service | numberFomartValue }}
                                    <span><sup class="text-success">({{loan.service | numberFomartValue}}%)</sup></span>
                                </td>
                                <!-- <td>
                                    {{ loan.total_insurance | numberFomartValue }}
                                    <span><sup class="text-success">({{loan.insurance | numberFomartValue}}%)</sup></span>
                                </td> -->
                                <td>{{ loan.loan_in | numberFomartValue }}</td>
                                <td>{{ loan.balance_principal | numberFomartValue }}</td>
                                <td>{{ loan.loan_balance | numberFomartValue }}</td>
                                <td>{{ loan.period}}</td>
                                <td>{{ loan.term_condi_name}}</td>
                                <td>
                                    <span v-if="loan.total_late>0">{{ loan.total_late}}</span>
                                </td>
                                <td>{{ funConditionPay(loan.condition_pay,loan.term_type)}}</td>
                                <td>
                                    <span :style="{ 'color': loan.color }">{{loan.loan_status}}</span>
                                </td>
                                <td>{{ loan.branch_name}}</td>
                                <td class="d-print-none">
                                    <div class="dropdown actions">
                                        <button type="button" class="btn btn-success s-btn-xs" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="fa-solid fa-ellipsis fa-sm"></i>
                                        </button>
                                        <ul class="dropdown-menu shadow">
                                            <li class="dropdown-item bg-secondary text-white">
                                                <p><i class="fa-solid fa-user fa-sm me-2 text-white"></i> {{ loan.client_name }}</p>
                                            </li>


                                            <!-- ================== ផ្នែកឥណទានប្រាក់ (Loan Section) ================== -->
                                            <li>
                                                <button type="button" @click="funContractLoan(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-file-signature fa-sm me-2 text-primary"></i> {{ $t('Loan Contract') }}
                                                </button>
                                            </li>
                                            <!-- <li>
                                                <button type="button" @click="funContractLoanFixed(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-handshake fa-sm me-2 text-primary"></i> {{ $t('កិច្ចសន្យាខ្ចីប្រាក់និងប្រគល់ប្រាក់') }}
                                                </button>
                                            </li> -->
                                            <li><hr class="dropdown-divider"></li>

                                            <!-- ================== ផ្នែករថយន្ត (Vehicle Section) ================== -->
                                            <!-- <li>
                                                <button type="button" @click="funReceiptPurchaseSaleCar(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-car fa-sm me-2 text-info"></i> {{ $t('លិខិតទិញ-លក់រថយន្ត') }}
                                                </button>
                                            </li>
                                            <li>
                                                <button type="button" @click="funContractRentalCar(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-car-on fa-sm me-2 text-warning"></i> {{ $t('កិច្ចសន្យាជួលរថយន្ត') }}
                                                </button>
                                            </li>
                                            <li>
                                                <button type="button" @click="funContractTerminateRentalCar(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-ban fa-sm me-2 text-danger"></i> {{ $t('កិច្ចសន្យាពមព្រៀងបញ្ចប់ភតិសន្យា(កិច្ចសន្យាជួលរថយន្ត)') }}
                                                </button>
                                            </li>
                                            <li>
                                                <button type="button" @click="funReceiptPaymentVehicle(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-car-side fa-sm me-2 text-success"></i> {{ $t('លិខិតប្រគល់-ទទួលប្រាក់ និងរថយន្ត') }}
                                                </button>
                                            </li>
                                            <li>
                                                <button type="button" @click="funReceiptDebtCar(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-file-circle-exclamation fa-sm me-2 text-warning"></i> {{ $t('លិខិតជំពាក់ឯកសាររថយន្ត') }}
                                                </button>
                                            </li>

                                            <li><hr class="dropdown-divider"></li> -->

                                            <!-- ================== ផ្នែកដីធ្លី (Land Section) ================== -->
                                            <!-- <li>
                                                <button type="button" @click="funContractLandPurchaseSale(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-map-location-dot fa-sm me-2 text-success"></i> {{ $t('កិច្ចសន្យាទិញ-លក់ដី') }}
                                                </button>
                                            </li>
                                            <li><hr class="dropdown-divider"></li> -->
                                            <!-- ================== ផ្នែកបង្កាន់ដៃ និងបញ្ចប់កិច្ចសន្យាទូទៅ (Receipts & Terminations) ================== -->
                                            <!-- <li>
                                                <button type="button" @click="funReceiptPayment(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-money-bill-wave fa-sm me-2 text-success"></i> {{ $t('លិខិតប្រគល់- ទទួលប្រាក់') }}
                                                </button>
                                            </li>
                                            <li>
                                                <button type="button" @click="funContractTerminatPayment(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-file-circle-xmark fa-sm me-2 text-danger"></i> {{ $t('លិខិតប្រគល់និងទទួលប្រាក់រំលាយកិច្ចសន្យា') }}
                                                </button>
                                            </li>
                                            <li><hr class="dropdown-divider"></li> -->
                                            <li v-show="user_branch != -1">
                                                <router-link v-if="$can('Payment List')" :to="{ name: 'Payment',params:{id:loan.id} }" class="dropdown-item">
                                                    <i class="fa-solid fa-eye fa-sm me-2 text-success"></i> {{ $t('Show Payment') }}
                                                </router-link>
                                            </li>
                                            <li v-show="loan.loan_status_id==2 && user_branch != -1">
                                                <button type="button" v-if="$can('Pay Off')" @click="funPayOff(loan)" class="dropdown-item">
                                                    <i class="fa-brands fa-paypal fa-sm me-2 text-success"></i> {{ $t('Pay Off') }}
                                                </button>
                                            </li>
                                            <li>
                                                <router-link v-if="$can('Loan Table Schedule')" :to="{ name: 'TableSchedule',params:{id:loan.id} }" class="dropdown-item">
                                                    <i class="fa-solid fa-list fa-sm me-2 text-primary"></i> {{ $t('Schedule') }}
                                                </router-link>
                                            </li>
                                            <li v-show="loan.loan_status_id==2 && user_branch != -1 && loan.count_acc_de_not_closing ==0">
                                                <router-link v-if="$can('Loan Reschedule')" :to="{ name: 'LoanReschedule',params:{id:loan.id} }" class="dropdown-item">
                                                    <i class="fa-solid fa-file-signature fa-sm me-2 text-secondary"></i> {{ $t('Loan Schedule') }}
                                                </router-link>
                                            </li>
                                            <li v-show="loan.loan_status_id==2 && user_branch != -1">
                                                <button type="button" v-if="$can('Move CO')" @click="funMoveCo(loan)" class="dropdown-item">
                                                    <i class="fa-solid fa-magnet fa-sm me-2 text-info"></i> {{ $t('Change CO') }}
                                                </button>
                                            </li>
                                            <!-- <li>
                                                <router-link v-if="$can('History Payment')" :to="{ name: 'HistoryPayment',params:{id:loan.id} }" class="dropdown-item">
                                                    <i class="fa-solid fa-folder fa-sm me-2 text-warning"></i> {{ $t('History Payment') }}
                                                </router-link>
                                            </li>  -->
                                            <li v-show="loan.loan_status_id==2 && loan.closing_date !=null && loan.count_acc_de_not_closing ==0 && user_branch != -1">
                                                <button type="button" v-if="$can('Move To Write Off')" @click="funWriteOff(loan.id, loan.client_name)"
                                                    class="dropdown-item">
                                                 <i class="fa-solid fa-arrow-right fa-sm me-2 text-primary"></i> {{ $t('Move To Write Off') }}
                                                </button>
                                            </li>

                                            <li><hr class="dropdown-divider"></li>
                                            <!-- <li v-show="loan.loan_status_id==2 && loan.loan_in==0 && loan.closing_date==null && user_branch != -1">
                                                <button v-if="$can('Loan Request BM')" type="button" :title="$t('Return')" @click="funRequest(loan.id)" class="dropdown-item" >
                                                    <i class="fa-solid fa-arrow-left fa-sm me-2 text-warning"></i> {{$t('Return')}}
                                                </button>
                                            </li> -->
                                            <li v-show="loan.loan_status_id==2 && loan.loan_in==0 && loan.closing_date==null && user_branch != -1">
                                                <router-link v-if="$can('Loan Edit')" :to="{ name: 'LoanCreate',params:{id:loan.id} }" class="dropdown-item">
                                                    <i class="fa-solid fa-pen-to-square fa-sm me-2 text-dark"></i> {{ $t('Edit') }}
                                                </router-link>
                                            </li>
                                            <li v-show="loan.loan_status_id==2 && loan.loan_in==0 && user_branch != -1">
                                                <button type="button" v-if="$can('Loan Delete')" @click="funDelete(loan.id)" class="dropdown-item">
                                                    <i class="fa-solid fa-trash-can fa-sm me-2 text-danger"></i>{{ $t("Delete") }}
                                                </button>
                                            </li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <tr class="table-active">
                                <td :colspan="user_branch != -1?7:6" class="text-end">{{ $t("Total") }}</td>
                                <td>{{totalLoanOut | numberFomartValue}}</td>
                                <td>{{totalInterest | numberFomartValue}}</td>
                                <td>{{totalOperatService | numberFomartValue}}</td>
                                <td>{{totalLoanReceived | numberFomartValue}}</td>
                                <td>{{totalService | numberFomartValue}}</td>
                                <!-- <td>{{totalInsurance | numberFomartValue}}</td> -->
                                <td>{{totalLoanIn | numberFomartValue}}</td>
                                <td>{{totalBalancePrincipal | numberFomartValue}}</td>
                                <td>{{totalLoanBalance | numberFomartValue}}</td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td class="d-print-none"></td>
                            </tr>
                        </tbody>
                    </table>
                    <footer-report style="display:none"></footer-report>
                </div>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="dataLoans" @onChangePage="funGetData($event)"></cumstom-pagination>
        </div>

        <!--Move CO-->
        <div slot="modal-custom" v-if="user_branch">
            <form method="post" role="form">
                <div class="modal fade" id="FormMoveCo" aria-hidden="true" role="dialog" data-backdrop="static">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">{{ $t('Change CO In Branch') }}</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-6">
                                        <div class="mb-3">
                                            <label for="">{{ $t('From CO') }}</label>
                                            <input type="text" class="form-control" v-model="form.co_name" :disabled="true">
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="mb-3">
                                            <label for="">{{ $t('To CO') }}<sup class="text-danger">*</sup></label>
                                            <Multiselect
                                                v-model="form.to_co_id"
                                                :placeholder="$t('To CO')"
                                                label="name"
                                                :class="{ 'is-invalid': form.errors.has('to_co_id') }"
                                                :searchable="true"
                                                :options="toCoes"
                                            />
                                            <div class="valid text-danger" v-if="form.errors.has('to_co_id')" v-html="form.errors.get('to_co_id')"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">{{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy || form.submitting" class="btn btn-primary" @click="funSubmitMoveCo()">
                                    {{$t('Submit')}}
                                </button>
                            </div>
                            <!-- <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal"><img src="/icons/b_drop.png" alt="" /> {{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy || form.submitting" class="btn btn-primary" @click="funSubmitMoveCo()">
                                    <img :src="params.busy ? ' /icons/loading.gif ' : '/icons/save.png'" alt="" />
                                    {{$t('Submit')}}
                                </button>
                            </div> -->
                        </div>
                    </div>
                </div>
            </form>

            <form method="post" role="form">
                <div class="modal fade" id="showTransferLoanInBranch" aria-hidden="true" role="dialog" data-backdrop="static">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">{{ $t('Change CO In Branch') }}</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-12">
                                        <div class="mb-3">
                                            <label for="">{{ $t('To CO') }}<sup class="text-danger">*</sup></label>
                                            <Multiselect
                                                v-model="form.to_co_id"
                                                :placeholder="$t('To CO')"
                                                label="name"
                                                :class="{ 'is-invalid': form.errors.has('to_co_id') }"
                                                :searchable="true"
                                                :options="toCoes"
                                            />
                                            <div class="valid text-danger" v-if="form.errors.has('to_co_id')" v-html="form.errors.get('to_co_id')"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">{{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy || form.submitting" class="btn btn-primary" @click="funSubmitInBranch()">
                                    {{$t('Submit')}}
                                </button>
                            </div>
                            <!-- <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal"><img src="/icons/b_drop.png" alt="" /> {{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy || form.submitting" class="btn btn-primary" @click="funSubmitInBranch()">
                                    <img :src="params.busy ? ' /icons/loading.gif ' : '/icons/save.png'" alt="" />
                                    {{$t('Submit')}}
                                </button>
                            </div> -->
                        </div>
                    </div>
                </div>
            </form>

            <form method="post" role="form">
                <div class="modal fade" id="modalShowTransfer" aria-hidden="true" role="dialog" data-backdrop="static">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">{{$t('Transfer Loan To Branch')}}</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-6">
                                        <div class="mb-3">
                                            <label for="">{{ $t('Transfer to branch') }}<sup class="text-danger">*</sup></label>
                                            <Multiselect
                                                v-model="form.brand_id_transfer"
                                                :placeholder="$t('Transfer to branch')"
                                                label="name_km"
                                                :class="{ 'is-invalid': form.errors.has('brand_id_transfer') }"
                                                :searchable="true"
                                                :options="branchTransfer"
                                                @input="getCoBranch"
                                            />
                                            <div class="valid text-danger" v-if="form.errors.has('brand_id_transfer')" v-html="form.errors.get('brand_id_transfer')"></div>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="mb-3">
                                            <label for="">{{ $t('To CO') }}<sup class="text-danger">*</sup></label>
                                            <Multiselect
                                                v-model="form.co_id_transfer"
                                                :placeholder="$t('To CO')"
                                                label="name"
                                                :class="{ 'is-invalid': form.errors.has('co_id_transfer') }"
                                                :searchable="true"
                                                :options="coBranch"
                                            />
                                            <div class="valid text-danger" v-if="form.errors.has('co_id_transfer')" v-html="form.errors.get('co_id_transfer')"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal"><img src="/icons/b_drop.png" alt="" /> {{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy || form.submitting" class="btn btn-primary" @click="funSubmitTransferLoan()">
                                    <img :src="params.busy ? ' /icons/loading.gif ' : '/icons/save.png'" alt="" />
                                    {{$t('Submit')}}
                                </button>
                            </div> -->
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">{{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy || form.submitting" class="btn btn-primary" @click="funSubmitTransferLoan()">
                                    {{$t('Submit')}}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <custom-date-filter @chooseDate="chooseDate"></custom-date-filter>
            <pay-off-form :form="form" :payment_methods="payment_methods" @submitPayOff="subPayOff"></pay-off-form>
            <VerifyPayOff modalId="modalVerifyPayOff" :form="form" :amount_pay="form.amountPay" :currency="form.currency_name" :client_name="form.client_name" @emitPayOff="fSubmitPayOff" />
            <ContractLoan :obj="obj"></ContractLoan>
            <ContractLandPurchaseSale :obj="obj"></ContractLandPurchaseSale>
            <ContractTerminatPayment :obj="obj"></ContractTerminatPayment>
            <ReceiptPayment :obj="obj"></ReceiptPayment>
            <ContractRentalCar :obj="obj"></ContractRentalCar>
            <ContractTerminateRentalCar :obj="obj"></ContractTerminateRentalCar>
            <ReceiptDebtCar :obj="obj"></ReceiptDebtCar>
            <ReceiptPaymentVehicle :obj="obj" />
            <ContractLoanFixed :obj="obj" />
            <ReceiptPurchaseSaleCar :obj="obj"></ReceiptPurchaseSaleCar>
        </div>
    </theme-table>
</template>

<script>
    import moment from 'moment';
    import  custom from '../../custom.js';
    import SortFilter from '../../components/SortFilter.vue';
    import { exportTableToExcel } from "../../exportExcel.js";
    import ThemeTable from '../../components/ThemeTable.vue';
    import HeaderReport from '../../components/report/header.vue';
    import FooterReport from '../../components/report/footer.vue';
    import CumstomPagination from '../../components/CustomPagination.vue';
    import CustomDateFilter from '../../components/report/CustomDateFilter.vue';
    import BodyDisbursed from "./BodyDisbursed.vue";
    import PayOffForm from '../CollectionLoan/PayOffForm.vue';
    import VerifyPayOff from "../../components/VerifyPayOff.vue";
    // =================== Contract and Receipt =================== //
    import ContractLoan from "../loan/show-loan/ContractLoan.vue";
    import ContractLandPurchaseSale from "../loan/show-loan/ContractLandPurchaseSale.vue";
    import ContractTerminatPayment from "../loan/show-loan/ContractTerminatPayment.vue";
    import ReceiptPayment from "../loan/show-loan/ReceiptPayment.vue";
    import ContractRentalCar from "../loan/show-loan/ContractRentalCar.vue";
    import ContractTerminateRentalCar from "../loan/show-loan/ContractTerminateRentalCar.vue";
    import ReceiptDebtCar from "../loan/show-loan/ReceiptDebtCar.vue";
    import ReceiptPurchaseSaleCar from "../loan/show-loan/ReceiptPurchaseSaleCar.vue";
    import ContractLoanFixed from "../loan/show-loan/ContractLoanFixed.vue";
    import ReceiptPaymentVehicle from "../loan/show-loan/ReceiptPaymentVehicle.vue";
    export default {
        components: {
            ThemeTable,
            HeaderReport,
            FooterReport,
            CumstomPagination,
            CustomDateFilter,
            BodyDisbursed,
            PayOffForm,
            VerifyPayOff,
            ContractLoan,
            ContractLandPurchaseSale,
            ContractTerminatPayment,
            ReceiptPayment,
            ContractRentalCar,
            ContractTerminateRentalCar,
            ReceiptDebtCar,
            ReceiptPurchaseSaleCar,
            ReceiptPaymentVehicle,
            ContractLoanFixed,
            SortFilter,
        },
        data() {
            return {
                moment      : moment,
                dataLoans   : [],
                dataPayment : [],
                clients     : [],
                Contract    : [],
                currency    : [],
                coes        : [],
                fromCoes    : [],
                toCoes      : [],
                obj         : [],
                termcondition: [],
                user_branch : '',
                sort_clientname: "",
                sort_code: "",
                // data_disburst  : '',
                payment_methods: [],
                // Move client to each branch
                isCheckAll     : false,
                checkBox       : [],
                branchTransfer : [],
                coBranch       : [],

                form: new Form({
                    'id'             : '',
                    'name_en'        : '',
                    'name_km'        : '',
                    'phone'          : '',
                    'address'        : '',
                    'to_co_id'       : '',
                    'from_co_id'     : '',
                    'loan_id'        : '',
                    'co_name'        : '',
                    'type_move'      : '',
                    'loan_id_default': '',
                    // Payoff
                    'client_name'    : "",
                    'currency_name'  : "",
                    'payment_date'   : "",
                    'note'           : "",
                    'total_late'     : 0,
                    'sumPrincipal'   : 0,
                    'sumInterest'    : 0,
                    'sumMaintenance' : 0,
                    'penalty_payoff' : 0,
                    'amountPay'      : 0,
                    'sumOperatService' : 0,
                    'received_date'  : new Date().toISOString(),
                    'chart_of_acc_id': "",
                    'submitting'     : false,
                    // Transfer Branch
                    'brand_id_transfer' : '',
                    'co_id_transfer'    : '',
                }),
                params: {
                    search_text:'',
                    loan_code:'',
                    sort_code:'',
                    sort_clientname:'',
                    pagin : false,
                    page: 1,
                    per_page: 25,
                    check_list_loan:2,
                    client_type: 1,
                    client_id:[],
                    co_id:[],
                    term_condi_id:[],
                    loan_status_id:[],
                    date:[],
                },
            }
        },
        created() {
            this.funGetData();
            this.getClient();
            this.getCO();
            this.getFromCO();
            this.funComUserBranch();
            this.getTermCondition();
        },
        methods: {
            getClient() {
                axios.get('admin-api/com-client')
                .then((res) => {
                    this.clients = res.data
                }).catch((error) => {
                    console.log(error);
                });
            },
            getCO() {
                axios.get('admin-api/com-co')
                .then((res) => {
                    this.coes = res.data
                }).catch((error) => {
                    console.log(error);
                });
            },
            getTermCondition() {
                axios.get("admin-api/com-get-term-condition").then((res) => {
                    this.termcondition = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            funGetData(page = 1) {
                this.params.page = page;
                axios.get('admin-api/loans', {
                    params: this.params
                }).then((res) => {
                    this.dataLoans = res.data;
                }).catch((error) => {
                    if(error.message=='Request failed with status code 403') {
                        this.$router.push({ name: 'permissionTest' });
                    } else {
                        console.log(error.message);
                    }
                });
            },
            PageChange: function (e) {
                this.params.per_page = e.target.value;
                this.funGetData();
            },
            funSearchData() {
                this.params.pagin = 'true';
                this.funGetData();
            },
            Searching(e) {
                this.params.search_text = e.target.value;
                this.funGetData();
            },
            chooseDate(value){
                this.params.date = value.data;
                this.funGetData();
            },
            funSortsssByCode(newSort) {
                custom.funSortByname(this.dataLoans.data, newSort);
            },

            // Pay Off
            funPayOff(loan) {
                this.funPaymentMethod();
                $("#modalPayOff").modal("show");
                axios.get("admin-api/show-pay-all/" + loan.id).then((res) => {
                    this.form.id             = loan.id;
                    this.form.currency_name  = loan.currency_id==1?'៛':'$';
                    this.form.client_name    = loan.client_name + " - " + loan.loan_code;
                    this.form.payment_date   = res.data.payment_date;
                    this.form.total_late     = res.data.total_late;
                    this.form.sumPrincipal   = res.data.sum_principal;
                    this.form.sumInterest    = res.data.sum_interest;
                    this.form.sumOperatService = res.data.sum_operat_service;
                    this.form.sumMaintenance = res.data.sum_maintenance;
                    this.form.penalty_payoff = res.data.penalty_payoff;
                    this.form.amountPay      = this.form.sumPrincipal + this.form.sumInterest + this.form.sumOperatService + this.form.sumMaintenance + this.form.penalty_payoff;
                }).catch((error) => {
                    console.log(error);
                });
            },
            funPaymentMethod() {
                axios.get("accounting/com-cash-bank").then((res) => {
                    this.payment_methods = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            subPayOff(){
                if(this.form.received_date=='' || this.form.received_date==null || this.form.chart_of_acc_id=='' || this.form.chart_of_acc_id==null || this.form.amountPay<=0){
                    this.$toast.warning("សូមបំពេញលក្ខខណ្ឌអោយបានត្រឹមត្រូវ!");
                } else{
                    $("#modalPayOff").modal("hide");
                    $("#modalVerifyPayOff").modal("show");
                }
            },
            fSubmitPayOff(){
                if (this.form.submitting) {
                    return;
                }
                this.form.submitting = true;
                this.form = new Form({
                    'id'            : this.form.id,
                    'sumPrincipal'  : this.form.sumPrincipal,
                    'sumInterest'   : this.form.sumInterest,
                    'sumOperatService' : this.form.sumOperatService,
                    'sumMaintenance': this.form.sumMaintenance,
                    'penalty_payoff': this.form.penalty_payoff,
                    'amountPay'     : this.form.amountPay,
                    'received_date' : this.form.received_date,
                    'chart_of_acc_id': this.form.chart_of_acc_id,
                    'note': this.form.note,
                });
                this.form.post("admin-api/submit-pay-all").then((res) => {
                    if (res.data.status == 1) {
                        this.$toast.success(res.data.message);
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                    $("#modalVerifyPayOff").modal("hide");
                    this.funGetData();
                }).catch((error) => {
                    this.$toast.warning(res.data.message);
                    console.log(error);
                }).finally(() => {
                    this.form.submitting = false;
                });
            },

            // Move CO
            getFromCO() {
                axios.get('admin-api/com-co').then((res) => {
                    this.fromCoes = res.data
                }).catch((error) => {
                    console.log(error);
                });
            },
            getMoveToCO() {
                this.form.to_co_id = '';
                axios.get('admin-api/com-co-loan',{
                    params:{
                        co_id : this.form.from_co_id
                    }
                }).then((res) => {
                    this.toCoes = res.data
                }).catch((error) => {
                    console.log(error);
                });
            },
            funMoveCo(value) {
                this.form.loan_id   = value.id;
                this.form.co_name   = value.co_name;
                this.form.from_co_id= value.co_id;
                axios.get('admin-api/com-co-loan',{
                    params:{
                        co_id : value.co_id
                    }
                }).then((res) => {
                    this.toCoes = res.data
                }).catch((error) => {
                    console.log(error);
                });
                $("#FormMoveCo").modal("show");
            },
            funSubmitMoveCo()
            {
                if (this.form.submitting) {
                    return;
                }
                this.form.submitting = true;
                this.form.post("admin-api/move-co").then((res) => {
                    if (res.data.status == 1) {
                        this.form.reset();
                        this.$toast.success(res.data.message);
                        $("#FormMoveCo").modal("hide");
                        this.funGetData();
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                }).catch((error) => {
                    console.log(error);
                }).finally(() => {
                    this.form.submitting = false;
                })
            },
            // End Move CO

            // Transfer Loans
            funCheckAll: function () {
                this.checkBox = [];
                if (!this.isCheckAll) {
                    for (var val in this.dataLoans.data) {
                        if (this.dataLoans.data[val].loan_status_id == 2) {
                            this.checkBox.push(this.dataLoans.data[val].id);
                        }
                    }
                }
            },
            funTransferLoanToBranch(){
                if(this.checkBox.length==0){
                    this.$toast.warning("No data to transfer!");
                } else{
                    axios.get('admin-api/com-branch-transfer').then((res) => {
                        this.branchTransfer = res.data
                    }).catch((error) => {
                        console.log(error);
                    });
                    $("#modalShowTransfer").modal("show");
                }
            },
            getCoBranch(branch_id){
                axios.get('admin-api/com-co-by-branch',{
                        params:{
                            branch_id : branch_id
                        }
                    }).then((res) => {
                        this.coBranch = res.data
                    }).catch((error) => {
                        console.log(error);
                    });
            },
            funSubmitTransferLoan(){
                if (this.form.submitting) {
                    return;
                }
                this.form.submitting = true;
                this.form = new Form({
                    'checkArrLoan'     : this.checkBox,
                    'brand_id_transfer': this.form.brand_id_transfer,
                    'co_id_transfer'   : this.form.co_id_transfer,
                });
                this.form.post("admin-api/submit-loan-transfer").then((res) => {
                    if (res.data.status == 1) {
                        this.$toast.success(res.data.message);
                        $("#modalShowTransfer").modal("hide");
                        this.form.reset();
                        this.checkBox = [];
                        this.funGetData();
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                }).catch((error) => {
                    console.log(error);
                }).finally(() => {
                    this.form.submitting = false;
                })
            },

            // Transfer In Branch
            funTransferLoanInBranch(){
                if(this.checkBox.length==0){
                    this.$toast.warning("No data to transfer!");
                } else{
                    this.form.to_co_id = '';
                    axios.get('admin-api/com-co').then((res) => {
                        this.toCoes = res.data
                    }).catch((error) => {
                        console.log(error);
                    });
                    $("#showTransferLoanInBranch").modal("show");
                }
            },
            funSubmitInBranch(){
                if (this.form.submitting) {
                    return;
                }
                this.form.submitting = true;
                this.form = new Form({
                    'checkArrLoan' : this.checkBox,
                    'to_co_id' : this.form.to_co_id,
                });
                this.form.post("admin-api/submit-transfer-loan-in-branch").then((res) => {
                    if (res.data.status == 1) {
                        this.$toast.success(res.data.message);
                        $("#showTransferLoanInBranch").modal("hide");
                        this.checkBox = [];
                        this.form.reset();
                        this.funGetData();
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                }).catch((error) => {
                    console.log(error);
                }).finally(() => {
                    this.form.submitting = false;
                })
            },

            async exportExcell() {
                this.$isLoading(true)
                try {
                    await exportTableToExcel({
                        tableId: "excel-table",
                        filename: "ListClientDisbursed",
                        reportTitle: "បញ្ជីអតិថិជនបានបើកឥណទាន",
                        subDate:this.params.date,
                    })
                } catch (e) {
                    this.$toast.warning(e.message);
                } finally {
                    this.$isLoading(false)
                }
            },
            funTerm(status){
                if(status==1){
                    return 'ថ្ងៃ';
                }else if(status==2){
                    return 'សប្ដាហ៍';
                }else if(status==3){
                    return 'កន្លះខែ';
                }else if(status==4){
                    return 'ខែ';
                }
            },
            funConditionPay(ConPay,status){
                if(ConPay==1){
                    return 'បង់ប្រចាំ'+'-'+this.funTerm(status)+'-'+'ថេរ';
                }else if(ConPay==2){
                    return 'បង់រំលោះប្រចាំ'+'-'+this.funTerm(status)+'-'+'ថយ(ដើមថេរ)';
                }else if(ConPay==3){
                    return 'បង់ប្រាក់ដើមនិងការប្រាក់ថេរ'+'-'+this.funTerm(status);
                }else if(ConPay==4){
                    return 'បង់តែការប្រាក់ប្រចាំ'+'-'+this.funTerm(status);
                }
            },
            printP() {
                this.$htmlToPaper('show-print');
            },

            funContractLoan(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                        this.obj = {
                            loan : res.data.loan,
                            client : res.data.client,
                            garuantor1 : res.data.garuantor1,
                            garuantor2 : res.data.garuantor2,
                            garuantor3 : res.data.garuantor3,
                            realestate : res.data.realestate,
                            motos : res.data.motos,
                            other : res.data.other,
                            // company: this.company.name_kh
                            // collateral_land_first : res.data.collateral_land_first,
                            // collateral_land_second : res.data.collateral_land_second,
                            // collateral_motor_first : res.data.collateral_motor_first,
                            // collateral_motor_second : res.data.collateral_motor_second,


                        }
                        }).catch((error) => {
                            console.log(error);
                        });
                $("#showContractLoan").modal("show");
            },

            funContractLoanFixed(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                        collateral_all : res.data.collateral_all,
                        data : res.data.data,
                        currency : res.data.currency,
                        co : res.data.co,
                        countPay : res.data.countPay,
                        repre_name : res.data.repre_name,
                    }
                }).catch((error) => {
                    console.log(error);
                });
                $("#showContractLoanFixed").modal("show");
            },
            funReceiptPurchaseSaleCar(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showReceiptPurchaseSaleCar").modal("show");
            },

            funContractRentalCar(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showContractRentalCar").modal("show");
            },

            funContractTerminateRentalCar(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showContractTerminateRentalCar").modal("show");
            },

            funReceiptPaymentVehicle(id) {
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan: res.data.loan,
                        client: res.data.client,
                        garuantor1: res.data.garuantor1,
                        garuantor2: res.data.garuantor2,
                        garuantor3: res.data.garuantor3,
                        collateral_land_first: res.data.collateral_land_first,
                        collateral_land_second: res.data.collateral_land_second,
                        collateral_motor_first: res.data.collateral_motor_first,
                        collateral_motor_second: res.data.collateral_motor_second,
                        collateral_all: res.data.collateral_all,
                        data: res.data.data,
                        currency: res.data.currency,
                        co: res.data.co,
                        countPay: res.data.countPay,
                        repre_name: res.data.repre_name,
                    };
                }).catch((error) => {
                    console.log(error);
                });
                $("#showReceiptPaymentVehicle").modal("show");
            },

            funReceiptDebtCar(id){
                 axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showReceiptDebtCar").modal("show");
            },

            funContractLandPurchaseSale(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showContractLandPurchaseSale").modal("show");
            },

            funReceiptPayment(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showReceiptPayment").modal("show");
            },

            funContractTerminatPayment(id){
                axios.get("admin-api/loans/show-payment/" + id).then((res) => {
                    this.obj = {
                        loan : res.data.loan,
                        client : res.data.client,
                        garuantor1 : res.data.garuantor1,
                        garuantor2 : res.data.garuantor2,
                        garuantor3 : res.data.garuantor3,
                        collateral_land_first : res.data.collateral_land_first,
                        collateral_land_second : res.data.collateral_land_second,
                        collateral_motor_first : res.data.collateral_motor_first,
                        collateral_motor_second : res.data.collateral_motor_second,
                    }
                    }).catch((error) => {
                        console.log(error);
                    });
                $("#showContractTerminatPayment").modal("show");
            },

            funWriteOff(loan_id, client_name) {
                this.$confirm({
                    message: " Are you sure you want move " + client_name + " to write off?",
                    button: {
                        no: 'No',
                        yes: 'Yes'
                    },
                    callback: confirm => {
                        if (confirm) {
                            this.form.put("admin-api/move-to-write-off/" + loan_id).then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.funGetData();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            })
                        }
                    }
                });
            },
            funWriteOffbycheckbox() {
                const loanList = this.dataLoans?.data || [];
                if (loanList.length === 0) {
                    this.$toast.warning("Loan data not loaded");
                    return;
                }
                //  selected loans by ID
                const selectedLoans = loanList.filter(loan =>
                    this.checkBox.includes(loan.id)
                );
                //  invalid condition check
                const invalidLoans = selectedLoans.filter(loan =>
                    !(loan.loan_status_id == 2 &&
                    loan.closing_date != null &&
                    loan.count_acc_de_not_closing == 0 &&
                    this.user_branch != -1)
                );
                //  stop if any invalid
                if (invalidLoans.length > 0) {
                    const names = invalidLoans.map(l => l.client_name).join(", ");
                    this.$toast.warning(
                        `These loans cannot be moved to write off: ${names}`
                    );
                    return;
                }
                this.$confirm({
                    message: "Are you sure?",
                    button: { no: "No", yes: "Yes" },
                    callback: (confirm) => {
                        if (!confirm) return;

                        if (this.form.submitting) return;
                        this.form.submitting = true;

                        this.form = new Form({
                            checkArrLoan: this.checkBox
                        });

                        this.form.post("admin-api/move-to-write-off-multiple")
                            .then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.checkBox = [];
                                    this.funGetData();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            })
                            .catch(err => console.log(err))
                            .finally(() => {
                                this.form.submitting = false;
                            });
                    }
                });
            },
            funDelete(id) {
                this.$confirm({
                    message: 'Are you sure?',
                    button: {
                        no: 'No',
                        yes: 'Yes'
                    },
                    callback: confirm => {
                        if (confirm) {
                            this.form.delete("admin-api/loans/" + id).then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.funGetData();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            })
                        }
                    }
                });
            },
            funRequest(id) {
                this.form.status_approve = 1;
                this.$confirm({
                    message: "Are you sure?",
                    button: {
                        no: "No",
                        yes: "Yes",
                    },
                    callback: (confirm) => {
                        if (confirm) {
                            this.form.put("admin-api/loans/" + id).then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.funGetData();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            });
                        }
                    },
                });
            },
        },
        computed:{
            totalLoanOut: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.loan_out);
                });
                return sum;
            },
            totalService: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_service);
                });
                return sum;
            },
            totalCollection: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_collection);
                });
                return sum;
            },
            totalInsurance: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_insurance);
                });
                return sum;
            },
            totalSeviceCollection:function(){
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_collection);
                });
                return sum;
            },
            totalInterest: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_interest);
                });
                return sum;
            },
            totalOperatService: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_operating_service);
                });
                return sum;
            },
            totalSecurityService: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.total_maintenance);
                });
                return sum;
            },
            // totalSaving: function () {
            //     var sum = 0;
            //     this.dataLoans.data?.forEach(function (item) {
            //         sum += parseFloat(item.total_saving);
            //     });
            //     return sum;
            // },
            totalLoanReceived: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.loan_receive);
                });
                return sum;
            },
            totalLoanIn: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.loan_in);
                });
                return sum;
            },
            totalBalancePrincipal: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.balance_principal);
                });
                return sum;
            },
            totalLoanBalance: function () {
                var sum = 0;
                this.dataLoans.data?.forEach(function (item) {
                    sum += parseFloat(item.loan_balance);
                });
                return sum;
            },
        }
    }
</script>
<style scoped>
    .fixed_left{
        position: sticky;
        left: 0;
        top: 0;
        z-index: 999;
        background: var(--bs-tertiary-bg);
    }
    .fixed_left::before{
        content: '';
        position: absolute;
        left: -1px;
        top: 0;
        bottom: 0;
        border-left: 1px solid var(--bs-border-color);;
    }
    .fixed_left::after{
        content: '';
        position: absolute;
        right: -1px;
        top: 0;
        bottom: 0;
        border-left: 1px solid var(--bs-border-color);;
    }
</style>
