<template>
        <theme-table :noneActions="true">
            <span slot="main-title">
                <router-link :to="{ name: 'Loan' }"> {{ $t('Loan List') }} </router-link>
                <label class="px-1">/</label>
                <label> {{ $t('Table Schedule') }}</label>
            </span>
            <template slot="more-button">
                <button type="button" @click="printP" class="btn btn-primary btn-sm"><i class="fa fa-print"></i> {{ $t('Print') }}</button>
                <button type="button" class="btn btn-danger ms-2" @click="exportExcell"><i class="fa fa-file-export"></i> {{ $t('Export') }}</button>
            </template>
            <div slot="body"  id="export-excel-table" >
                <div id="show-print" style="overflow-x: auto" >
                    <div class="table-schedule ">
                        <div class="table-responsive table_scroll report_print">

                            <div class="report_header position-relative" style="min-height: 80px">
                                <img src="images/logo.png" alt="" width="80px" class="position-absolute" style="top: 5px; left: 0;">
                                <div class="text-center">
                                    <h5 class="title_en fw-bold mb-2">កាលវិភាគសងប្រាក់</h5>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-4">
                                    <table class="mb-0">
                                        <tr>
                                            <td>ឈ្មោះភ្នាក់ងារ</td>
                                            <td class="ps-2">: {{ coSchedule.name }}</td>
                                        </tr>
                                        <tr>
                                            <td>ឈ្មោះអតិថិជន</td>
                                            <td class="ps-2">: {{ clientSchedule.name }}</td>
                                        </tr>
                                        <tr>
                                            <td>លេខកូដអតិថិជន</td>
                                            <td class="ps-2">: {{ clientSchedule.code }}</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-4">
                                    <table class="mb-0">
                                        <tr>
                                            <td>អ្នករួមខ្ចី</td>
                                            <td class="ps-2">: {{ garuantor1.name }}</td>
                                        </tr>
                                          <tr>
                                            <td>ប្រភេទសង</td>
                                            <td class="ps-2">: {{ funConditionPay(loanSchedule.condition_pay)}}</td>
                                        </tr>
                                          <tr>
                                            <td>អាស័យដ្ឋាន</td>
                                            <td class="ps-2">: {{ clientSchedule.village_kh }} {{ clientSchedule.commune_kh }} {{ clientSchedule.district_kh }} {{ clientSchedule.province_kh }}</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-4">
                                    <table class="mb-0">
                                        <tr>
                                            <td>លេខទូរស័ព្ទ</td>
                                            <td class="ps-2">: {{ clientSchedule.phone }}</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>

                            <div class="my-1 border border-dark w-100"></div>

                            <div class="row mb-2">
                                <div class="col-4">
                                    <table class="mb-0">
                                        <tr>
                                            <td>ចំនួនទឹកប្រាក់</td>
                                            <td class="ps-2">: {{ loanSchedule.loan_out | numberFomartValue }} {{ Curr.currency_km }}</td>
                                        </tr>
                                         <tr>
                                            <td>រយះពេលខ្ចី</td>
                                            <td class="ps-2">: {{ loanSchedule.period }}ដង / {{funTerm(loanSchedule.term_type)}}</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-4">
                                    <table class="mb-0">
                                        <tr>
                                            <td>ចំនួនទឹកប្រាក់ជាអក្សរ</td>
                                            <td class="ps-2">: {{ totalToword(loanSchedule.loan_out, loanSchedule.currency_id) }}</td>
                                        </tr>
                                         <tr>
                                            <td>កាលបរិច្ឆេទ</td>
                                            <td class="ps-2">: {{ loanSchedule.installment_date | onlyDate }}</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-4">
                                    <table class="mb-0">
                                        <tr>
                                            <td>ថ្លៃសេវារដ្ធបាល</td>
                                            <td class="ps-2">: {{ loanSchedule.total_service | numberFomartValue }} {{ Curr.currency_km }}</td>
                                        </tr>
                                         <tr>
                                            <td>កាលវិភាគសងប្រាក់លើកចុងក្រោយ</td>
                                            <td class="ps-2">: {{ loanSchedule.expired_date | onlyDate }}</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>

                            <table class="table mb-1 table-bordered border-dark">
                                <thead class="text-nowrap text-center fixed_table">
                                    <tr>
                                        <th style="width: 40px">ល.រ</th>
                                        <th>ថ្ងៃបង់ប្រាក់</th>
                                        <th>ប្រាក់ដើមនៅជំពាក់</th>
                                        <th>ថ្លៃសេវាត្រូវបង់</th>
                                        <th>ប្រាក់សរុបត្រូវបង់</th>
                                        <th>សំគាល់ផ្សេងៗ</th>
                                    </tr>
                                </thead>
                                <tbody class="text-nowrap text-end">
                                    <tr v-for="(acc, index) in dataPayment.data" :key="index" :class="index==(countPay-1)?'bg-ccc':''">
                                        <td class="text-center">{{ index + 1 }}</td>
                                        <td class="text-start">{{formatKhmerDate(acc.payment_date)}} </td>
                                        <td>{{ acc.balance_principal_new  | numberFomartValue }}</td>
                                        <td>{{ acc.risk_per_month | numberFomartValue }}</td>
                                        <td>{{ acc.payment_per_month | numberFomartValue }}</td>
                                        <td></td>
                                    </tr>
                                </tbody>
                            </table>

                            <div>
                                <div class="row mx-0 my-2 text-nowrap">
                                    <div class="col noted-desc">
                                        <p>ក្រោយពីបានពិនិត្យកិច្ចសន្យានិងតារាងបង់ប្រាក់ខាងលើ ខ្ញុំបាទ/នាងខ្ញុំបានយល់ព្រមបង់សងប្រាក់មក ស្ថាប័ន</p>
                                    </div>
                                </div>

                                <div class="row text-center mx-0">
                                    <div class="col-3">
                                        <p>ហត្ថលេខាបុគ្គលិក</p>
                                        <br>
                                        <br>
                                        <br>
                                        <br>
                                        <p>{{ coSchedule.name }}</p>
                                        <p>{{ coSchedule.phone }}</p>
                                    </div>
                                    <div class="col-3">
                                        <p>ស្នាមមេដៃអ្នករួមខ្ចី</p>
                                        <br>
                                        <br>
                                        <br>
                                        <br>
                                        <p>{{ garuantor1.name }}</p>
                                    </div>
                                    <div class="col-3">
                                        <p>ស្នាមមេដៃអ្នកធានា</p>
                                        <br>
                                        <br>
                                        <br>
                                        <br>
                                        <p>{{ garuantor2.name }}</p>
                                    </div>
                                    <div class="col-3">
                                        <p>ស្នាមមេដៃអ្នកខ្ចី</p>
                                        <br>
                                        <br>
                                        <br>
                                        <br>
                                        <p>{{ clientSchedule.name }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </theme-table>
</template>

<script>
    import HeaderReport from "../../components/report/header.vue";
    import HeaderTable from "../../components/report/HeaderTable.vue";
    import ThemeTable from "../../components/ThemeTable.vue";
    import { exportTableToExcel } from "../../exportScheduleExcel.js"
    import moment from "moment";
    import {currencyToWord } from "number_to_khmer_word";
    export default {

        props: ["id"],
        components: {
            HeaderReport,
            HeaderTable,
            ThemeTable,
        },
        data() {
            return {
                moment  : moment,
                format  : "YYYY-MM-DD",
                currencyToWord : currencyToWord,
                dataPayment   : { data: [] },
                loanSchedule  : "",
                clientSchedule: "",
                garuantor1    : "",
                garuantor2    : "",
                garuantor3    : "",
                coSchedule    : "",
                countPay      : "",
                Curr          : "",
                company      : "",
                type_logo     : 1,
                type_row     : 1,
                collateral_name: "",
            };
        },
        created() {
            this.funGetData();
            this.funGetCompany();
        },
        computed: {
            totalPrincipal: function () { var sum = 0; this.dataPayment.data.forEach(function (item) { sum += parseFloat(item.principal);}); return sum; },
            totalInterestPerMonth: function () { var sum = 0; this.dataPayment.data.forEach(function (item) { sum += parseFloat(item.interest_per_month);}); return sum; },
            totalRiskPerMonth: function () { var sum = 0; this.dataPayment.data.forEach(function (item) { sum += parseFloat(item.risk_per_month);}); return sum; },
            totalPaymentPerMonth: function () { var sum = 0; this.dataPayment.data.forEach(function (item) { sum += parseFloat(item.payment_per_month);}); return sum; },
            totalPenalty: function () { var sum = 0; this.dataPayment.data.forEach(function (item) { sum += parseFloat(item.penalty);}); return sum; },
            totalLoanBalance: function () { var sum = 0; this.dataPayment.data.forEach(function (item) { sum += parseFloat(item.loan_balance);}); return sum; },
        },
        methods: {
            funGetCompany(){
                axios.get('admin-api/company').then((res) => {
                    this.company = res.data;
                });
            },
            calculateDaysBetweenPaymentDates(index) {
                if (index === 0) {
                    const currentDate = moment(this.dataPayment.data[index].payment_date);
                    const previousDate = moment(this.loanSchedule.installment_date);
                    return currentDate.diff(previousDate, 'days');
                } else {
                    const currentDate = moment(this.dataPayment.data[index].payment_date);
                    const previousDate = moment(this.dataPayment.data[index - 1].payment_date);
                    return currentDate.diff(previousDate, 'days');
                }
            },
            funGetData() {
                axios.get("admin-api/loans/show-payment/" + this.id).then((res) => {
                        this.dataPayment = res.data;
                        this.loanSchedule = res.data.loan;
                        this.clientSchedule = res.data.client;
                        this.garuantor1 = res.data.garuantor1;
                        this.garuantor2 = res.data.garuantor2;
                        this.garuantor3 = res.data.garuantor3;
                        this.coSchedule = res.data.co;
                        this.countPay = res.data.countPay;
                        this.Curr = res.data.currency;
                        this.collateral_name = res.data.collateral_name;
                    }).catch((error) => {
                        console.log(error);
                    });
            },
            formatKhmerDate(dateStr) {
                if (!dateStr) return '';

                const date = new Date(dateStr);

                const days = ['អាទិត្យ', 'ចន្ទ', 'អង្គារ', 'ពុធ', 'ព្រហស្បតិ៍', 'សុក្រ', 'សៅរ៍'];
                const months = [
                'មករា','កុម្ភៈ','មីនា','មេសា','ឧសភា','មិថុនា',
                'កក្កដា','សីហា','កញ្ញា','តុលា','វិច្ឆិកា','ធ្នូ'
                ];

                const khmerNumbers = ['0','1','2','3','4','5','6','7','8','9'];

                const toKhmerNumber = (num) => {
                return num.toString().split('').map(n => khmerNumbers[n]).join('');
                };

                const dayName = days[date.getDay()];
                const day = toKhmerNumber(date.getDate());
                const month = months[date.getMonth()];
                const year = toKhmerNumber(date.getFullYear());

                return `${dayName} ${day}-${month}-${year}`;
            },
            totalToword(loan_out,currency_id) {
                if (currency_id == 1) {
                    if (loan_out) {
                        return currencyToWord(loan_out, "KHR").slice(1).replace(/-/g, "");
                    } else {
                        return currencyToWord(0, "KHR").slice(1);
                    }
                } else {
                    if (loan_out) {
                        return currencyToWord(loan_out, "USD")
                            .slice(1)
                            .replace(/-/g, " ")
                            .replace(/ ដុល្លារ គត់/, " ដុល្លារសហរដ្ឋអាមេរិចគត់");
                    } else {
                        return currencyToWord(0, "USD").slice(1);
                    }
                }
            },
            funTerm(status){
                if(status==1){
                    return 'ថ្ងៃ';
                }else if(status==2){
                    return 'សប្ដាហ៍';
                }else if(status==3){
                    return 'កន្លះខែ';
                }else if(status==4){
                    return 'ខែ';
                }
            },
             funConditionPay(ConPay){
                if(ConPay==1){
                    return 'បង់ប្រាក់ថេរ';
                }else if(ConPay==2){
                    return 'បង់ប្រាក់ដើមថេរ';
                }else if(ConPay==3){
                    return 'បង់ប្រាក់ដើមនិងការប្រាក់ថេរ';
                }else if(ConPay==4){
                    return 'បង់តែការប្រាក់';
                }
            },

            funDay(day) {
                if (day == "Mo") {
                    return "ចន្ទ";
                } else if (day == "Tu") {
                    return "អង្គារ";
                } else if (day == "We") {
                    return "ពុធ";
                } else if (day == "Th") {
                    return "ព្រហ";
                } else if (day == "Fr") {
                    return "សុក្រ";
                } else if (day == "Sa") {
                    return "សៅរ៍";
                } else {
                    return "អាទិត្យ";
                }
            },
            funTypeLoan(typeLoan)
            {
                if(typeLoan == 1){
                    return "ID-M"
                }else if(typeLoan == 2){
                    return "ID-C"
                }else if(typeLoan == 3){
                    return "ID-L"
                }
            },
            printP() {
                this.$htmlToPaper("show-print", {
                    styles: ["/css/app.css",
                     "/css/style-print.css",
                     "/css/print/print-tableschedule.css"],
                });
            },

           async exportExcell() {
    // បង្ហាញ Loading
    this.$isLoading(true);

    try {
        // ហៅមុខងារ Export ដោយបញ្ជូនទិន្នន័យអោយត្រូវតាម Parameter ថ្មី
        await exportTableToExcel({
            dataPayment: this.dataPayment,       // Object ទាំងមូលដែលមាន .data នៅខាងក្នុង
            clientSchedule: this.clientSchedule,
            loanSchedule: this.loanSchedule,
            coSchedule: this.coSchedule,
            garuantor1: this.garuantor1,         // បញ្ជូនអ្នករួមខ្ចីទី១
            garuantor2: this.garuantor2,         // បញ្ជូនអ្នកធានាទី២
            Curr: this.Curr,                     // ដើម្បីយកនិមិត្តសញ្ញារូបិយប័ណ្ណ
            totalToword: this.totalToword,       // បញ្ជូន Function បំប្លែងលេខជាអក្សរទៅដែរ
            fileName: `Schedule_${this.loanSchedule.loan_code || 'List'}.xlsx`
        });

    } catch (e) {
        // បង្ហាញសារព្រមានក្នុងករណីមានកំហុស
        console.error(e);
        this.$toast.warning("មានបញ្ហាក្នុងការទាញយកឯកសារ Excel");
    } finally {
        // បិទ Loading វិញ
        this.$isLoading(false);
    }
}

        },
    };
</script>

<style lang="scss" scoped>
    .table-schedule{
        min-width: 210mm;
    }
</style>
