<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>
                            <th>ល.រ</th>
                            <th>ឈ្មោះទ្រព្យសកម្ម</th>
                            <th>ម៉ាក</th>
                            <th>លេខសម្គាល់</th>
                            <th>កាលបរិច្ឆេទទិញ</th>
                            <th>តម្លៃទិញ</th>
                            <th>រំលស់រយៈពេល/ខែ</th>
                            <th>រយៈពេលបានរំលស់</th>
                            <th>រយៈពេលនៅសល់</th> 
                            <th>ទឹកប្រាក់រំលស់ប្រចាំខែ</th>
                            <th>ទឹកប្រាក់បានរំលស់</th>
                            <th>ទឹកប្រាក់នៅសល់</th>
                            <th>ប្រភេទរំលស់ទ្រព្យ</th>
                            <th>ស្ថានភាពទ្រព្យ</th>
                            <th>ទីតាំងប្រើប្រាស់</th>
                            <th>អ្នកប្រើប្រាស់</th>
                            <th>ផ្សេងៗ</th>
                            <th>សាខា</th>
                            <th>សកម្មភាព</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template class="text-nowrap" v-for="(value,index) in depreciations.data">
                            <tr>
                                <td class="text-nowrap">{{index+1}}</td>
                                <td class="text-nowrap">{{value.asset_name}}</td>
                                <td class="text-nowrap">{{value.brand}}</td>
                                <td class="text-nowrap">{{value.invoice_number}}</td>
                                <td class="text-nowrap">{{value.depreciation_date | onlyDate}}</td>
                                <td class="text-nowrap">{{value.total_amount | numberFomartValue}}</td>
                                <td class="text-nowrap">{{value.period}} ខែ</td>
                                <td class="text-nowrap">{{value.period_paid}}</td>
                                <td class="text-nowrap">{{value.period_unpaid}}</td>
                                <td class="text-nowrap">{{value.first_payment | numberFomartValue}}</td>
                                <td class="text-nowrap">{{value.total_paid | numberFomartValue}}</td>
                                <td class="text-nowrap">{{value.balance | numberFomartValue}}</td>
                                <td class="text-nowrap">{{value.type_asset_name}}</td>
                                <td class="text-nowrap">{{funStatusAsset(value.status_asset)}}</td>
                                <td class="text-nowrap">{{value.location_using}}</td>
                                <td class="text-nowrap">{{value.user_name}}</td>
                                <td class="text-nowrap">{{value.another}}</td>
                                <td class="text-nowrap">{{value.branch_name}}</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>
                                    <button type="button" v-if="$can('Depreciation Edit')" v-show="value.total_paid==0 && user_branch != -1" @click="funshowForm(value.id)" :title="$t('Edit')" class="btn btn-dark  s-btn-xs">
                                        <i class="fa-solid fa-pen-to-square fa-sm"></i>
                                    </button>
                                    <router-link v-if="$can('Depreciation Print')" :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>
                                <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 class="text-end">{{ $t('Total') }}</th>
                            <th>{{sumAmount | numberFomartValue}}</th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th>{{sumFirstPayment | numberFomartValue}}</th>
                            <th>{{sumTotalPaid | numberFomartValue}}</th>
                            <th>{{sumBalance | numberFomartValue}}</th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></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 DepreciationForm from "./DepreciationForm.vue";
    import CumstomPagination from "../../../components/CustomPagination.vue";
    import ThemeTable from "../../../components/ThemeTable.vue";
    export default {
        components: {
            CumstomPagination,
            DepreciationForm,
            ThemeTable,
        },
        data() {
            return {
                depreciations: { data: [] }, 
                user_branch : '',
                form: new Form({
                    id: "",
                    desc: "",
                    asset_id: "",
                    asset_name:"",
                    currency_id: "",
                    branch_id: "",
                    amount: "",
                    period: "",
                    pay_money: "",
                    chart_asset: "",
                    chart_expense: "",
                    payment_date: "",
                    depreciation_date: new Date().toISOString(),
                    arr_depreciation: [],
                    status_asset:'',
                    brand:'',
                    location_using:'',
                    user_name:'',
                    another:'',
                    invoice_number:'',
                }),
                //Toggle
                opened: [],
                tropened: false,
                deprec_details: [],
                params: {
                    page: 1,
                    per_page: 25,
                    search_text: "",
                },
            };
        },
        created() {
            this.funGetData();
            this.funCurrency();
            this.funComUserBranch();
        },
        computed: {
            sumAmount: function () {
                var sum = 0;
                this.depreciations.data.forEach(function (item) {
                    sum += parseFloat(item.total_amount);
                });
                return sum;
            },
            sumFirstPayment: function () {
                var sum = 0;
                this.depreciations.data.forEach(function (item) {
                    sum += parseFloat(item.first_payment);
                });
                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: {
            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();
            },
            funStatusAsset(status){
                if(status==1){
                    return 'ថ្មី';
                }else if(status==2){
                    return 'ចាស់';
                }else if(status==3){
                    return 'មួយទឹក';
                }
            },
            funCurrency() {
                axios.get("admin-api/default-currency").then((res) => {
                    this.form.currency_id = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            funshowForm(id) {
                if(this.user_branch == -1){
                    this.$toast.warning('អ្នកកំពុងស្ថិតនៅការិយាល័យកណ្តាល!');
                } else {
                    if(id){
                        axios.get("accounting/depreciation/create", {
                            params: { id: id },
                        }).then((res) => {
                            if (res.data.status == 1) {
                                this.form.fill(res.data.data);
                                this.form.arr_depreciation = res.data.data.details;
                            }
                        }).catch((error) => {
                            if (error.message == "Request failed with status code 403") {
                                this.$router.push({ name: "permissionTest" });
                            } else {
                                console.log(error.message);
                            }
                        });
                    } else{
                        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.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>