<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Collect Loan Write off') }}
        </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 Loan Write off')" 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 Late") }}</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("Loan Out") }}</th>
                                <th>{{ $t("Balance Principal") }}</th>
                                <th>{{ $t("Loan Balance") }}</th>
                                <th>{{ $t("Date Late") }}</th>
                                <th>{{ $t("Total Late") }}</th>
                                <!-- <th>{{ $t("Total Penalty") }}</th> -->
                                <th>{{ $t("Branch") }}</th>
                                <th class="d-print-none" v-if="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">
                                        <i class="fa-solid fa-money-bill-transfer fa-sm"></i> {{ (acc.unreceived_late) | numberFomartValue }}
                                    </button>
                                </td>
                                <td v-else>
                                    {{ (acc.unreceived_late) | numberFomartValue }}
                                </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.loan_out | numberFomartValue }}</td>
                                <td>{{ acc.balance_principal | numberFomartValue }}</td>
                                <td>{{ acc.total_loan_balance | numberFomartValue }}</td>
                                <td>{{ acc.date_late | onlyDate}}</td>
                                <td>{{ acc.total_late}} ថ្ងៃ</td>
                                <td>{{ acc.branch_name}}</td>
                                <!-- <td>{{ acc.total_penalty | numberFomartValue }}</td> -->
                                <td width="5%" class="d-print-none" v-if="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 Of')" @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>
                            </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: [],
                collectionData  : {data:[]},
                payment_methods : [],
                user_branch  : '',
                form: new Form({
                    // Repayment & payOff
                    id: "",
                    currency_name: "",
                    amount_repay : 0,
                    total_penalty : 0,
                    paid_penalty  : 0,
                    waiv_penalty  : 0,
                    // payoff
                    sumPrincipal  : 0,
                    sumInterest   : 0,
                    sumOperatService : 0,
                    sumMaintenance: 0,
                    penalty_payoff: 0,
                    amountPay     : 0,
                    // show
                    client_name   : "",
                    payment_date  : '',
                    payment       : 0,
                    principal     : 0,
                    interest      : 0,
                    operating_service : 0,
                    maintenance   : 0,
                    unreceived    : 0,
                    total_late_day: 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: [],
                    type_collect_late: 1,
                    client_type: 2,
                },
            };
        },
        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);
                });
            },
            funGetData(page = 1) {
                this.params.page = page;
                axios
                    .get("admin-api/collect-late-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.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");
            },
            funPaymentMethod() {
                axios.get("accounting/com-cash-bank").then((res) => {
                    this.payment_methods = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            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,
                });
                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: "CollectLoanWriteoff",
                        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) {
                    sum += parseFloat(item.unreceived_late);
                });
                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>
