<template>
    <theme-dailog :modalId="'depreciationForm'" :title="'Depreciation List'" :loading="form.busy" @submitData="$emit('submitData')" data-bs-backdrop="static">
        <div slot="modal-body">
            <div class="row">
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Type of Asset Depreciation') }} <span class="text-danger">*</span></label>
                    <Multiselect
                        :class="{'is-invalid': form.errors.has('asset_id') }"
                        :placeholder="$t('Type of Asset Depreciation')"
                        :disabled="form.can_edit ==false"
                        :searchable="true"
                        :reduce="group_assets => group_assets.id"
                        :options="group_assets"
                        label="asset_name"
                        v-model="form.asset_id">
                        <span slot="no-options" >
                            {{$t('No Data')}}
                        </span>
                    </Multiselect>
                    <div class="valid text-danger" v-if="form.errors.has('asset_id')" v-html="form.errors.get('asset_id')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Brand') }}</label>
                    <input type="text" class="form-control" v-model="form.brand" :placeholder="$t('Brand')" :class="{'is-invalid': form.errors.has('brand') }">
                    <div class="valid text-danger" v-if="form.errors.has('brand')" v-html="form.errors.get('brand')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Asset Name') }}</label>
                    <input type="text" class="form-control" v-model="form.asset_name" :placeholder="$t('Asset Name')" :class="{'is-invalid': form.errors.has('asset_name') }">
                    <div class="valid text-danger" v-if="form.errors.has('asset_name')" v-html="form.errors.get('asset_name')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Status Asset') }}</label><Multiselect
                    v-model="form.status_asset"
                    :placeholder="$t('Status Asset')"
                    :class="{ 'is-invalid': form.errors.has('status_asset') }"
                    trackBy="status_asset"
                    value="id"
                    label="status_asset"
                    :searchable="true"
                    :options="[
                    { value: 1, status_asset:'ថ្មី'},
                    { value: 2, status_asset:'ចាស់'},
                    { value: 3, status_asset:'មួយទឹក'},
                ]"
                />
                <div class="valid text-danger" v-if="form.errors.has('form.status_asset')" v-html="form.errors.get('form.status_asset')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Location Using') }}</label>
                    <input type="text" class="form-control" v-model="form.location_using" :placeholder="$t('Location Using')" :class="{'is-invalid': form.errors.has('location_using') }">
                    <div class="valid text-danger" v-if="form.errors.has('location_using')" v-html="form.errors.get('location_using')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('User') }}</label>
                    <input type="text" class="form-control" v-model="form.user_name" :placeholder="$t('User')" :class="{'is-invalid': form.errors.has('user_name') }">
                    <div class="valid text-danger" v-if="form.errors.has('user_name')" v-html="form.errors.get('user_name')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Depreciation Date') }} <span class="text-danger">*</span></label>
                    <date-picker v-model="form.depreciation_date" valueType="format" @keypress="isNumber($event)" @input="clickdperdate" :format="format" :class="{'is-invalid': form.errors.has('depreciation_date') }"></date-picker>
                    <div class="text-danger" v-if="form.errors.has('depreciation_date')" v-html="form.errors.get('depreciation_date')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{ $t('Total Amount') }} <span class="text-danger">*</span></label>
                    <input type="text" class="form-control number-only" @keypress="isNumber($event)" @click="clickTotal" v-model="form.amount" :class="{'is-invalid': form.errors.has('amount') }">
                    <div class="valid text-danger" v-if="form.errors.has('amount')" v-html="form.errors.get('amount')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label"><strong>{{ $t('Period') }}</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control number-only" @keypress="isNumber($event)"
                                @click="clickPeriod" v-model="form.period" :class="{'is-invalid': form.errors.has('period') }">
                    <div class="valid text-danger" v-if="form.errors.has('period')" v-html="form.errors.get('period')"></div>
                </div>
                <div class="col-sm-4 mb-3">
                    <label class="form-label"><strong>{{ $t('Payment Date') }}</strong> <span class="text-danger">*</span></label>
                    <date-picker v-model="form.payment_date" valueType="format" @keypress="isNumber($event)" @input="clickdatepayment" :format="format" :class="{'is-invalid': form.errors.has('payment_date') }"></date-picker>
                    <div class="text-danger" v-if="form.errors.has('payment_date')" v-html="form.errors.get('payment_date')"></div>
                </div>

                <div class="col-sm-4 mb-3">
                    <label class="form-label">{{$t('Description')}}</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 class="form-label">{{ $t('Another') }}</label>
                    <input type="text" class="form-control" v-model="form.another" :placeholder="$t('Another')" :class="{'is-invalid': form.errors.has('another') }">
                    <div class="valid text-danger" v-if="form.errors.has('another')" v-html="form.errors.get('another')"></div>
                </div>

                <div class="col-sm-4 mb-3">
                    <div class="mb-3">
                        <label class="form-label">គណនីរំលស់បង្គរ <span class="text-danger">*</span></label>
                        <Multiselect
                            :class="{'is-invalid': form.errors.has('chart_asset') }"
                            :placeholder="'គណនីរំលស់បង្គរ'"
                            :disabled="form.can_edit ==false"
                            :searchable="true"
                            :reduce="get_acc_assets => get_acc_assets.id"
                            :options="get_acc_assets"
                            label="chart_code_name"
                            v-model="form.chart_asset">
                            <span slot="no-options" >
                                {{$t('No Data')}}
                            </span>
                        </Multiselect>
                        <div class="valid text-danger" v-if="form.errors.has('chart_asset')" v-html="form.errors.get('chart_asset')"></div>
                    </div>
                </div>
                <div class="col-sm-4 mb-3">
                    <div class="mb-3">
                        <label class="form-label">គណនីចំណាយ <span class="text-danger">*</span></label>
                        <Multiselect
                            :class="{'is-invalid': form.errors.has('chart_expense') }"
                            :placeholder="'គណនីចំណាយ'"
                            :disabled="form.can_edit ==false"
                            :searchable="true"
                            :reduce="get_acc_expense => get_acc_expense.id"
                            :options="get_acc_expense"
                            label="chart_code_name"
                            v-model="form.chart_expense">
                            <span slot="no-options" >
                                {{$t('No Data')}}
                            </span>
                        </Multiselect>
                        <div class="valid text-danger" v-if="form.errors.has('chart_expense')" v-html="form.errors.get('chart_expense')"></div>
                    </div>
                </div>
                <!-- Generate Button -->
                <div
                    class="col-xl-2 col-lg-6 col-md-6 col-12"
                    v-show="generateTrue == true"
                >
                    <div class="mb-3">
                        <label class="form-label">
                            <strong>{{ $t("Generate") }}</strong><sup class="text-danger">*</sup>
                        </label>
                        <input
                            type="button"
                            class="form-control btn btn-success border-primary"
                            @click="generateDepreciation()"
                            value="Generate"
                        />
                    </div>
                </div>

                <!-- Clear Button -->
                <div
                    class="col-xl-2 col-lg-6 col-md-6 col-12"
                    v-show="clearFalse == true"
                >
                    <div class="mb-3">
                        <label class="form-label">
                            <strong>{{ $t("Clear") }}</strong>
                        </label>
                        <input
                            type="button"
                            class="form-control btn btn-danger"
                            @click="clearDepreciation()"
                            value="Clear"
                        />
                    </div>
                </div>

            </div>
            <!-- <hr>
            <div class="row">
                <div class="col-sm-4 mb-3">
                    <label class="form-label"><strong>{{ $t('Amount') }}</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control number-only" v-model="form.pay_money" :class="{'is-invalid': form.errors.has('pay_money') }">
                    <div class="valid text-danger" v-if="form.errors.has('pay_money')" v-html="form.errors.get('pay_money')"></div>
                </div>
            </div> -->
            <hr>
            <div class="row">
                <div class="col-sm-12">
                    <table style="width: 100%" class="table table-bordered">
                        <thead>
                            <tr>
                                <th>{{ $t("#") }}</th>
                                <th>{{ $t('Payment Date') }}</th>
                                <th>{{ $t('Amount') }}</th>
                                <th>{{ $t('Remain Balance') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(value,index) in form.arr_depreciation" :key="index">
                                <td>{{index+1}}</td>
                                <td>
                                    <date-picker v-model="value.payment_date" valueType="format" :format="format" :class="{'is-invalid': form.errors.has('payment_date') }"></date-picker>
                                </td>
                                <td>
                                    <input type="text" :value="value.payment_amount | numberFomartValue" class="form-control" disabled />
                                </td>
                                <td>
                                    <input type="text" :value="value.loan_balance | numberFomartValue" class="form-control" disabled />
                                </td>
                            </tr>

                            <tr v-show="generateTrue == false">
                                <td></td>
                                <td class="text-end">
                                    <strong>{{ $t('Total') }}</strong>
                                </td>
                                <td>
                                    <input type="text" disabled class="form-control text-bold text-primary" :value="totalAmount | numberFomartValue" />
                                </td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>    
                </div>
            </div>
        </div>
    </theme-dailog>
</template>
<script>
import ThemeDailog from "../../../components/model-dialog/ThemeDailog.vue";
var moment = require("moment");
export default {
    props: {
        form: {},
    },
    components: {
        ThemeDailog,
    },
    data() {
        return {
            moment : moment,
            format : 'YYYY-MM-DD',

            group_assets : [],
            get_acc_assets : [],
            get_acc_expense : [],
            clearFalse: false, 
            generateTrue: true,
        }
    },
    created() {
        this.getGroupAsset();
        this.getGroupAccAsset();
        this.getGroupAccExpense();
    },
    computed:{
        totalAmount: function(){
            return this.form.arr_depreciation.reduce(function(total, item){
                return (total + parseFloat(item.payment_amount));
            },0.00);
        },
    },
    methods: {
        getGroupAsset() {
            axios.get('accounting/get-asset').then((res) => {
                this.group_assets = res.data;
            }).catch((error) => {
                console.log(error);
            });
        },
        getGroupAccAsset() {
            axios.get('accounting/get-acc-fixed-asset').then((res) => {
                this.get_acc_assets = res.data;
            }).catch((error) => {
                console.log(error);
            });
        },
        getGroupAccExpense() {
            axios.get('accounting/get-acc-expense').then((res) => {
                this.get_acc_expense = res.data;
            }).catch((error) => {
                console.log(error);
            });
        },
        clickdperdate() {
            this.clearDepreciation();
        },
        clickdatepayment() {
            this.clearDepreciation();
        },
        clickTotal() {
            this.clearDepreciation();
        },
        isNumber: function (evt) {
            evt = evt ? evt : window.evt;
            var charCode = evt.which ? evt.which : evt.keyCode;
            if (
                charCode > 31 &&
                (charCode < 48 || charCode > 57) &&
                charCode !== 46
            ) {
                evt.preventDefault();
            } else {
                return true;
            }
        },
        clickPeriod() {
            this.clearDepreciation();
            this.form.period = this.form.period == 0 ? "" : this.form.period;
        },
        // , periodInMoney = this.form.pay_money
        generateDepreciation(totalAmountPeriod = this.form.amount, periodInMonth = this.form.period, paymentDate = this.form.payment_date){
            this.clearFalse = true;
            this.generateTrue = false;
            if(this.form.currency_id==2)
            {
                if(totalAmountPeriod>0 && paymentDate != '')
                {
                    var totalAmount = parseFloat(totalAmountPeriod);
                    var paymentEachMonth = parseFloat(totalAmount/periodInMonth).toFixed(2);
                    var monthStep = 0;
                    for(var i=1; i<= periodInMonth; i++)
                    {
                        if(i!=periodInMonth){
                            var loan_balance  =  totalAmount - paymentEachMonth;
                            totalAmount       =  totalAmount - paymentEachMonth;
                            var object = {
                                payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                payment_amount : parseFloat(paymentEachMonth).toFixed(2),
                                loan_balance   : parseFloat(loan_balance).toFixed(2),
                            }
                            this.form.arr_depreciation.push(object);
                        }
                        else{
                            var object = {
                                payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                payment_amount : parseFloat(totalAmount).toFixed(2),
                                loan_balance   : parseFloat(totalAmount - totalAmount).toFixed(2),
                            }
                            this.form.arr_depreciation.push(object);
                        }
                        monthStep++;
                    }
                }
            }
            else
            {
                if(totalAmountPeriod>0 && paymentDate != '')
                {
                    var totalAmount = totalAmountPeriod;
                    var paymentEachMonth = Math.floor((totalAmount/periodInMonth)/100)*100;
                    var monthStep = 0;
                    for(var i=1; i<= periodInMonth; i++)
                    {
                        if(i!=periodInMonth){
                            var loan_balance  =  totalAmount - paymentEachMonth;
                            totalAmount       =  totalAmount - paymentEachMonth;
                            var object = {
                                payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                payment_amount : paymentEachMonth,
                                loan_balance   : loan_balance,
                            }
                            this.form.arr_depreciation.push(object);
                        }
                        else{
                            var object = {
                                payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                payment_amount : totalAmount,
                                loan_balance   : totalAmount - totalAmount,
                            }
                            this.form.arr_depreciation.push(object);
                        }
                        monthStep++;
                    }
                }
            }
        },
        clearDepreciation(){
            this.form.arr_depreciation = [];
            this.clearFalse = false;
            this.generateTrue = true;
        },
    },
}
</script>
