<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Reject Loan Report') }}
        </span>
        <div 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('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>
                    <label class="form-label">{{ $t('Received Date') }}</label>
                    <div class="mb-3 d-flex">
                        <date-picker class="me-1" :range="true" :placeholder="$t('Received 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 class="list-group mb-3">
                        <button type="button" class="btn btn-success" @click="funGetData"><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>
        </div>
        <div slot="body">
            <div id="show-print">
                <div class="table-responsive report_print overflow-auto" style="height: calc(100vh - 270px)">
                    <header-report :title="$t('Sum Total Client Payment')" :date="current_date" :type="1" style="display: none;"></header-report>
                    <table class="table table-bordered m-0" id="excel-table">
                        <thead class="text-nowrap fixed_table">
                            <tr>
                                <th>{{ $t("#") }}</th>
                                <th>លេខកូដអតិថិជន</th>
                                <th>{{ $t("Client Name") }}</th>
                                <th>{{ $t("CO Name") }}</th>
                                <th>{{ $t("Phone") }}</th>
                                <th>{{ $t("Installment Date") }}</th>
                                
                                <th>{{ $t("Period") }}</th>
                                <th>{{ $t("Term Condition") }}</th> 
                                <th>{{ $t("Type Payment") }}</th>
                                <th>{{ $t("Loan Out") }}</th>
                                <th>{{ $t("Total Interest") }}</th>
                                <th>{{ $t("Service") }} </th>
                                <th>{{ $t("Service") }}</th>
                                <th>{{ $t("Total Insurance") }}</th>
                                <th>{{ $t("Collateral") }}</th>
                                <th>{{ $t("Status") }}</th>
                            </tr>
                        </thead>
                        <tbody class="text-nowrap">
                            <tr v-for="(acc, index) in rejectloanreport.data" :key="index">
                                <td>{{ index + 1 }}</td>
                                <td>{{ acc.loan_code }}</td>
                                <td>{{ acc.client_name }}</td>
                                <td>{{ acc.co_name }}</td>
                                <td>{{ acc.client_phone }}</td>
                                <td>{{ acc.installment_date | onlyDate }}</td>
                                <td>{{ acc.period }}</td>
                                <td>{{ acc.term_condi_name}}</td>
                                <td>{{funTerm(acc.term_type)}}</td>
                                <td>{{ acc.loan_out | numberFomartValue }}</td>
                                <td>{{ acc.total_interest }}</td>
                                <td>{{ acc.service }}</td>
                                <td>{{ acc.total_service | numberFomartValue}}</td>
                                <td>{{ acc.total_insurance | numberFomartValue}}</td>
                                <td>{{ getModelTypes(acc.collateral) }}</td>
                                <td>{{ acc.loan_status}}</td>
                            </tr>
                            <tr class="table-active">
                                <td></td>
                                <td></td>
                                <td></td>
                                <td colspan="5" class="text-center">{{ $t("Total") }}</td>
                                <td></td>
                                <td>{{totalLoanOut | numberFomartValue}}</td>
                                <td>{{totalInterest | numberFomartValue}}</td>
                                <td>{{totalService | numberFomartValue}}</td>
                                <td>{{totalInsurance | numberFomartValue}}</td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>
                    <footer-report style="display: none;"></footer-report>
                </div>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="rejectloanreport" @onChangePage="funGetData($event)"></cumstom-pagination>
        </div>
    </theme-table>
</template>
<script>
import HeaderReport from "../../components/report/header.vue";
import FooterReport from "../../components/report/footer.vue";
import ThemeTable from "../../components/ThemeTable.vue";
import CumstomPagination from "../../components/CustomPagination.vue";
import { exportTableToExcel } from "../../exportExcel.js";
export default {
    components: {
        ThemeTable,
        HeaderReport,
        FooterReport, 
        CumstomPagination
    }, 
    data() {
        return {
 
            format: "YYYY-MM-DD",
            rejectloanreport: { data: [] },
            current_date: new Date().toISOString(),
            clients: [],
            coes: [],
            form: new Form({}),
            params: {
                page: 1,
                per_page: 25,
                search_text: "",

                client_id: [],
                co_id: [],
                date: [],
                deatail: 1,
                loan_status_id: 2,
                client_type: 1,
            },
        };
    },
    created() {
        this.funGetData();
        this.getClient();
        this.getCO();
    },
    methods: {
        async exportExcell() {
            this.$isLoading(true)
            try {
                await exportTableToExcel({
                    tableId: "excel-table",
                    filename: "ExportBorrow",
                    reportTitle: "ចំនួនទឹកប្រាក់សរុបនៃការទូទាត់របស់អតិថិជន",
                    subDate: this.params.date,
                })
            } catch (e) {
                this.$toast.warning(e.message);
            } finally {
                this.$isLoading(false)
            }
        },
        printP() {
            this.$htmlToPaper("show-print");
        },
        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);
                });
        },
        funGetData(page = 1) {
            this.params.page = page;
            axios
                .get("admin-api/reject-loan-report", {
                    params: this.params,
                })
                .then((res) => {
                    this.rejectloanreport = 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();
        },
        funTerm(status){
                if(status==1){
                    return 'ថ្ងៃ';
                }else if(status==2){
                    return 'សប្ដាហ៍';
                }else if(status==3){
                    return 'កន្លះខែ';
                }else if(status==4){
                    return 'ខែ';
                }
        },
        
        getModelTypes(collateral) {
                if (!collateral || !Array.isArray(collateral)) {
                    return '';
                }
                return collateral
                    .map((item) => item?.model_type)
                    .filter(Boolean) // Removes any undefined or null values
                    .join(' / '); // Joins the values with a space
        },

    },
    computed: {
            totalLoanOut: function () {
                var sum = 0;
                this.rejectloanreport.data.forEach(function (item) {
                    sum += parseFloat(item.loan_out);
                });
                return sum;
            },
            totalService: function () {
                var sum = 0;
                this.rejectloanreport.data.forEach(function (item) {
                    sum += parseFloat(item.total_service);
                });
                return sum;
            },
            totalInsurance: function () {
                var sum = 0;
                this.rejectloanreport.data.forEach(function (item) {
                    sum += parseFloat(item.total_insurance);
                });
                return sum;
            },
            totalInterest: function () {
                var sum = 0;
                this.rejectloanreport.data?.forEach(function (item) {
                    sum += parseFloat(item.total_interest);
                });
                return sum;
            },
    },
};
</script>
