<template>
    <theme-dailog :modalId="'depreciationForm'" :title="'Depreciation List'" :loading="form.busy" @submitData="$emit('submitData')">
        <div slot="modal-body">
            <div class="row">
                <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t('Type Depreciation') }} <span class="text-danger">*</span></label>
                    <Multiselect
                        :class="{'is-invalid': form.errors.has('asset_id') }"
                        :placeholder="$t('Type 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-6 mb-3">
                    <label class="form-label">{{ $t('Total Amount') }} <span class="text-danger">*</span></label>
                    <input type="text" class="form-control number-only" 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-6 mb-3">
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Chart Asset') }} <span class="text-danger">*</span></label>
                        <Multiselect
                            :class="{'is-invalid': form.errors.has('chart_asset') }"
                            :placeholder="$t('Chart Asset')"
                            :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-6 mb-3">
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Chart Expense') }} <span class="text-danger">*</span></label>
                        <Multiselect
                            :class="{'is-invalid': form.errors.has('chart_expense') }"
                            :placeholder="$t('Chart Expense')"
                            :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>
                <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t('Depreciation Date') }} <span class="text-danger">*</span></label>
                    <date-picker v-model="form.depreciation_date" valueType="format" :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-6 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="3"></textarea>
                    <div class="text-danger" v-if="form.errors.has('desc')" v-html="form.errors.get('desc')"></div>
                </div>
            </div>
            <hr>
            <div class="row">
                <div class="col-sm-3 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" :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-3 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 class="col-sm-3 mb-3">
                    <label class="form-label"><strong>{{ $t('Period') }}</strong> <span class="text-danger">*</span></label>
                    <input type="text" class="form-control number-only" 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-3 mb-3">
                    <label class="form-label"><strong>{{ $t('Generate')}}</strong><sup class="text-danger">*</sup></label>
                    <input type="button" v-if="form.arr_depreciation.length==0" class="form-control btn-success border-primary" @click="generateDepreciation()" value="Generate" />
                    <button type="button" v-else class="form-control btn-danger" @click="clearDepreciation">{{ $t('Clear') }}</button>
                </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="parseFloat(value.payment_amount).toFixed(2) | numberFomartValue" class="form-control" disabled />
                                </td>
                                <td>
                                    <input type="text" :value="parseFloat(value.loan_balance).toFixed(2) | numberFomartValue" class="form-control" disabled />
                                </td>
                            </tr>

                            <tr>
                                <td></td>
                                <td class="text-end">
                                    <strong>{{ $t('Total') }}</strong>
                                </td>
                                <td>
                                    <input type="text" disabled class="form-control text-bold text-primary" :value="parseFloat(totalAmount).toFixed(2) | 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 : [],
        }
    },
    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);
            });
        },
        generateDepreciation(totalAmountPeriod = this.form.amount, periodInMonth = this.form.period, periodInMoney = this.form.pay_money, paymentDate = this.form.payment_date){
            if(this.form.currency_id==2)
            {
                if(totalAmountPeriod>0 && paymentDate != '')
                {
                    if(periodInMonth != 0 && periodInMoney == 0)
                    {
                        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(periodInMonth == 0 && periodInMoney != 0)
                    {
                        var totalAmount  = parseFloat(totalAmountPeriod);
                        var paymentMoney = totalAmount / periodInMoney;
                        var findPay      = parseFloat(periodInMoney);
                        var monthStep = 0;
                        for(var i=1; i <= paymentMoney; i++){
                            var loan_balance = totalAmount - parseFloat(periodInMoney);
                            totalAmount = totalAmount - parseFloat(periodInMoney);
                            var obJect ={
                                payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                payment_amount : findPay,
                                loan_balance   : loan_balance,
                            }
                            this.form.arr_depreciation.push(obJect);
                            monthStep++

                            if(loan_balance < findPay && loan_balance != 0 ){
                                var obJect ={
                                    payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                    payment_amount : loan_balance,
                                    loan_balance   : loan_balance-loan_balance,
                                }
                                this.form.arr_depreciation.push(obJect);
                            }
                        }
                    }
                    else if(periodInMonth != 0 && periodInMoney != 0){
                        var totalAmount  = parseFloat(totalAmountPeriod);
                        var paymentMoney = totalAmountPeriod / periodInMoney;
                        var findPay = parseFloat(periodInMoney);
                        var monthStep =0;
                        for(var i=1; i <= paymentMoney; i++){
                            var loan_balance = totalAmount - parseFloat(periodInMoney);
                            if(periodInMonth != i){
                                totalAmount = totalAmount - parseFloat(periodInMoney);
                                var obJect ={
                                    payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                    payment_amount : findPay,
                                    loan_balance   : loan_balance,
                                }
                            this.form.arr_depreciation.push(obJect);
                            monthStep++
                            }
                            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);
                                break;
                            }
                            if(loan_balance < findPay && loan_balance != 0 ){
                                var obJect ={
                                    payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                    payment_amount : loan_balance,
                                    loan_balance   : loan_balance-loan_balance,
                                }
                                this.form.arr_depreciation.push(obJect);
                            }
                        }
                    }
                    else{
                        this.$toast.warning('Value Amount or Period must Larger 0');
                    }
                }
                else{
                    this.$toast.warning('Field * is required.');
                }
            }
            else
            {
                if(totalAmountPeriod>0 && paymentDate != '')
                {
                    if(periodInMonth != 0 && periodInMoney == 0)
                    {
                        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++;
                        }
                    }
                    else if(periodInMonth == 0 && periodInMoney != 0)
                    {
                        var totalAmount  = parseFloat(totalAmountPeriod);
                        var paymentMoney = totalAmount / periodInMoney;
                        var findPay      = parseFloat(periodInMoney);
                        var monthStep = 0;
                        for(var i=1; i <= paymentMoney; i++){
                            var loan_balance = totalAmount - parseFloat(periodInMoney);
                            totalAmount = totalAmount - parseFloat(periodInMoney);
                            var obJect ={
                                payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                payment_amount : findPay,
                                loan_balance   : loan_balance,
                            }
                            this.form.arr_depreciation.push(obJect);
                            monthStep++

                            if(loan_balance < findPay && loan_balance != 0 ){
                                var obJect ={
                                    payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                    payment_amount : loan_balance,
                                    loan_balance   : loan_balance-loan_balance,
                                }
                                this.form.arr_depreciation.push(obJect);
                            }
                        }
                    }
                    else if(periodInMonth != 0 && periodInMoney != 0){
                        var totalAmount  = parseFloat(totalAmountPeriod);
                        var paymentMoney = totalAmountPeriod / periodInMoney;
                        var findPay = parseFloat(periodInMoney);
                        var monthStep =0;
                        for(var i=1; i <= paymentMoney; i++){
                            var loan_balance = totalAmount - parseFloat(periodInMoney);
                            if(periodInMonth != i){
                                totalAmount = totalAmount - parseFloat(periodInMoney);
                                var obJect ={
                                    payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                    payment_amount : findPay,
                                    loan_balance   : loan_balance,
                                }
                            this.form.arr_depreciation.push(obJect);
                            monthStep++
                            }
                            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);
                                break;
                            }
                            if(loan_balance < findPay && loan_balance != 0 ){
                                var obJect ={
                                    payment_date   : moment(paymentDate).add(monthStep, "M").format('YYYY-MM-DD'),
                                    payment_amount : loan_balance,
                                    loan_balance   : loan_balance-loan_balance,
                                }
                                this.form.arr_depreciation.push(obJect);
                            }
                        }
                    }
                    else{
                        this.$toast.warning('Value Amount or Period must Larger 0');
                    }
                }
                else{
                    this.$toast.warning('Field * is required.');
                }
            }
        },
        clearDepreciation(){
            this.form.arr_depreciation = [];
        },
    },
}
</script>
