<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Loan Collection') }}
        </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>
                    <label class="form-label">{{ $t('Payment Date') }}</label>
                    <div class="mb-3 d-flex">
                        <date-picker :placeholder="$t('Payment Date')" v-model="params.date" valueType="format" format="YYYY-MM-DD"> </date-picker>
                    </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('Loan Collection')" 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 class="fixed_left">{{ $t("Client") }}</th>
                                <th>{{ $t("Phone") }}</th>
                                <th>{{ $t("Village") }}</th>
                                <th>{{ $t("CO") }}</th>
                                <th>{{ $t("Loan Code") }}</th>
                                <th>{{ $t("Installment Date") }}</th>
                                <th>{{ $t("Payment Date") }}</th>
                                <th>{{ $t("Total Period") }}</th>
                                <th>{{ $t("Period Unpaid") }}</th>
                                <th>{{ $t("Total Late") }}</th>
                                <th>{{ $t("Loan Out") }}</th>
                                <th>{{ $t("Balance Principal") }}</th>
                                <th>{{ $t("Loan Balance") }}</th>
                                <th>{{ $t("Branch") }}</th>
                                <th class="d-print-none" v-show="user_branch != -1">{{ $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%" v-if="user_branch != -1">
                                    <button type="button" v-if="$can('Repay')" @click="funRepay(acc)"
                                        :title="$t('Repay')" class="btn btn-success s-btn-xs rounded-pill fw-bold">
                                        <span v-show="acc.unreceived != null">
                                            <i class="fa-solid fa-money-bill-transfer fa-sm"></i> {{ acc.unreceived | numberFomartValue }}
                                        </span>
                                        <span v-show="acc.unreceived_late != null">
                                            <i class="fa-solid fa-money-bill-transfer fa-sm"></i> {{ (acc.unreceived_late) | numberFomartValue }}
                                        </span>
                                    </button>
                                </td>
                                <td v-else>
                                    <span v-show="acc.unreceived != null">
                                        {{ acc.unreceived | numberFomartValue }}
                                    </span>
                                    <span v-show="acc.unreceived_late != null">
                                        {{ (acc.unreceived_late) | numberFomartValue }}
                                    </span>
                                </td>
                                <td class="fw-bold fixed_left" 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.installment_date | onlyDate }}</td>
                                <td>{{ acc.date_late | onlyDate }}</td>
                                <td>{{ acc.total_period }}</td>
                                <td>{{ acc.count_period_unpaid }}</td>
                                <td>{{ acc.total_late }} ថ្ងៃ</td>
                                <td>{{ acc.loan_out | numberFomartValue }}</td>
                                <td>{{ acc.balance_principal | numberFomartValue }}</td>
                                <td>{{ acc.total_loan_balance | numberFomartValue }}</td>
                                <td>{{ acc.branch_name }}</td>
                                <td width="5%" class="d-print-none" v-show="user_branch != -1">
                                    <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>
                            <tr class="table-active">
                                <td class="text-end">{{ $t("Total") }}</td>
                                <td>{{ sumUnreceived | numberFomartValue }}</td>
                                <td colspan="10"></td>
                                <td>{{ sumLoanOut | numberFomartValue }}</td>
                                <td>{{ sumBalancePrincipal | numberFomartValue }}</td>
                                <td>{{ sumLoanBalance | numberFomartValue }}</td>
                                <td></td>
                                <td class="d-print-none" v-show="user_branch != -1"></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" :client_name="form.client_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" :client_name="form.client_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: [] },
            user_branch: '',
            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,
                sumOperatService: 0,
                sumMaintenance: 0,
                penalty_payoff: 0,
                amountPay: 0,
                // show
                client_name: "",
                loan_code: "",
                payment_date: "",
                payment: 0,
                principal: 0,
                interest: 0,
                unreceived: 0,
                operating_service: 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: [],
                date: null,
                // type_collect_late: 1,
                type_collection: 1,
                client_type: 1,
            },
        };
    },
    created() {
        this.funGetData();
        this.getClient();
        this.getCO();
        this.getVillage();
        this.funComUserBranch();
    },
    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);
            });
        },
        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.operating_service = data.operating_service;
        //     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");
        // },
        funRepay(data) {
            this.form.id = data.id;
            this.form.chart_of_acc_id = '';
            this.form.maintenance = data.maintenance_late;
            this.form.waiv_penalty = 0;
            this.form.currency_name = data.currency_id == 1 ? '៛' : '$';
            this.form.client_name = data.client_name + " - " + data.loan_code;
            this.form.principal = data.principal_late;
            this.form.interest = data.interest_late;
            this.form.operating_service = data.operating_service_late;
            this.form.payment = data.unreceived_late;
            this.form.unreceived = data.unreceived_late;
            this.form.payment_date = data.payment_date;
            this.form.total_penalty = data.total_penalty;
            this.form.paid_penalty = 0;
            this.form.amount_repay = data.unreceived_late;
            this.form.total_late_day = data.total_late;
            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.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);
            });
        },
        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,
            });
            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;
            });
        },
        async exportExcell() {
            this.$isLoading(true)
            try {
                await exportTableToExcel({
                    tableId: "excel-table",
                    filename: "LoanCollection",
                    reportTitle: "បញ្ជីអតិថិជនប្រមូលប្រាក់កម្ចី",
                    subDate: this.params.date,
                })
            } catch (e) {
                this.$toast.warning(e.message);
            } finally {
                this.$isLoading(false)
            }
        },
    },
    computed: {
        sumUnreceived: function () {
            var sum = 0;
            this.collectionData.data?.forEach(function (item) {
                if (item.unreceived != null) {
                    sum += parseFloat(item.unreceived);
                } else {
                    sum += parseFloat(item.unreceived_late);
                }
            });
            return sum;
        },
        sumLoanOut: function () {
            var sum = 0;
            this.collectionData.data?.forEach(function (item) {
                sum += parseFloat(item.loan_out)
            });
            return sum;
        },
        sumBalancePrincipal: function () {
            var sum = 0;
            this.collectionData.data?.forEach(function (item) {
                sum += parseFloat(item.balance_principal)
            });
            return sum;
        },
        sumLoanBalance: function () {
            var sum = 0;
            this.collectionData.data?.forEach(function (item) {
                sum += parseFloat(item.total_loan_balance)
            });
            return sum;
        },
    }
};
</script>
<style scoped>
.fixed_left {
    position: sticky;
    left: 0;
    top: 0;
    z-index: 999;
    background: #f8f8f8;
}

.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>
