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 ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.9'
import NoRecords from '/Components/Common/NoRecords.js?v=3.9'
import { getLabelText, getAmount, getFileContentsFromInput } 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 },
        companyId: { type: Number, required: true },
        globalDateAfter: { type: String, required: true },
        globalDateBefore: { type: String, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        OperationsPanel,
        SearchPanel,
        VueSelect,
        InputSearch,
        DatePicker,
        NoRecords,
        Pager,
        ModalPopUp,
        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,
                paymentNumber: '',
                clientId: '',
                customerName: '',
                sepaEndToEndID: '',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'PaymentId',
                sortDir: 'Desc',
                updateSorting: false
            },
            showClearButton: false,

            //***** START: Modal Popup *******
            fileXML: null,
            showModal: false,
            modalTitle: '',
            parentContext: {},  //params to execute callback method related to current operation
            //***** END: Modal Popup *******
            
        }
    },
    methods: {
        getLabelText,
        getAmount,
        getFileContentsFromInput,
        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;

                });

        },
        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/GetSEPADirectDebits", 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;
        },
        downloadSEPAXML: function () {
            let selectedRecords = this.records.filter(a => a.IsItemSelected);

            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('plzSelectPayments'));
            }
            else {

                var vm = this;

                let postRequest = { ...fetchPost };
                let params = {
                    'SEPAInProcess': selectedRecords.map(item => ({
                        'PaymentId': item.PaymentId,
                        'InvoiceId': item.InvoiceID,
                        'CompanyId': item.CompanyId,
                        'CustomerId': item.CustomerId
                    }))
                };
                postRequest.body = JSON.stringify(params);

                fetch("/RCC/Billing/Payments.aspx/DownloadSEPAXML", postRequest)
                    .then(response => response.json()).then((data) => {
                        if (data && data.d && data.d != '')
                            window.open('/DownloadHandler.ashx', "_blank");
                        
                    })
                    .catch(function (e) {
                        displayErrorMsg(e);
                    });
            }
        },
        markAsPending: async function () {
            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 = {
                    'SEPAInProcess': selectedRecords.map(item => ({
                        'PaymentId': item.PaymentId,
                        'InvoiceId': item.InvoiceID,
                        'CompanyId': item.CompanyId,
                        'CustomerId': item.CustomerId
                    }))
                };
                postRequest.body = JSON.stringify(params);

                await fetch("/RCC/Billing/Payments.aspx/MarkAsPendingSEPA", 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.paymentNumber = '';
            this.search.clientId = '';
            this.search.customerName = '';
            this.search.sepaEndToEndID = '';

            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);
            });
        },
        onFileChange: function (event) {
            this.fileXML = event.target.files[0];
        },        
        paidBySEPAXML: async function () {
            try {

                const fileName = this.fileXML.name;
                const fileContent = await this.getFileContentsFromInput(this.fileXML);

                if (fileContent == '' || fileContent == null || !this.fileXML) {
                    alert(this.getLabelText("FAM0038"));
                    return;
                }
                else {
                    var vm = this;

                    let postRequest = { ...fetchPost };
                    let params = { 'fileName': fileName, 'fileContent': fileContent };
                    
                    postRequest.body = JSON.stringify(params);

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

                            vm.clearPopUpControls();
                            vm.doSearch();
                            displaySuccessMsg(data.d);
                        })
                        .catch(function (e) {
                            displayErrorMsg(e);
                        });
                }
            }
            catch (e) {
                displayErrorMsg(e);
            }
            
        },
        mpModelEventHandler: function (obj) {            
            this.clearPopUpControls();
            this.showModal = false;
        },
        clearPopUpControls: function () {
            this.fileXML = null;
            $('#markaspaidpopup').modal('hide');
            this.showModal = false;
        },
        showPaidBySEPAPopUp: function (e) {

            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

            if (disabledValue === 'true' || disabledValue === true)
                return false;

            this.showModal = true;
            $('#markaspaidpopup').modal('show');
            //this.parentContext = { selectedRecords: selectedRecords, op: "convert" };
            //this.modalTitle = this.getLabelText('StrConversionDate');
            
        },
    },
    created: async function () {

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

        var vm = this;

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

    <OperationsPanel v-if="!readOnly">
        <a @click.prevent="downloadSEPAXML" ID="LB_DownloadSEPAFile" class="btn btn-primary waves-effect">{{ getLabelText('DownloadSEPAFile') }}</a>
        <a @click.prevent="showPaidBySEPAPopUp" ID="Btn_PaidBySEPA" class="btn btn-primary waves-effect">{{ getLabelText('MarkAsPaid') }}</a>
        <a @click.prevent="markAsPending" ID="Btn_MarkAsPending" class="btn btn-primary waves-effect">{{ getLabelText('MarkAsPending') }}</a>
    </OperationsPanel>

    <SearchPanel id='sepapayments-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>

        <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.sepaEndToEndID" fieldName="sepaEndToEndID" :fieldLabel="getLabelText('SEPAEndToEndID')" :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>

    <ModalPopUp :id="'markaspaidpopup'" v-if="showModal" :parentContext="parentContext" :modalTitle="getLabelText('MarkAsPaid')">
        <div class="row">
            <div class="col-sm-4 col-xs-12 row-label">
                <label>{{ '* ' + getLabelText('SelectXMLDD') }}: </label>
            </div>
            <div class="col-sm-5 col-xs-12">
                <div class="form-group">
                    <div class="fileupload fileupload-new" data-provides="fileupload">
                        <span class="btn btn-primary btn-file"><span class="fileupload-new">{{ getLabelText('strSelectFile') }}</span>
                            <span class="fileupload-exists">{{ getLabelText('GN0000385') }}</span>
                            <input type="file" @change="onFileChange" />
                        </span>
                        <span class="fileupload-preview"></span>
                        <a href="#" class="close fileupload-exists" data-dismiss="fileupload" style="float: none">×</a>
                    </div>
                </div>
            </div>
            <div class="col-sm-3 col-xs-12">
                <a @click.prevent="paidBySEPAXML" v-bind:class="[{'disabled':(!fileXML)}, 'btn btn-primary waves-effect']">Upload</a>
            </div>
        </div>
    </ModalPopUp>

    <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-2">{{ getLabelText('GN000114') }}</th>
                    <th class="col-xs-2">{{ getLabelText('SEPAEndToEndID') }}</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>{{ record.SEPAInfo.split('|')[1] }}</td>
                                        
                </tr>

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