<template>
    <theme-table :newButton="true" :permisName="'Journal Create'" @click="funNewJournal()" @input="Searching">
        <span slot="main-title">
            {{ $t('Journal Posting') }}
        </span>
        <div slot="body">
            <div class="table-responsive table_scroll">
                <table class="table table-bordered text-center">
                    <thead>
                        <tr class="border-top border-bottom text-nowrap">
                            <th>{{ $t("#") }}</th>
                            <th>{{ $t("Invoice Number") }}</th>
                            <th>{{ $t("Journal Date") }}</th>
                            <th>{{ $t("Account Number") }}</th>
                            <th>{{ $t("Account Name") }}</th>
                            <th>{{ $t("Debit") }}</th>
                            <th>{{ $t("Credit") }}</th>
                            <th>{{ $t("Created By") }}</th>
                            <th>{{ $t("Description") }}</th>
                            <th class="text-nowrap hidden_p">{{ $t("Action") }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(value,index) in journal_data.data">
                            <td>{{index+1}}</td>
                            <td>{{value.invoice_number}}</td>
                            <td>{{value.journal_date | onlyDate}}</td>
                            <td>{{value.chart_code}}</td>
                            <td class="text-nowrap text-start">{{value.chart_name}}</td>
                            <td class="text-nowrap">
                                <span v-if="value.debit>0">{{value.debit | numberFomartValue}}</span>
                            </td>
                            <td class="text-nowrap">
                                <span v-if="value.credit>0">{{value.credit | numberFomartValue}}</span>
                            </td>
                            <td>{{value.created_by}}</td>
                            <td class="text-start">{{value.desc}}</td>
                            <td class="text-nowrap hidden_p">
                                <button v-show="$can('Journal Edit')" @click="funEditJournal(value)" v-if="showEditOrDelete(index, value)" class="btn btn-dark btn-sm s-btn-xs">
                                    <i class="fa-solid fa-pen-to-square fa-sm"></i>
                                </button>
                                <button v-show="$can('Journal Delete')" @click="funDelete(value.parent_id)" v-if="showEditOrDelete(index, value)" type="button" class="btn btn-danger btn-sm s-btn-xs">
                                    <i class="fa-solid fa-trash-can fa-sm"></i>
                                </button>
                            </td>
                        </tr>
                        <tr class="table-active">
                            <td colspan="5" class="text-end">{{ $t("Total") }}</td>
                            <td>{{sumTotalDebit | numberFomartValue}}</td>
                            <td>{{sumTotalCredit | numberFomartValue}}</td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="journal_data" @onChangePage="funGetData($event)"></cumstom-pagination>
        </div>
        <div slot="modal-custom">
            <form method="post" role="form">
                <div class="modal fade" id="modalAddNew" aria-hidden="true" role="dialog" data-backdrop="static">
                    <div class="modal-dialog modal-dialog-scrollable modal-xl">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">{{ $t("Journal Posting") }}</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-sm-4 mb-3">
                                        <label>{{ $t("Invoice Number") }} <span class="text-danger">*</span></label>
                                        <input :placeholder="$t('Invoice Number')" type="text" class="form-control" v-model="form.invoice_number" :class="{'is-invalid': form.errors.has('invoice_number') }" />
                                        <div class="text-danger" v-if="form.errors.has('invoice_number')" v-html="form.errors.get('invoice_number')"></div>
                                    </div>
                                    <div class="col-sm-4 mb-3">
                                        <label>{{$t('Description')}} <span class="text-danger">*</span></label>
                                        <textarea :placeholder="$t('Description')" class="form-control" v-model="form.desc" :class="{'is-invalid': form.errors.has('desc') }" rows="1"></textarea>
                                        <div class="text-danger" v-if="form.errors.has('desc')" v-html="form.errors.get('desc')"></div>
                                    </div>
                                    <div class="col-sm-4 mb-3">
                                        <label>{{ $t("Journal Date") }} <span class="text-danger">*</span></label>
                                        <date-picker v-model="form.journal_date" valueType="format" :format="format" :class="{'is-invalid': form.errors.has('journal_date') }"></date-picker>
                                        <div class="text-danger" v-if="form.errors.has('journal_date')" v-html="form.errors.get('journal_date')"></div>
                                    </div>
                                    <div class="col-12 mb-2 text-end" v-show="this.method==false">
                                        <button class="btn btn-outline-success" type="button" @click="addRow()" role="button"><i class="fa-solid fa-plus"></i> {{$t('Add Row')}}</button>
                                    </div>
                                    <div class="col-12 table-responsive">
                                        <table style="width: 100%" class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th class="text-nowrap">{{ $t("#") }}</th>
                                                    <th class="text-nowrap">{{$t("Chart Code")}}</th>
                                                    <th class="text-nowrap">{{$t("Debit")}}</th>
                                                    <th class="text-nowrap">{{$t("Credit")}}</th>
                                                    <th class="text-nowrap" v-show="method==false">{{$t("Action")}}</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr v-for="(row,index) in journal_rows" :key="index">
                                                    <td>{{index+1}}</td>
                                                    <td style="width: 50%">
                                                        <Multiselect
                                                            :class="{'is-invalid': form.errors.has('journal_rows.'+index+'.chart_of_acc_id') }"
                                                            :placeholder="$t('Chart Code')"
                                                            :disabled="form.can_edit ==false"
                                                            :searchable="true"
                                                            :options="chart_of_account"
                                                            label="chart_code_name"
                                                            trackBy="chart_code_name"
                                                            value="id"
                                                            v-model="row.chart_of_acc_id"
                                                            style="min-width: 200px"
                                                        />
                                                    </td>
                                                    <td>
                                                        <input
                                                            type="number"
                                                            step="any"
                                                            v-model="row.debit"
                                                            style="width: 200px;"
                                                            @input="funDebit(index)"
                                                            :disabled="row.credit>0"
                                                            class="form-control number-only"
                                                            :class="{'is-invalid': form.errors.has('journal_rows.'+index+'.debit') }"
                                                        />
                                                    </td>
                                                    <td>
                                                        <input
                                                            type="number"
                                                            step="any"
                                                            v-model="row.credit"
                                                            style="width: 200px;"
                                                            @input="funCredit(index)"
                                                            :disabled="row.debit>0"
                                                            class="form-control number-only"
                                                            :class="{'is-invalid': form.errors.has('journal_rows.'+index+'.credit') }"
                                                        />
                                                    </td>
                                                    <td v-show="method==false">
                                                        <button type="button" :title="$t('Delete')" class="btn btn-sm text-danger" @click="removeRowItem(index)"><i class="fa-solid fa-trash"></i></button>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" class="text-end"><strong>{{$t("Total")}}</strong></td>
                                                    <td><strong>{{totalDebitJournal | numberFomartValue}}</strong></td>
                                                    <td><strong>{{totalCreditJournal | numberFomartValue}}</strong></td>
                                                    <td v-show="method==false"></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">{{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy||journal_rows==''" class="btn btn-primary" @click="method? funUpdateData() : funSubmitData()">
                                    {{$t('Submit')}}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </theme-table>
</template>
<script>
    import ThemeTable from "../../../components/ThemeTable.vue";
    import CumstomPagination from "../../../components/CustomPagination.vue";
    export default {
        components: {
            ThemeTable,
            CumstomPagination,
        },
        data() {
            return {
                method: false,
                isLoading: false,
                format: "YYYY-MM-DD",
                journal_data: { data: [] },
                chart_of_account: [],
                user_branch  : '',
                form: new Form({
                    id: "",
                    desc: "",
                    debit: null,
                    credit: null,
                    journal_date: new Date().toISOString(),
                    invoice_number: null,
                }),
                journal_rows: [
                    {
                        chart_of_acc_id: null,
                        debit: null,
                        credit: null,
                    },
                ],
                params: {
                    page: 1,
                    per_page: 25,
                    search_text: "",
                    journal_list: 1,
                },
                per_page: "",
                current_page: "",
                to_page: "",
                total_page: "",
            };
        },

        created() {
            this.funGetData();
            this.funGetDataChartOfAcc();
            this.funComUserBranch();
        },
        methods: {
            funGetData(page = 1) {
                this.params.page = page;
                axios
                    .get("accounting/journals", {
                        params: this.params,
                    })
                    .then((res) => {
                        this.journal_data = 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();
            },
            Searching(e) {
                this.params.search_text = e.target.value;
                this.funGetData();
            },
            funGetDataChartOfAcc() {
                axios
                    .get("accounting/com-chart-of-account")
                    .then((res) => {
                        this.chart_of_account = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },
            funNewJournal() {
                if(this.user_branch == -1){
                    this.$toast.warning('អ្នកកំពុងស្ថិតនៅការិយាល័យកណ្តាល!');
                } else{
                    this.method = false;
                    this.journal_rows = [];
                    this.form = new Form({
                        desc: "",
                        invoice_number: null,
                        journal_date: new Date().toISOString(),
                    });
                    $("#modalAddNew").modal("show");
                }
            },
            addRow: function () {
                this.journal_rows.push({
                    chart_of_acc_id: null,
                    debit: 0,
                    credit: 0,
                });
            },
            removeRowItem: function (index) {
                this.journal_rows.splice(index, 1);
            },
            funDebit(index) {
                if (this.journal_rows[index].credit > 0) {
                    this.journal_rows[index].debit = 0;
                }
                if (this.journal_rows[index].debit > 0) {
                    this.journal_rows[index].credit = 0;
                }
            },
            funCredit(index) {
                if (this.journal_rows[index].credit > 0) {
                    this.journal_rows[index].debit = 0;
                }
                if (this.journal_rows[index].debit > 0) {
                    this.journal_rows[index].credit = 0;
                }
            },
            funSubmitData() {
                if (this.totalDebitJournal != this.totalCreditJournal) {
                    this.$toast.error("Total of debit and credit is not equal!");
                } else {
                    this.form = new Form({
                        journal_rows: this.journal_rows,
                        desc: this.form.desc,
                        invoice_number: this.form.invoice_number,
                        journal_date: this.form.journal_date,
                    });
                    this.form
                        .post("accounting/journals")
                        .then((res) => {
                            this.funGetData();
                            $("#modalAddNew").modal("hide");
                            this.$toast.success(res.data.message);
                        })
                        .catch((error) => {
                            this.$toast.warning(error.data.message);
                        });
                }
            },
            showEditOrDelete(index, value) {
                return (value.payment_model_id == 0 && this.journal_data.data.findIndex(item => item.parent_id === value.parent_id) === index)
            },
            funEditJournal(cat) {
                this.method = true;
                axios
                    .get("accounting/journals/" + cat.parent_id)
                    .then((res) => {
                        this.form.fill(cat);
                        this.journal_rows = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
                $("#modalAddNew").modal("show");
            },
            funUpdateData() {
                if (this.totalDebitJournal != this.totalCreditJournal) {
                    this.$toast.error("Total of debit and credit is not equal!");
                } else {
                    this.isLoading = true;
                    this.form = new Form({
                        id: this.journal_rows[0].parent_id,
                        journal_rows: this.journal_rows,
                        desc: this.form.desc,
                        invoice_number: this.form.invoice_number,
                        journal_date: this.form.journal_date,
                    });
                    this.form
                        .put("accounting/journals/" + this.form.id)
                        .then((res) => {
                            this.$toast.success(res.data.message);
                            this.funGetData();
                            $("#modalAddNew").modal("hide");
                        })
                        .catch((error) => {
                            console.log(error);
                            setTimeout(() => (this.isLoading = false), 200);
                        });
                }
            },
            funDelete(id) {
                this.$confirm({
                    message: "Are you sure?",
                    button: {
                        no: "No",
                        yes: "Yes",
                    },
                    callback: (confirm) => {
                        if (confirm) {
                            this.form.delete("accounting/journals/" + id).then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.funGetData();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            });
                        }
                    },
                });
            },
        },
        computed: {
            sumTotalDebit: function () {
                var sum = 0;
                this.journal_data.data?.forEach((e) => {
                    sum += e.debit;
                });
                return sum;
            },
            sumTotalCredit: function () {
                var sum = 0;
                this.journal_data.data?.forEach((e) => {
                    sum += e.credit;
                });
                return sum;
            },
            totalDebitJournal: function () {
                return this.journal_rows.reduce(function (total, journal) {
                    return total + parseFloat(journal.debit);
                }, 0.0);
            },
            totalCreditJournal: function () {
                return this.journal_rows.reduce(function (total, journal) {
                    return total + parseFloat(journal.credit);
                }, 0.0);
            },
        },
    };
</script>