<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Collect Good Loan') }}
        </span>
        <template slot="more-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('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('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('Village') }}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.village_id" trackBy="full_name_km" value="id" label="full_name_km" :searchable="true" :options="villages" />
                    </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('Collect Good Loan')" style="display: none;"></header-report>
                    <table class="table table-bordered" id="excel-table">
                        <thead class="text-nowrap fixed_table">
                            <tr>
                                <th>{{ $t("#") }}</th>
                                <th>{{ $t("Payment Today") }}</th>
                                <th>{{ $t("Client") }}</th>
                                <th>{{ $t("Phone") }}</th>
                                <th>{{ $t("Village") }}</th>
                                <th>{{ $t("CO") }}</th>
                                <th>{{ $t("Loan Code") }}</th>
                                <th>{{ $t("Loan Out") }}</th>
                                <th>{{ $t("Balance Principal") }}</th>
                                <th>{{ $t("Loan Balance") }}</th>
                                <th class="d-print-none">{{ $t("Action") }}</th>
                            </tr>
                        </thead>
                        <tbody class="text-nowrap">
                            <tr v-for="(acc, index) in collectionData.data" :key="index">
                                <td>{{ index+1}}</td>
                                <td width="5%">
                                    <button type="button" v-if="$can('Repay')" @click="funRepay(acc)" :title="$t('Repay')" class="btn btn-success s-btn-xs rounded-pill fw-bold">
                                        <i class="fa-solid fa-money-bill-transfer fa-sm"></i> {{ acc.unreceived | numberFomartValue }}
                                    </button>
                                </td>
                                <td class="fw-bold" style="color:#0303f3">{{ acc.client_name}}</td>
                                <td>{{ acc.client_phone}}</td>
                                <td>{{ acc.village}}</td>
                                <td>{{ acc.co_name}}</td>
                                <td>{{ acc.loan_code}}</td>
                                <td>{{ acc.loan_out | numberFomartValue }}</td>
                                <td>{{ acc.balance_principal | numberFomartValue }}</td>
                                <td>{{ acc.total_loan_balance | numberFomartValue }}</td>
                                <td width="5%" class="d-print-none">
                                    <router-link v-if="$can('History Payment')" :to="{ name: 'HistoryPayment',params:{id:acc.loan_id} }" :title="$t('History Payment')" class="btn btn-info s-btn-xs">
                                        <i class="fa-solid fa-calendar-days fa-sm"></i>
                                    </router-link>
                                    <button type="button" v-if="$can('Pay Off')" @click="funPayOff(acc)" :title="$t('Pay Of')" class="btn btn-primary s-btn-xs">
                                        <i class="fa-brands fa-paypal fa-sm"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <footer-report style="display: none;"></footer-report>
                </div>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="collectionData" @onChangePage="funGetData($event)"></cumstom-pagination>
        </div>
        <div slot="modal-custom">
            <!-- Repayment -->
            <repayment-form :form="form" :payment_methods="payment_methods" @submitRepay="subRepayment"></repayment-form>
            <VerifyRepayment modalId="modalVerify" :form="form" :amount_pay="form.amount_repay" :currency="form.currency_name" @submit="fSubmitData" />
            <!-- Pay Off -->
            <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" @emitPayOff="fSubmitPayOff" />
        </div>
    </theme-table>
