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 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 },
        globalDateAfter: { type: String, required: true },
        globalDateBefore: { type: String, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        SearchPanel,
        VueSelect,
        InputSearch,
        DatePicker,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            statuses: {},
            search: {
                selectedOwner: '',
                dateAfter: this.globalDateAfter,
                dateBefore: this.globalDateBefore,
                docNum: '',
                clientId: '',
                customerName: '',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'DocId',
                sortDir: 'Desc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    methods: {
        getLabelText,
        getAmount,
        handleGlobalSearch: function () {
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            var searchQueryType = '';
            var searchQueryValue = '';

            for (var i = 0; i < hashes.length; i++) {
                var hash = hashes[i].split('=');
                if (hash[0].toLowerCase() == 'op') {
                    searchQueryType = decodeURI(hash[1]);
                }
                else if (hash[0].toLowerCase() == 'val') {
                    searchQueryValue = decodeURI(hash[1]);
                }
            }

            if (searchQueryType != '' && searchQueryValue != '') {
                if (searchQueryType == 'B3')
                    this.search.docNum = searchQueryValue;
                else if (searchQueryType == 'B5')
                    this.search.clientId = searchQueryValue;
                else if (searchQueryType == 'B6')
                    this.search.customerName = searchQueryValue;

                this.showClearButton = true;
            }
        },
        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();
        },
        dateAfterSelectHandler: function (d) {
            this.search.dateAfter = d.selectedDateStr;

            this.$emit('onAfterDateChange', { dateAfter: this.search.dateAfter });
        },
        dateBeforeSelectHandler: function (d) {
            this.search.dateBefore = d.selectedDateStr;

            this.$emit('onBeforeDateChange', { dateBefore: this.search.dateBefore });
        },
        ownerChangeHandler: function (obj) {

            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);

        },
        listOwners: async function () {

            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/GetOwners", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.owners = JSON.parse(data.d);
                    this.search.selectedOwner = this.owners.initialValue;

                })
            //.catch(function (e) {
            //    displayErrorMsg(e);
            //});

        },
        listRecords: async function () {

            var vm = this;
            vm.isLoading = true;
            this.records = [];
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);
            
            await fetch("/RCC/Billing/Documents.aspx/GetCreds", 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;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.selectedOwner = this.owners.initialValue;
            this.search.docNum = '';
            this.search.clientId = '';
            this.search.customerName = '';

            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;

        this.handleGlobalSearch();
        await this.listOwners().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            displayErrorMsg(e);
        });
    },
    template: `

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

                        <SearchPanel id='credits-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>
                            <div :class="searchContainerDivClass" v-if="owners.show">
                                <div class="form-group form-float">
                                    <VueSelect :id="'ownersCred'" :options="owners.items" :selectedValue="this.search.selectedOwner" @selectchange="ownerChangeHandler" />
                                </div>
                            </div>

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

                            <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" />

                            <div class="row">
                                <div class="col-xs-12">
                                    <div :class="searchContainerDivClass">
                                        <div class="row">
                                            <div class="col-sm-6 col-xs-12 row-label">
                                                <label>{{ getLabelText('GN0000687') + ': ' }}</label>
                                            </div>
                                            <DatePicker id='dateAfterCred' wrapperClass="col-sm-6 col-xs-12" :default-val="search.dateAfter" @onDateSelected='dateAfterSelectHandler' :is-required='true'></DatePicker>
                                        </div>
                                    </div>

                                    <div :class="searchContainerDivClass">
                                        <div class="row">
                                            <div class="col-sm-6 col-xs-12 row-label">
                                                <label>{{ getLabelText('GN0000688') + ': ' }}</label>
                                            </div>
                                            <DatePicker id='dateBeforeCred' wrapperClass="col-sm-6 col-xs-12" :default-val="search.dateBefore" @onDateSelected='dateBeforeSelectHandler' :is-required='true'></DatePicker>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </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-1">{{getLabelText('String385')}}</th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('DocId')">{{ getLabelText('GN0000677') }}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('DocType')">{{ getLabelText('GN0000680') }}</a></th>
                                        <th class="col-xs-2"><a href="#" @click.prevent="sortBy('DocDate')">{{ getLabelText('GN0000691') }}</a></th>
                                        <th class="col-xs-2"><a href="#" @click.prevent="sortBy('CustomerId')">{{ getLabelText('GN0000850') }}</a></th>
                                        <th class="col-xs-2" v-if="owners.show"><a href="#" @click.prevent="sortBy('Owner')">{{ getLabelText('SPT002811') }}</a></th>
                                        <th class="col-xs-2">{{getLabelText('GN000114')}}</th>
                                        <th class="col-xs-2">{{getLabelText('GN0000693')}}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td>{{ getLabelText('GN0000264') }}</td>

                                        <td><a v-bind:href="'/RCC/Billing/VCreditAdj.aspx?PaymentId=' + record.PaymentId + '|' + record.CompanyId">{{ record.PaymentId }}</a></td>

                                        <td>{{ getLabelText('GN0000264') }}</td>

                                        <td><DatePicker :id="record.DocId.toString()" wrapperClass="col-xs-12 m-b-0" :defaultVal='record.DocDate' :is-Disabled='true' :displayAsLabel='true'></DatePicker></td>

                                        <td><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID=' + record.CustomerId + '&DT=3'">{{ '#' + record.CustomerId + '- ' + record.Name }}</a></td>

                                        <td v-if="owners.show"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?RD=1&CID=' + record.OwnerId" v-bind:class="{'disabled':(record.OwnerId <= 0)}">{{ record.Owner }}</a></td>

                                        <td>{{ getAmount(record.CurrencySymbol, record.CurrentTotal) }}</td>

                                        <td>{{ 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>
                </div>
            </div>
        </div>
`
}
