<template>
    <theme-table :newButton="true" :permisName="'Income List'" @click="funNewIncome()" @input="Searching">
        <span slot="main-title">
            {{ $t('Income List') }}
        </span>
        <div slot="body">
            <div class="table-responsive table_scroll">
                <table class="table table-bordered">
                    <thead>
                        <tr class="border-top border-bottom text-nowrap">
                            <th>{{ $t("#") }}</th>
                            <th>{{ $t("Invoice Number") }}</th>
                            <th>{{ $t("Income Date") }}</th>
                            <th>{{ $t("Description") }}</th>
                            <th>{{ $t("Created By") }}</th>
                            <th>{{ $t("Chart Name") }}</th>
                            <th>{{ $t("Debit") }}</th>
                            <th>{{ $t("Credit") }}</th>
                            <th class="text-nowrap hidden_p">{{ $t("Action") }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template v-for="(value,index) in income_data.data">
                            <template v-for="(sub,sub_index) in value.sub_income">
                                <tr>
                                    <td><template v-if="(sub_index==0)">{{index+1}} </template></td>
                                    <td><template v-if="(sub_index==0)">{{value.invoice_number}} </template></td>
                                    <td><template v-if="(sub_index==0)">{{value.income_date | onlyDate}} </template></td>
                                    <td><template v-if="(sub_index==0)">{{value.desc}} </template></td>
                                    <td><template v-if="(sub_index==0)">{{value.created_by}} </template></td>
                                    <td class="text-nowrap">({{sub.chart_code}}) {{sub.chart_name}}</td>
                                    <td class="text-nowrap">{{sub.debit==0?0: sub.debit | numberFomartValue}}</td>
                                    <td class="text-nowrap">{{sub.credit==0?0: sub.credit | numberFomartValue}}</td>
                                    <td class="text-nowrap hidden_p">
                                        <template v-if="(sub_index==0)">
                                            <button v-if="$can('Income Edit')" @click="funEditIncome(value)" v-show="value.payment_model_id==0" class="btn btn-dark btn-sm s-btn-xs">
                                                <i class="fa-solid fa-pen-to-square fa-sm"></i>
                                            </button>
                                            <button v-if="$can('Income Delete')" @click="funDelete(value.parent_id)" v-show="value.payment_model_id==0" type="button" class="btn btn-danger btn-sm s-btn-xs">
                                                <i class="fa-solid fa-trash-can fa-sm"></i>
                                            </button>
                                        </template>
                                    </td>
                                </tr>
                            </template>
                        </template>
                    </tbody>
                </table>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="income_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-xl">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">{{ $t("Income") }}</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-3 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-3 mb-3">
                                        <label>{{ $t("Income Date") }} <span class="text-danger">*</span></label>
                                        <date-picker v-model="form.income_date" valueType="format" :format="format" :class="{'is-invalid': form.errors.has('income_date') }"></date-picker>
                                        <div class="text-danger" v-if="form.errors.has('income_date')" v-html="form.errors.get('income_date')"></div>
                                    </div>
                                    <div class="col-sm-3 mb-3">
                                        <label>{{ $t("Income") }} <span class="text-danger">*</span></label>
                                        <Multiselect :placeholder="$t('Chart Code')" :searchable="true" :options="dataIncomes" label="chart_code_name" trackBy="chart_code_name" value="id" v-model="form.chart_of_acc_id" />
                                    </div>
                                    <div class="col-sm-3 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-12 mb-2 text-end" v-show="this.method==false">
                                    </div>
                                    <div class="col-12">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>{{ $t("#") }}</th>
                                                    <th>{{$t("Chart Code")}}</th>
                                                    <th>{{$t("Amount")}}</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr v-for="(row,index) in income_rows" :key="index">
                                                    <td style="width:5%">{{index+1}}</td>
                                                    <td style="width:50%">
                                                        <Multiselect
                                                            :class="{'is-invalid': form.errors.has('income_rows.'+index+'.chart_of_acc_id') }"
                                                            :placeholder="$t('Chart Code')"
                                                            :disabled="form.can_edit ==false"
                                                            :searchable="true"
                                                            :options="dataCashBanks"
                                                            label="chart_code_name"
                                                            trackBy="chart_code_name"
                                                            value="id"
                                                            v-model="row.chart_of_acc_id"
                                                        />
                                                    </td>
                                                    <td style="width: 20%">
                                                        <input type="number" step="any" v-model="row.debit" class="form-control number-only" :class="{'is-invalid': form.errors.has('income_rows.'+index+'.debit') }" />
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" class="text-end"><strong>{{$t("Total")}}</strong></td>
                                                    <td><strong>{{totalDebitIncome | numberFomartValue}}</strong></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal"><img src="/icons/b_drop.png" alt="" /> {{ $t("Close") }}</button>
                                <button type="button" :disabled="params.busy||income_rows==''" class="btn btn-primary" @click="method? funUpdateData() : funSubmitData()">
                                    <img :src="params.busy ? ' /icons/loading.gif ' : '/icons/save.png'" alt="" />
                                    {{$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 {
                isLoading: false,
                method: false,
                format: "YYYY-MM-DD",
                income_data: { data: [] },
                dataCashBanks: [],
                dataIncomes: [],
                form: new Form({
                    id: "",
                    desc: "",
                    chart_of_acc_id: null,
                    debit: null,
                    credit: null,
                    income_date: new Date().toISOString(),
                    invoice_number: null,
                }),
                income_rows: [
                    {
                        id: "",
                        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.funGetCashBank();
            this.funGetIncome();
        },
        computed: {
            totalDebitIncome: function () {
                return this.income_rows.reduce(function (total, journal) {
                    return total + parseFloat(journal.debit);
                }, 0.0);
            },
            totalCreditIncome: function () {
                return this.income_rows.reduce(function (total, journal) {
                    return total + parseFloat(journal.credit);
                }, 0.0);
            },
        },
        methods: {
            funGetData(page = 1) {
                this.params.page = page;
                axios
                    .get("accounting/incomes", {
                        params: this.params,
                    })
                    .then((res) => {
                        this.income_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();
            },
            funGetCashBank() {
                axios
                    .get("accounting/com-cash-bank")
                    .then((res) => {
                        this.dataCashBanks = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },
            funGetIncome() {
                axios
                    .get("accounting/com-income")
                    .then((res) => {
                        this.dataIncomes = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },
            funNewIncome() {
                this.method = false;
                (this.income_rows = []),
                    (this.form = new Form({
                        desc: "",
                        invoice_number: null,
                        income_date: new Date().toISOString(),
                    }));
                this.income_rows.push({
                    chart_of_acc_id: null,
                    debit: 0,
                    credit: 0,
                });
                $("#modalAddNew").modal("show");
            },
            funSubmitData() {
                this.form = new Form({
                    income_rows: this.income_rows,
                    desc: this.form.desc,
                    chart_of_acc_id: this.form.chart_of_acc_id,
                    invoice_number: this.form.invoice_number,
                    income_date: this.form.income_date,
                });
                this.form
                    .post("accounting/incomes")
                    .then((res) => {
                        this.funGetData();
                        $("#modalAddNew").modal("hide");
                        this.$toast.success(res.data.message);
                    })
                    .catch((error) => {
                        this.$toast.warning(error.data.message);
                    });
            },
            funEditIncome(cat) {
                this.method = true;
                axios
                    .get("accounting/incomes/" + cat.parent_id)
                    .then((res) => {
                        this.form.fill(cat);
                        console.log(cat);
                        this.income_rows = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
                $("#modalAddNew").modal("show");
            },
            funUpdateData() {
                this.isLoading = true;
                this.form = new Form({
                    id: this.form.id,
                    parent_id: this.income_rows[0].parent_id,
                    chart_of_acc_id: this.form.chart_of_acc_id,
                    income_rows: this.income_rows,
                    desc: this.form.desc,
                    invoice_number: this.form.invoice_number,
                    income_date: this.form.income_date,
                });
                this.form
                    .put("accounting/incomes/" + this.form.id)
                    .then((res) => {
                        if (res.data.status == 1) {
                            this.$toast.success(res.data.message);
                            this.funGetData();
                        } else {
                            this.$toast.warning(res.data.message);
                        }
                        $("#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/incomes/" + id).then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.funGetData();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            });
                        }
                    },
                });
            },
        },
    };
</script>