</template>
<script>
    import moment from "moment";
    import CumstomPagination from "../../components/CustomPagination.vue";
    import HeaderReport from "../../components/report/header.vue";
    import FooterReport from "../../components/report/footer.vue";
    import ThemeTable from "../../components/ThemeTable.vue";
    // Repayment
    import RepaymentForm from "./RepaymentForm.vue";
    import VerifyRepayment from "../../components/VerifyRepayment.vue";
    // PayOff
    import PayOffForm from "./PayOffForm.vue";
    import VerifyPayOff from "../../components/VerifyPayOff.vue";
    import { exportTableToExcel } from "../../exportExcel.js"
    
    export default {
        components: {
            CumstomPagination,
            HeaderReport,
            FooterReport,
            ThemeTable,
            // Repayment
            RepaymentForm,
            VerifyRepayment,
            // PayOff
            PayOffForm,
            VerifyPayOff
        },
        data() {
            return {
                moment  : moment,
                format  : "YYYY-MM-DD",
                clients : [],
                coes    : [],
                villages: [],
                payment_methods: [],
                collectionData : {data:[]},
                form: new Form({
                    // Repayment & payOff
                    id: "",
                    currency_name : "",
                    amount_repay  : 0,
                    total_penalty : 0,
                    paid_penalty  : 0,
                    waiv_penalty  : 0,
                    // unpaid_penalty: 0,
                    total_late_day: 0,
                    // payoff
                    sumPrincipal  : 0,
                    sumInterest   : 0,
                    sumRisk       : 0,
                    sumMaintenance: 0,
                    penalty_payoff: 0,
                    amountPay     : 0,
                    // show
                    client_name   : "",
                    loan_code     : "",
                    payment_date  : "",
                    payment       : 0,
                    principal     : 0,
                    interest      : 0,
                    unreceived    : 0,

                    chart_of_acc_id : '',
                    received_date : new Date().toISOString(),
                    submitting : false,
                }),
                params: {
                    page: 1,
                    per_page: 25,
                    search_text: "",
                    pagin: false,

                    client_id : [],
                    co_id : [],
                    village_id:[],
                    client_type: 1,
                },
            };
        },
        created() {
            this.funGetData();
            this.getClient();
            this.getCO();
            this.getVillage();
        },
        methods: {
            async exportExcell() {
                this.$isLoading(true)
                try {
                    await exportTableToExcel({
                        tableId: "excel-table",
                        filename: "CollectGoodLoan",
                        reportTitle: "ប្រមូលពីកម្ចីល្អ",
                        subDate:this.params.date,
                    })
                } catch (e) {
                    this.$toast.warning(e.message);
                } finally {
                    this.$isLoading(false)
                }
            },
            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);
                });
            },
            getVillage() {
                axios.get("admin-api/com-village-client").then((res) => {
                    this.villages = 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);
                });
            },
            funGetData(page = 1) {
                this.params.page = page;
                axios
                    .get("admin-api/collect-good-loan", {
                        params: this.params,
                    })
                    .then((res) => {
                        this.collectionData = 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();
            },
            printP() {
                this.$htmlToPaper("show-print");
            },

            // Repayment
            funRepay(data) {
                this.form.id = data.id;
                this.form.chart_of_acc_id = '';
                this.form.currency_name= data.currency_id==1?'៛':'$';
                this.form.client_name  = data.client_name + " - " + data.loan_code;
                this.form.unreceived   = data.unreceived;
                this.form.payment_date = data.payment_date;
                this.form.received     = data.received;
                this.form.principal    = data.principal;
                this.form.payment      = data.payment_per_month;
                this.form.interest     = data.interest_per_month;
                this.form.risk         = data.risk_per_month;
                this.form.maintenance  = data.maintenance_per_month;
                this.form.paid_penalty = data.total_penalty;
                this.form.total_penalty = 0;
                this.form.amount_repay  = data.unreceived + data.total_penalty;
                this.funPaymentMethod();
                $("#modalRepayForm").modal("show");
            },
            subRepayment() {
                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.amount_repay<=0){
                    this.$toast.warning("សូមបំពេញលក្ខខណ្ឌអោយបានត្រឹមត្រូវ!");
                } else{
                    $("#modalRepayForm").modal("hide");
                    $("#modalVerify").modal("show");
                }
            }, 
            fSubmitData(){
                if (this.form.submitting) {
                    return;
                }   
                this.form.submitting = true;
                this.form = new Form({
                    'id' : this.form.id,
                    'chart_of_acc_id': this.form.chart_of_acc_id,
                    'received_date'  : this.form.received_date,
                    'amount_repay'   : this.form.amount_repay,
                    'paid_penalty'   : this.form.paid_penalty==''?0:this.form.paid_penalty,
                    'waiv_penalty'   : this.form.waiv_penalty==''?0:this.form.waiv_penalty,
                    // 'unpaid_penalty' : 0,
                });
                this.form.post("admin-api/client-payment").then((res) => {
                    if (res.data.status == 1) {
                        this.form.reset();
                        this.$toast.success(res.data.message);
                        $("#modalVerify").modal("hide");
                        this.funGetData();
                    } else {
                        this.$toast.warning(res.data.message);
                    }
                }).catch((error) => {
                    console.log(error);
                }).finally(() => {
                    this.form.submitting = false;
                });
            },
            
            // Pay Off
            funPayOff(loan) {
                this.funPaymentMethod();
                $("#modalPayOff").modal("show");
                axios.get("admin-api/show-pay-all/" + loan.loan_id).then((res) => {
                    this.form.id = loan.loan_id;
                    this.form.chart_of_acc_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.sumRisk        = res.data.sum_risk;
                    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.sumRisk + this.form.sumMaintenance + this.form.penalty_payoff;
                }).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,
                    'sumRisk'        : this.form.sumRisk,
                    '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,
                });
                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;
                });
            }
        },
    };
</script>