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

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        companyId: { type: Number, 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: {},
            paymentGroups: {},
            chargeStatuses: {},
            paymentMethods: {},
            payAs: {},
            paymentGateways: {},
            search: {
                selectedOwner: '',
                dateAfter: this.globalDateAfter,
                dateBefore: this.globalDateBefore,
                selectedPaymentGroup: '',
                selectedPaymentMethod: '',
                selectedChargeStatus: '',
                selectedPayAs: '',
                selectedPaymentGateway: '',
                paymentNumber: '',
                clientId: '',
                customerName: '',
                creditCard: '',
                transactionId: '',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'PaymentId',
                sortDir: 'Desc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    methods: {
        getLabelText,
        getAmount,
        checkAll: function (checked) {
            this.records.map(obj => obj.IsItemSelected = checked);
        },
        showActionButton: function () {
            return this.records.find(obj => obj.IsItemSelected);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        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;

                });

        },
        paymentMethodChangeHandler: function (obj) {

            this.search.selectedPaymentMethod = obj.selectedValue;

        },
        listPaymentMethods: async function () {

            var vm = this;

            await fetch("/RCC/Billing/Payments.aspx/GetPaymentMethods", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.paymentMethods = JSON.parse(data.d);
                    this.search.selectedPaymentMethod = this.paymentMethods.initialValue;

                });

        },
        paymentGroupChangeHandler: function (obj) {

            this.search.selectedPaymentGroup = obj.selectedValue;

        },
        listPaymentGroups: async function () {

            var vm = this;

            await fetch("/RCC/Billing/Payments.aspx/GetPaymentGroups", fetchGet)
                .then(response => response.json()).then((data) => {

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

                });

        },
        chargeStatusChangeHandler: function (obj) {
            this.search.selectedChargeStatus = obj.selectedValue;
        },
        listChargeStatuses: async function () {

            var vm = this;

            await fetch("/RCC/Billing/Payments.aspx/GetChargeStatuses", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.chargeStatuses = JSON.parse(data.d);
                    this.search.selectedChargeStatus = this.chargeStatuses.initialValue;

                });
        },
        payAsChangeHandler: function (obj) {
            this.search.selectedPayAs = obj.selectedValue;
        },
        listPayAs: async function () {

            var vm = this;

            await fetch("/RCC/Billing/Payments.aspx/GetPayAs", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.payAs = JSON.parse(data.d);
                    this.search.selectedPayAs = this.payAs.initialValue;

                });
        },
        paymentGatewayChangeHandler: function (obj) {
            this.search.selectedPaymentGateway = obj.selectedValue;
        },
        listPaymentGateways: async function () {

            var vm = this;

            await fetch("/RCC/Billing/Payments.aspx/GetPaymentGateways", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.paymentGateways = JSON.parse(data.d);
                    this.search.selectedPaymentGateway = this.paymentGateways.initialValue;

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

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

            await fetch("/RCC/Billing/Payments.aspx/GetAntiFraudPayments", 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].RowCounter;

                        vm.records.map(obj => ({ ...obj, IsItemSelected: false }));
                    }
                });
            vm.isLoading = false;
        },
        activateApprove: async function (action) {
            let selectedRecords = this.records.filter(a => a.IsItemSelected);
            var vm = this;

            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('plzSelectPayments'));
            }
            else {
                let postRequest = { ...fetchPost };
                let params = {
                    'PaymentIds': selectedRecords.map(item => item.PaymentId).join(),
                    'action': action
                };
                postRequest.body = JSON.stringify(params);

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

                        this.doSearch();
                        displaySuccessMsg(data.d);
                    }).catch(function (e) {
                        displayErrorMsg(e);
                    });
            }
        },
        processPayment: async function (pId, gop, compId) {
            var vm = this;

            if (gop == '0')
                return false;
            else if (gop == '2')
                window.location.href = '/RCC/Billing/PaymentDetail.aspx?Action=C&SRC=AF&PaymentId=' + pId + '|' + compId;
            else {

                let postRequest = { ...fetchPost };
                let params = {
                    'CompanyId': compId,
                    'PaymentId': pId,
                    'action': gop
                };
                postRequest.body = JSON.stringify(params);

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

                        this.doSearch();
                        displaySuccessMsg(data.d);
                    }).catch(function (e) {
                        displayErrorMsg(e);
                    });
            }
        },
        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.selectedPaymentMethod = this.paymentMethods.initialValue;
            this.search.selectedChargeStatus = this.chargeStatuses.initialValue;
            this.search.selectedPayAs = this.payAs.initialValue;
            this.search.selectedPaymentGateway = this.paymentGateways.initialValue;
            this.search.paymentNumber = '';
            this.search.clientId = '';
            this.search.customerName = '';
            this.search.creditCard = '';
            this.search.transactionId = '';

            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.listOwners().then(this.listPaymentGroups).then(this.listPaymentMethods).then(this.listChargeStatuses).
            then(this.listPayAs).then(this.listPaymentGateways).then(this.listRecords).catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
    },
    template: `

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

        <div :class="searchContainerDivClass" v-if="paymentMethods.show">
            <div class="form-group form-float">
                <VueSelect :options="paymentMethods.items" :selectedValue="this.search.selectedPaymentMethod" @selectchange="paymentMethodChangeHandler" />
            </div>
        </div>

        <div :class="searchContainerDivClass" v-if="chargeStatuses.show">
            <div class="form-group form-float">
                <VueSelect :options="chargeStatuses.items" :selectedValue="this.search.selectedChargeStatus" @selectchange="chargeStatusChangeHandler" />
            </div>
        </div>

        <div :class="searchContainerDivClass" v-if="payAs.show">
            <div class="form-group form-float">
                <VueSelect :options="payAs.items" :selectedValue="this.search.selectedPayAs" @selectchange="payAsChangeHandler" />
            </div>
        </div>

        <div :class="searchContainerDivClass" v-if="paymentGateways.show">
            <div class="form-group form-float">
                <VueSelect :options="paymentGateways.items" :selectedValue="this.search.selectedPaymentGateway" @selectchange="paymentGatewayChangeHandler" />
            </div>
        </div>

        <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.paymentNumber" fieldName="paymentNumber" :fieldLabel="getLabelText('GN0000696')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

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

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

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

        <InputSearch :searchValue="search.transactionId" fieldName="transactionId" :fieldLabel="getLabelText('GN000122')" :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='dateAfterAllPay' 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='dateBeforeAllPay' 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 align-center">
                        <input type="checkbox" id="CheckAll" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />
                    </th>
                    <th class="col-xs-1"><a href="#" @click.prevent="sortBy('PaymentId')">{{getLabelText('GN0000678')}}</a></th>
                    <th class="col-xs-1">{{ getLabelText('GN000124') }}</th>
                    <th class="col-xs-2"><a href="#" @click.prevent="sortBy('PaymentTimeStamp')">{{ getLabelText('GN0000721') }}</a></th>
                    <th class="col-xs-2"><a href="#" @click.prevent="sortBy('CustomerId')">{{ getLabelText('GN0000850') }}</a></th>
                    <th class="col-xs-1" v-if="owners.show"><a href="#" @click.prevent="sortBy('Owner')">{{getLabelText('SPT002811')}}</a></th>
                    <th class="col-xs-1">{{ getLabelText('GN000114') }}</th>
                    <th class="col-xs-1">{{ getLabelText('GN0000813') }}</th>
                    <th class="col-xs-2" v-if="!readOnly">{{ getLabelText('GN0000360') }}</th>
                </tr>
                <tr v-for="record in records">

                    <td class="align-center">
                        <input type="checkbox" v-bind:id="'cb' + record.PaymentId" v-model="record.IsItemSelected" />
                    </td>

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

                    <td>{{ getLabelText(record.PaymentMethod) }}</td>

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

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

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

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

                    <td v-if="!readOnly">
                        <div class="form-group form-float">
                            <select v-model="record.GO" class="vue-select">
                                <option value="0">{{getLabelText("GN0000643")}}</option>
                                <option value="1">{{getLabelText("GN0000810")}}</option>
                                <option value="2">{{getLabelText("GN0000811")}}</option>
                            </select>
                        </div>
                        
                        <a @click.prevent="processPayment(record.PaymentId, record.GO, record.CompanyId)" ID="LB_Go" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000647') }}</a>
                    </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-if="!readOnly && records.length > 0">
        <a @click.prevent="activateApprove(1)" class="btn btn-primary waves-effect btnAction" ID="Btn_Approve_V6">{{ getLabelText('GN0000810') }}</a>
    </div>
`
}
