<template>
    <theme-table :permisName="'Depreciation Create'" :newButton="true" @click="funshowForm" @input="Searching">
        <span slot="main-title">
            {{ $t('Depreciation List') }}
        </span>

        <div slot="body">
            <div class="table-responsive table_scroll">
                <table class="table table-bordered">
                    <thead class="text-nowrap fixed_table">
                        <tr class="text-nowrap">
                            <th>{{ $t("#") }}</th>
                            <th>{{ $t("Type Depreciation") }}</th>
                            <th>{{ $t("Period") }}</th>
                            <th>{{ $t("Depreciation Date") }}</th>
                            <th>{{ $t("Create Date") }}</th>
                            <th>{{ $t("Description") }}</th>
                            <th>{{ $t("Create By") }}</th>
                            <th>{{ $t("Chart Asset") }}</th>
                            <th>{{ $t("Chart Expense") }}</th>
                            <th>{{ $t("Total Amount") }}</th>
                            <th>{{ $t("Total Paid") }}</th>
                            <th>{{ $t("Remain Balance") }}</th>
                            <th>{{ $t("Action") }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template class="text-nowrap" v-for="(value,index) in depreciations.data">
                            <tr>
                                <td>{{index+1}}</td>
                                <td>{{value.asset_name}}</td>
                                <td>{{value.period}} ខែ</td>
                                <td class="text-nowrap">{{value.depreciation_date | onlyDate}}</td>
                                <td class="text-nowrap">{{value.created_at | onlyDate}}</td>
                                <td>{{value.desc}}</td>
                                <td>{{value.created_by}}</td>
                                <td>({{value.asset_code}}) {{value.acc_asset_name}}</td>
                                <td>({{value.expense_code}}) {{value.expense_name}}</td>
                                <td>{{value.total_amount | numberFomartValue}}</td>
                                <td>{{value.total_paid | numberFomartValue}}</td>
                                <td>{{value.balance | numberFomartValue}}</td>
                                <td class="text-nowrap">
                                    <button @click="funToggle(value.id)" :class="{ opened: opened.includes(value.id) }" :title="$t('Show')" class="btn btn-danger btn-sm s-btn-xs mr-1">
                                        <i class="fa-solid fa-eye fa-sm"></i>
                                    </button>
                                    <router-link :to="{ name: 'PrintSchedule', params: { id: value.id } }" class="btn btn-success s-btn-xs" :title="$t('Schedule')">
                                        <i class="fa-solid fa-file-invoice fa-sm"></i>
                                    </router-link>
                                </td>
                            </tr>
                            <tr v-if="opened.includes(value.id)" v-show="tropened==true">
                                <th>{{ $t("#") }}</th>
                                <th class="text-nowrap">{{ $t('Payment Date') }}</th>
                                <th class="text-nowrap">{{ $t('Amount') }}</th>
                                <th class="text-nowrap">{{ $t('Paid') }}</th>
                                <th class="text-nowrap">{{ $t('Unpaid') }}</th>
                                <th class="text-nowrap">{{ $t('Remain Balance') }}</th>
                                <th class="text-nowrap">{{ $t("Action") }}</th>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr v-for="(val,i) in deprec_details" v-if="opened.includes(value.id)">
                                <td>{{i+1}}</td>
                                <td class="text-nowrap">{{val.payment_date | onlyDate}}</td>
                                <td>{{val.amount | numberFomartValue}}</td>
                                <td>{{val.paid | numberFomartValue}}</td>
                                <td>{{val.unpaid | numberFomartValue}}</td>
                                <td>{{val.loan_balance | numberFomartValue}}</td>
                                <td>
                                    <div class="d-flex">
                                        <strong v-show="val.status == 2" class="text-danger mx-1 px-1 py-0">
                                            <i class="fa-sharp fa-solid fa-check"></i>
                                        </strong>
                                        <button v-show="val.unpaid>0" @click="funPayDepreciation(val.id)" class="mx-1 px-1 py-0 btn btn-sm btn-outline-info">
                                            {{ $t('Payment') }}
                                        </button>
                                    </div>
                                </td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        </template>
                        <tr class="table-active" v-show="tropened==false">
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th class="text-end">{{ $t('Total') }}</th>
                            <th>{{sumAmount | numberFomartValue}}</th>
                            <th>{{sumTotalPaid | numberFomartValue}}</th>
                            <th>{{sumBalance | numberFomartValue}}</th>
                            <th></th>
                        </tr>
                    </tbody>
                </table>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="depreciations" @onChangePage="funGetData($event)"></cumstom-pagination>
        </div>

        <div slot="modal-custom">
            <depreciation-form :form="form" @submitData="submitData"></depreciation-form>
        </div>
    </theme-table>
</template>
<script>

    import ActiveStatus from "../../../components/ActiveStatus.vue";
    import DepreciationForm from "./DepreciationForm.vue";
    import CumstomPagination from "../../../components/CustomPagination.vue";
    import ThemeTable from "../../../components/ThemeTable.vue";
    export default {
        components: {
            ActiveStatus,

            CumstomPagination,
            DepreciationForm,
            ThemeTable,
        },
        data() {
            return {
                depreciations: { data: [] },
                form: new Form({
                    id: "",
                    desc: "",
                    asset_id: "",
                    currency_id: "",
                    branch_id: "",
                    amount: "",
                    period: "",
                    pay_money: "",
                    chart_asset: "",
                    chart_expense: "",
                    payment_date: "",
                    depreciation_date: new Date().toISOString(),
                    arr_depreciation: [],
                }),
                //Toggle
                opened: [],
                tropened: false,
                deprec_details: [],
                params: {
                    page: 1,
                    per_page: 25,
                    search_text: "",
                },
            };
        },
        created() {
            this.funGetData();
            this.funCurrency();
        },
        computed: {
            sumAmount: function () {
                var sum = 0;
                this.depreciations.data.forEach(function (item) {
                    sum += parseFloat(item.total_amount);
                });
                return sum;
            },
            sumTotalPaid: function () {
                var sum = 0;
                this.depreciations.data.forEach(function (item) {
                    sum += parseFloat(item.total_paid);
                });
                return sum;
            },
            sumBalance: function () {
                var sum = 0;
                this.depreciations.data.forEach(function (item) {
                    sum += parseFloat(item.balance);
                });
                return sum;
            },
        },
        methods: {
            funCurrency() {
                axios
                    .get("admin-api/default-currency")
                    .then((res) => {
                        this.form.currency_id = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },
            funGetData(page = 1) {
                this.params.page = page;
                axios
                    .get("accounting/depreciation", {
                        params: this.params,
                    })
                    .then((res) => {
                        this.depreciations = res.data;
                    })
                    .catch((error) => {
                        if (error.message == "Request failed with status code 403") {
                            this.$router.push({ name: "permissionTest" });
                        } else {
                            console.log(error.message);
                        }
                        console.log(error);
                    });
            },
            PageChange: function (e) {
                this.params.per_page = e.target.value;
                this.funGetData();
            },
            Searching(e) {
                this.params.search_text = e.target.value;
                this.funGetData();
            },
            funshowForm() {
                // this.form.reset();
                this.form.asset_id = "";
                this.form.amount = "";
                this.form.chart_asset = "";
                this.form.chart_expense = "";
                this.form.desc = "";
                this.form.period = "";
                this.form.pay_money = "";
                this.form.payment_date = "";
                this.form.arr_depreciation = [];
                $("#depreciationForm").modal("show");
            },
            submitData() {
                if (this.form.arr_depreciation == "") {
                    this.$toast.warning("Please generate period!");
                } else {
                    this.form = new Form({
                        asset_id: this.form.asset_id,
                        chart_asset: this.form.chart_asset,
                        chart_expense: this.form.chart_expense,
                        amount: this.form.amount,
                        desc: this.form.desc,
                        pay_money: this.form.pay_money,
                        period: this.form.period,
                        payment_date: this.form.payment_date,
                        arr_depreciation: this.form.arr_depreciation,
                        depreciation_date: this.form.depreciation_date,
                    });
                    this.form
                        .post("accounting/depreciation")
                        .then((res) => {
                            if (res.data.status == 1) {
                                this.$toast.success(res.data.message);
                                $("#depreciationForm").modal("hide");
                                this.funGetData();
                            } else {
                                this.$toast.warning(res.data.message);
                            }
                        })
                        .catch((error) => {
                            console.log(error);
                        });
                }
            },
            funToggle(id) {
                const index = this.opened.indexOf(id);
                if (index > -1) {
                    this.tropened = false;
                    this.opened.splice(index, 1);
                } else {
                    axios
                        .get("accounting/depreciation/" + id)
                        .then((res) => {
                            this.deprec_details = res.data.data.details;
                        })
                        .catch((err) => console.log(err));
                    this.opened.push(id);
                    this.tropened = true;
                }
            },
            funPayDepreciation(id) {
                this.$confirm({
                    message: "Are you sure, You want to pay it?",
                    button: {
                        no: "No",
                        yes: "Yes",
                    },
                    callback: (confirm) => {
                        if (confirm) {
                            this.form.post("accounting/submit-payment-depreciation/" + id).then((res) => {
                                this.$toast.success(res.data.message);
                                const index = this.opened.indexOf(id);
                                this.tropened = false;
                                this.opened.splice(index, 1);
                                this.funGetData();
                            });
                        }
                    },
                });
            },
        },
    };
</script>
