import { getLabelText } from '/components/common/utils.js?v=3.4'
import VueSelect from "/Components/Common/VueSelect.js?v=3.4"
import InputSearch from "/Components/Common/InputSearch.js?v=3.4"
import Pager from "/Components/Common/Pager.js?v=3.4"
import SearchPanel from "/Components/Common/SearchPanelWrapper.js?v=3.4"
import OperationsPanel from "/Components/Common/OperationsPanelWrapper.js?v=3.4"
import ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.4'
import NoRecords from "/Components/Common/NoRecords.js?v=3.4"
import Loading from "/Components/Common/Loading.js?v=3.4"

export default {
    props: {
        //tabIndex: { type: String, required: true },
        readOnly: { type: Boolean, required: true },
        isSubReseller: { type: Boolean, required: true }
    },
    components: {
        VueSelect,
        InputSearch,
        Pager,
        SearchPanel,
        OperationsPanel,
        ModalPopUp,
        NoRecords,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            search: {
                selectedOwner: '',
                customerName: '',
                clientId: '',
                contactName: '',
                customerNo: '',
                email: '',
                phone: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'ContactName',
                sortDir: 'Asc',
                updateSorting: false,
                showDeleted: false,
                status: 'GN0000261'
            },
            showClearButton: false,


        }
    },
    methods: {
        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();
        },
        showActionButton: function () {
            return this.customers.find(obj => obj.IsItemSelected);
        },
        ownerChangeHandler: async function (obj) {

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

        },
        listContacts: async function () {

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

            await fetch("/RCC/Clients/ClientsList.aspx/GetContactList", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);

                    if (vm.records.length > 0)
                        vm.totalRecords = vm.records[0].TotalRecords;
                });
            vm.isLoading = false;
        },
        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);
            //});

        },
        doClearSearch: async function () {
        
            this.search.clientId = '';
            this.search.customerNo = '';
            this.search.customerName = '';
            this.search.contactName = '';
            this.search.email = '';
            this.search.phone = '';
            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();

        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            vm.isLoading = true;
            this.listContacts().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        getLabelText,
        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 = hash[1];
                }
                else if (hash[0].toLowerCase() == 'val') {
                    searchQueryValue = decodeURI(hash[1]);
                }
            }

            if (searchQueryType != '' && searchQueryValue != '') {
                if (searchQueryType == 'C1')
                    this.search.name = searchQueryValue;
                else if (searchQueryType == 'C2')
                    this.search.email = searchQueryValue;
                else if (searchQueryType == 'C3')
                    this.search.domainName = searchQueryValue;
                else if (searchQueryType == 'C4')
                    this.search.companyName = searchQueryValue;
                else if (searchQueryType == 'C5')
                    this.search.clientId = searchQueryValue;
                else if (searchQueryType == 'C6')
                    this.search.address = searchQueryValue;
                //else if (searchQueryType == 'C7')
                //    this.search.phone = searchQueryValue;
                else if (searchQueryType == 'C8')
                    this.search.phone = searchQueryValue;
                else if (searchQueryType == 'C9')
                    this.search.card4Digit = searchQueryValue;
                else if (searchQueryType == 'C10')
                    this.search.notes = searchQueryValue;
                else if (searchQueryType == 'C11')
                    this.search.city = searchQueryValue;
                else if (searchQueryType == 'C12')
                    this.search.zipPostalCode = searchQueryValue;
                else if (searchQueryType == 'C13')
                    this.search.customerNo = searchQueryValue;
            }
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        }
    },
    created: async function () {

        var vm = this;

        await this.listOwners().then(this.listContacts).catch(function (e) {
            vm.listContacts = [];
            vm.totalRecords = 0;
            displayErrorMsg(e);

            // alert(e);
        });

    },
    template: ` 
        <div class="col-xs-12">
            <div class="card">
                <div class="body">
                    <div class="row">                                                            

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

                            <InputSearch :searchValue="search.customerName" fieldName="customerName" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                           
                            <InputSearch fieldDataType="number" :searchValue="search.clientId" fieldName="clientId" :fieldLabel="getLabelText('GN0000678')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                                  
                            <InputSearch :searchValue="search.contactName" fieldName="contactName" :fieldLabel="getLabelText('String1002')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                                                                                                                            
                            <InputSearch :searchValue="search.email" fieldName="email" :fieldLabel="getLabelText('GN0000652')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                                                                                      
                            <InputSearch :searchValue="search.phone" fieldName="phone" :fieldLabel="getLabelText('GN00012')" :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-4"><a href="#" @click.prevent="sortBy('ContactName')">{{getLabelText("Contact")}}</a></th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('CustomerName')">{{getLabelText("customer")}}</a></th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('CustomerCompanyName')">{{getLabelText("Exh505")}}</a></th>
                                        <th class="col-xs-2"><a href="#" @click.prevent="sortBy('PhoneNumber')">{{getLabelText("String1003")}}</a></th>
                                         
                                    </tr>
                                    <tr v-for="record in records">

                                        <td>{{record.FirstName}} {{record.LastName}} [{{record.PrimaryEmail}}]</td>                                     
                                        <td><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID='+record.CustomerID+'&Src=C'">{{record.CustomerName}} </a> </td>
                                        <td>{{record.CustomerCompanyName}} </td>
                                        <td>{{record.PhoneCountryCode}} - {{record.Phone}} </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>
`
}

