import VueSelect from '/Components/Common/VueSelect.js?v=3.9'
import InputSearch from '/Components/Common/InputSearch.js?v=3.9'
import DatePicker from '/Components/Common/DatePicker.js?v=3.9'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.9'
import OperationsPanel from "/Components/Common/OperationsPanelWrapper.js?v=3.9"
import Pager from '/Components/Common/Pager.js?v=3.9'
import NoRecords from '/Components/Common/NoRecords.js?v=3.9'
import { getLabelText, getAmount } from '/Components/Common/utils.js?v=3.9'
import Loading from "/Components/Common/Loading.js?v=3.9"


export default {
    props: {
        readOnly: { type: Boolean, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
        balanceSignRule: { type: String, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        OperationsPanel,
        SearchPanel,
        VueSelect,
        InputSearch,
        DatePicker,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            paymentGroups: {},
            search: {
                selectedPaymentGroup: '',
                clientId: '',
                customerName: '',
                email: '',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'CustomerId',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    methods: {
        getLabelText,
        getAmount,
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        sortBy: function (exp) {

            if (this.search.sortExpression != exp) {
                this.search.sortExpression = exp;
                this.search.sortDir = "Asc";
            }
            else
                this.search.sortDir = this.search.sortDir == "Asc" ? "Desc" : "Asc";

            this.search.updateSorting = true;
            this.doSearch();
        },
        paymentGroupChangeHandler: function (obj) {

            this.search.selectedPaymentGroup = obj.selectedValue;

        },
        listPaymentGroups: async function () {

            var vm = this;
            
            await fetch("/RCC/Billing/Statments.aspx/GetPaymentGroups", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.paymentGroups = JSON.parse(data.d);
                    this.search.selectedPaymentGroup = this.paymentGroups.initialValue;

                });
            
        },
        listRecords: async function () {

            var vm = this;
            vm.isLoading = true;
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

            await fetch("/RCC/Billing/Statments.aspx/GetStatements", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].RowCounter;
                });
            vm.isLoading = false;
        },
        exportToExcel: function () {
            var vm = this;
            vm.isLoading = true;
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

            fetch("/RCC/Billing/Statments.aspx/ExportToExcel", postRequest)
                .then(response => response.json()).then((data) => {
                    if (data && data.d && data.d != '')
                        window.open('/DownloadHandler.ashx', "_blank");
                    // console.log(data.d);
                })
                .catch(function (e) {
                    vm.isLoading = false;
                    displayErrorMsg(e);
                });
            vm.isLoading = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.selectedPaymentGroup = this.paymentGroups.initialValue;
            this.search.clientId = '';
            this.search.customerName = '';
            this.search.email = '';

            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
    },
    created: async function () {

        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;

        var vm = this;

        await this.listPaymentGroups().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    template: `

        <div class="col-xs-12">
            <div class="card">

                <div class="header">
                    <h3>{{ getLabelText('M0014') }}</h3>
                </div>
                
                <div class="body">
                    <div class="row">

                        <OperationsPanel>
                            <a @click.prevent="exportToExcel" class="btn btn-primary waves-effect btnAction" v-if="!readOnly" >{{getLabelText("Ex001")}}</a>
                        </OperationsPanel>

                        <SearchPanel id='statements-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>
                            <div :class="searchContainerDivClass" v-if="paymentGroups.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="paymentGroups.items" :selectedValue="this.search.selectedPaymentGroup" @selectchange="paymentGroupChangeHandler" />
                                </div>
                            </div>

                            <InputSearch :searchValue="search.clientId" fieldName="clientId" fieldDataType="Number" v-if="!isLoggedInAsReseller" :fieldLabel="getLabelText('GN0000715')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                            <InputSearch :searchValue="search.customerName" fieldName="customerName" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                            <InputSearch :searchValue="search.email" fieldName="email" :fieldLabel="getLabelText('GN0000652')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                        </SearchPanel>

                        <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                    <div class="col-xs-12" v-else>
                            <table class="table table-bordered table-striped table-hover" v-if="records.length > 0">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('CustomerId')">{{getLabelText('GN0000715')}}</a></th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('CustomerName')">{{ getLabelText('GN0000268') }}</a></th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('CustCompanyName')">{{ getLabelText('CompanyName') }}</a></th>
                                        <th class="col-xs-3">{{ getLabelText('GN0000693') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td><a v-bind:href="'/RCC/Billing/StatmentDetail.aspx?ClientId=' + record.CustomerId + '&PG=' + this.search.selectedPaymentGroup">{{ '#' + record.CustomerId }}</a></td>

                                        <td><a v-bind:href="'/RCC/Billing/StatmentDetail.aspx?ClientId=' + record.CustomerId + '&PG=' + this.search.selectedPaymentGroup">{{ '#' + record.CustomerName }}</a></td>

                                        <td>{{ record.CustCompanyName }}</td>

                                        <td v-if="record.Balance > 0 && this.balanceSignRule == getLabelText('GN00001063')">{{ getAmount(record.CurrencySymbol, record.Balance) }}</td>
                                        <td v-else-if="record.Balance < 0 && this.balanceSignRule == getLabelText('GN00001063')">{{ getAmount(record.CurrencySymbol, (record.Balance * -1)) }}</td>
                                        <td v-else-if="record.Balance > 0 && this.balanceSignRule == getLabelText('GN00001064')">{{ getAmount(record.CurrencySymbol, record.Balance) }}</td>
                                        <td v-else-if="record.Balance < 0 && this.balanceSignRule == getLabelText('GN00001064')">{{ getAmount(record.CurrencySymbol, record.Balance * -1) }}</td>
                                        <td v-else>{{ getAmount(record.CurrencySymbol, record.Balance) }}</td>
                                        
                                    </tr>

                                    <Pager :totalRecords="totalRecords" :pageSize="this.search.pageSize" :currentPage="this.search.pageIndex" @pagerChange="pagerChangeHandler" />
                                </tbody>
                            </table>
                            <NoRecords v-else />
                        </div>

                        <div class="col-xs-12" v-html="balanceSignRule">
                        </div>
                    </div>
                </div>
            </div>
        </div>
`
}
