<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Cashier Received') }}
        </span>
        <template slot="more-button">
            <button type="button" title="បេឡាទទួលលុយ" @click="funApprove()" v-show="user_branch != -1" :disabled="this.form.checkBox == ''" class="btn btn-success me-2">
                បេឡាទទួលលុយ
            </button>
            <button class="btn btn-secondary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">{{$t('Filter')}}</button>
            <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="offcanvasRightLabel">{{$t('Filter')}}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Client') }}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.client_id" trackBy="name" value="id" label="name" :searchable="true" :options="clients" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Co') }}</label>
                        <Multiselect mode="tags" :close-on-select="false" v-model="params.co_id" trackBy="name" value="id" label="name" :searchable="true" :options="coes" />
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ $t('Status') }}</label>
                        <Multiselect
                            v-model="params.status_approve"
                            :placeholder="$t('Status')"
                            trackBy="status_approve"
                            value="id"
                            label="status_approve"
                            :searchable="true"
                            :options="[{ value: 1, status_approve: 'មិនទាន់អនុញ្ញាត' }, { value: 2, status_approve:'បានអនុញ្ញាត' }]"
                        />
                    </div>
                    <label class="form-label">{{ $t('Received Date') }}</label>
                    <div class="mb-3 d-flex">
                        <date-picker class="me-1" :range="true" :placeholder="$t('Received Date')" v-model="params.date" valueType="format" format="YYYY-MM-DD"> </date-picker>
                        <button type="button" class="btn border btn-sm text-nowrap py-0" data-bs-toggle="modal" data-bs-target="#modalFilter">
                            <i class="fas fa-sm fa-filter"></i> {{ $t('Filter') }}
                        </button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" class="btn btn-success" @click="funSearchData"><i class="fa fa-search"></i> {{ $t('Search') }}</button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" @click="printP" class="btn btn-primary"><i class="fa fa-print"></i> {{ $t('Print') }}</button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" @click="exportExcell" class="btn btn-danger"><i class="fa fa-file-export"></i> {{ $t('Export') }}</button>
                    </div>
                </div>
            </div>
        </template>
        <div slot="body">
            <div id="show-print">
                <div class="table-responsive table_scroll report_print">
                    <header-report :title="$t('Cashier Received')" style="display: none;"></header-report>
                    <table class="table table-hover table-bordered" id="excel-table">
                        <thead class="text-nowrap fixed_table" :class="isCheckAll?'table-primary border-light-subtle': ''">
                            <tr>
                                <th class="no-export" v-if="user_branch != -1">
                                    <input type="checkbox" @click="checkAll()" v-model="isCheckAll" />
                                </th>
                                <th>{{ $t("#") }}</th>
                                <th>{{ $t("CO Name") }}</th>
                                <th>{{ $t("Client Name") }}</th>
                                <th>{{ $t("Received Date") }}</th>
                                <th>{{ $t("Payment Method") }}</th>
                                <th>{{ $t("Principal") }}</th>
                                <th v-if="user_type==1">{{ $t("Interest") }}</th>
                                <th v-if="user_type==1">{{ $t("Operating Services") }}</th>
                                <th>{{ $t("Received") }}</th>
                                <th>{{ $t("Penalty") }}</th>
                                <th>{{ $t("Total Received") }}</th>
                                <th>{{ $t("Remak") }}</th>
                                <th>{{ $t("Branch") }}</th>
                                <th>{{ $t("Status") }}</th>
                            </tr>
                        </thead>
                        <tbody class="text-nowrap">
                            <tr v-for="(acc, index) in dataPayments.data" :key="index">
                                <td class="no-export" v-if="user_branch != -1">
                                    <input type="checkbox" :value="acc" v-model="form.checkBox" v-if="acc.status==1" />
                                </td>
                                <td>{{ index + 1 }}</td>
                                <td>{{ acc.co_name}}</td>
                                <td>{{ acc.client_name}}</td>
                                <td>{{ acc.received_date | onlyDate}}</td>
                                <td>{{ acc.payment_method}}</td>
                                <td>{{ acc.paid_principal | numberFomartValue }}</td>
                                <td v-if="user_type==1">{{ acc.paid_interest | numberFomartValue }}</td>
                                <td v-if="user_type==1">{{ acc.paid_operating_service | numberFomartValue }}</td>
                                <td>{{ acc.received | numberFomartValue }}</td>
                                <td>{{ acc.paid_penalty | numberFomartValue }}</td>
                                <td>{{ acc.total_collected | numberFomartValue }}</td>
                                <td>{{ acc.note}}</td>
                                <td>{{ acc.branch_name}}</td>
                                <td :class="acc.status==1?'text-danger':'text-success'">{{ acc.status==1?'មិនទាន់អនុញ្ញាត':'បានអនុញ្ញាត' }}</td>
                            </tr>
                            <tr class="table-active">
                                <td class="no-export"></td>
                                <td :colspan="user_branch!=-1?5:4" class="text-end">{{ $t("Total") }}</td>
                                <td>{{totalPrincipal | numberFomartValue}}</td>
                                <td v-if="user_type==1">{{totalInterest | numberFomartValue}}</td>
                                <td v-if="user_type==1">{{totalOperatService | numberFomartValue}}</td>
                                <td>{{totalReceived | numberFomartValue}}</td>
                                <td>{{totalPenalty | numberFomartValue}}</td>
                                <td>{{totalCollected | numberFomartValue}}</td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>
                    <footer-report style="display: none;"></footer-report>
                </div>
            </div>
            <cumstom-pagination :pageShow="true" @PageChange="PageChange($event)" :data="dataPayments" @onChangePage="funGetData($event)"></cumstom-pagination>
        </div>
        <div slot="modal-custom">
            <custom-date-filter @chooseDate="chooseDate"></custom-date-filter>
        </div>
    </theme-table>
</template>
<script>
    import CumstomPagination from "../../components/CustomPagination.vue";
    import CustomDateFilter from "../../components/report/CustomDateFilter.vue";
    import HeaderReport from "../../components/report/header.vue";
    import FooterReport from "../../components/report/footer.vue";
    import moment from "moment";
    import ThemeTable from '../../components/ThemeTable.vue';
    import { exportTableToExcel } from "../../exportExcel.js";
    export default {
        components: {
            CumstomPagination,
            CustomDateFilter,
            HeaderReport,
            FooterReport,
            ThemeTable 
        },
        data() {
            return {
                moment: moment,
                format: "YYYY-MM-DD",
                dataPayments: { data: [] },
                clients: [],
                coes: [],
                pagin: false,
                isCheckAll: false,
                user_branch  : '',
                user_type: '',
                form: new Form({
                    id: "",
                    checkBox: [],
                }),
                params: {
                    page: 1,
                    per_page: 25,
                    search_text: "",
                    pagin: false,

                    client_id: [],
                    co_id: [],
                    date: [],
                    status_approve: '',
                },
            };
        },
        created() {
            this.funGetData();
            this.getClient();
            this.getCO();
            this.funComUserBranch();
        },
        methods: {
            checkAll: function () {
                this.form.checkBox = [];
                if (!this.isCheckAll) {
                    if (!this.pagin) {
                        for (var val in this.dataPayments.data) {
                            if (this.dataPayments.data[val].status == 1) {
                                this.form.checkBox.push(this.dataPayments.data[val]);
                            }
                        }
                    } else {
                        for (var val in this.searchCashierReceivedFromCO) {
                            if (this.searchCashierReceivedFromCO[val].status == 1) {
                                this.form.checkBox.push(this.searchCashierReceivedFromCO[val]);
                            }
                        }
                    }
                }
            },
            getClient() {
                axios
                    .get("admin-api/com-client")
                    .then((res) => {
                        this.clients = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },
            getCO() {
                axios
                    .get("admin-api/com-co")
                    .then((res) => {
                        this.coes = res.data;
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            },
            funGetData(page = 1) {
                this.params.page = page;
                axios
                    .get("admin-api/cashier-received", {
                        params: this.params,
                    })
                    .then((res) => {
                        this.dataPayments = 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();
            },
            funSearchData() {
                this.params.pagin = 'true';
                this.funGetData();
            },
            printP() {
                this.$htmlToPaper("show-print");
            },
            chooseDate(value) {
                this.params.date = value.data;
                this.funSearchData();
            },
            funApprove() {
                if(this.form.checkBox.length==0){
                    this.$toast.warning("No data to approve!");
                } else{
                    this.$confirm({
                        message: "Are you sure?",
                        button: {
                            no: "No",
                            yes: "Yes",
                        },
                        callback: (confirm) => {
                            if (confirm) {
                                this.form.post("admin-api/cashier-approve").then((res) => {
                                    if (res.data.status == 1) {
                                        this.$toast.success(res.data.message);
                                        window.location.reload();
                                        this.funGetData();
                                    } else {
                                        this.$toast.warning(res.data.message);
                                    }
                                });
                            }
                        },
                    });
                }
            },
            async exportExcell() {
                this.$isLoading(true)
                try {
                    await exportTableToExcel({
                        tableId: "excel-table",
                        filename: "CashierReceived",
                        reportTitle: "បញ្ជីសង្ខេបបេឡាទទួលប្រាក់",
                        subDate:this.params.date,
                    })
                } catch (e) {
                    this.$toast.warning(e.message);
                } finally {
                    this.$isLoading(false)
                }
            }
        },
        computed: {
            totalPrincipal: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.paid_principal);
                });
                return sum;
            },
            totalInterest: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.paid_interest);
                });
                return sum;
            },
            totalOperatService: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.paid_operating_service);
                });
                return sum;
            },
            // totalMaintenance: function () {
            //     var sum = 0;
            //     this.dataPayments.data.forEach(function (item) {
            //         sum += parseFloat(item.paid_maintenance);
            //     });
            //     return sum;
            // },
            totalReceived: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.received);
                });
                return sum;
            },
            totalPenalty: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.paid_penalty);
                });
                return sum;
            },
            totalWaiv: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.waiv_penalty);
                });
                return sum;
            },
            totalCollected: function () {
                var sum = 0;
                this.dataPayments.data.forEach(function (item) {
                    sum += parseFloat(item.total_collected);
                });
                return sum;
            },
        },
    };
</script>
