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 },
        paymentGroupId: { type: Number, required: true },
        customerId: { type: Number, required: true },
        isLoggedInAsReseller: { type: Boolean, 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,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            summary: {},
            search: {
                pgId: this.paymentGroupId,
                dateAfter: this.globalDateAfter,
                dateBefore: this.globalDateBefore,
                clientId: this.customerId,

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'SDate',
                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();
        },
        dateAfterSelectHandler: function (d) {
            this.search.dateAfter = d.selectedDateStr;
        },
        dateBeforeSelectHandler: function (d) {
            this.search.dateBefore = d.selectedDateStr;
        },
        listSummary: async function () {
            var vm = this;

            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

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

                    vm.summary = data.d; // JSON.parse(data.d);
                });
        },
        listRecords: async function () {

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

            await fetch("/RCC/Billing/StatmentDetail.aspx/GetStatementDetail", 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.length;
                });
            vm.isLoading = false;
        },
        exportToExcel: function () {
            var vm = this;

            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

            fetch("/RCC/Billing/StatmentDetail.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) {
                    displayErrorMsg(e);
                });

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listSummary().then(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.listSummary().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="body">
                    <div class="row">

                        <OperationsPanel>
                            <a @click.prevent="exportToExcel" class="btn btn-primary waves-effect btnAction" v-if="!readOnly" >{{getLabelText("Ex001")}}</a>
                        </OperationsPanel>
                                
                        <div class="col-xs-12" v-if="Object.keys(summary).length > 0">
                            <div class="card">
                                <div class="header">
                                    <h3>{{getLabelText("GN0000835")}}</h3>
                                </div>
                                <div class="body">
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{getLabelText("GN0000836")}}</div>
                                        <div class="col-sm-4 col-xs-12" data-toggle="tooltip" data-placement="top" title="" :data-original-title="'Name: ' + summary.FirstName + ' ' + summary.LastName + '<br />Address: ' + summary.Address1 + ' ' + summary.Address2 + '<br />Email: ' + summary.PrimaryEmail + '<br />Status: ' + summary.Status" data-html="true"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID=' + summary.CustomerId">{{ '#' + summary.CustomerId + ' ' + summary.FirstName + ' ' + summary.LastName }}</a></div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{getLabelText("GN0000837")}}</div>
                                        <div class="col-sm-4 col-xs-12">{{ getAmount(summary.CurrencySymbol, summary.TotalCharges) }}</div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{getLabelText("GN0000838")}}</div>
                                        <div class="col-sm-4 col-xs-12">{{ getAmount(summary.CurrencySymbol, summary.TotalPayments) }}</div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{getLabelText("GN0000693")}}</div>
                                        <div class="col-sm-4 col-xs-12" v-html="summary.TdBalanceInnerText"></div>
                                    </div>
                                    <div class="row hide">
                                        <div class="col-sm-2 col-xs-12 row-label">{{getLabelText("GN000148")}}</div>
                                        <div class="col-sm-4 col-xs-12" id="Td_Comments"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <SearchPanel id='statementdetails-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>
                            <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='dateAfterInv' 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='dateBeforeInv' 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-html="summary.DivPrevBalanceInnerText">
                        </div>

                         <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-2">{{getLabelText('GN0000677')}}</th>
                                        <th class="col-xs-4">{{ getLabelText('GN0000680') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('GN000114') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('GN0000693') }}</th>
                                        <th class="col-xs-2">{{getLabelText('GN0000721')}}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td v-if="record.Type == 'GN0000262'"><a v-bind:href="'/RCC/Billing/InvoiceDetail.aspx?InvoiceId=' + record.SID + '|' + record.CompanyId">{{ record.SID }}</a></td>
                                        <td v-else><a v-bind:href="'/RCC/Billing/PaymentDetail.aspx?PaymentId=' + record.SID + '|' + record.CompanyId">{{ record.SID }}</a></td>

                                        <td v-if="record.Type == 'GN0000262'">{{ getLabelText(record.TypeName) + (record.ItemCancelled ? ' (C)': '') + (record.Status == 4 ? ' (D)': '') }}</td>
                                        <td v-else>{{ getLabelText(record.TypeName) + (record.HasRefunds ? ' (R)': '') + (record.HasCredits ? ' (Cr)': '') + (record.Status == 5 ? ' (C)': '') + (record.Status == 7 ? ' (F)': '') + (record.Status == 4 ? ' (OH)': '') }}</td>

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

                                        <td v-if="record.PrevBal > 0 && summary.BalanceSign">{{ getAmount(summary.CurrencySymbol, record.PrevBal) }}</td>
                                        <td v-else-if="record.PrevBal < 0 && summary.BalanceSign">{{ getAmount(summary.CurrencySymbol, (record.PrevBal * -1)) }}</td>
                                        <td v-else-if="record.PrevBal > 0 && !summary.BalanceSign">{{ getAmount(summary.CurrencySymbol, record.PrevBal) }}</td>
                                        <td v-else-if="record.PrevBal < 0 && !summary.BalanceSign">{{ getAmount(summary.CurrencySymbol, (record.PrevBal * -1)) }}</td>
                                        <td v-else>{{ getAmount(summary.CurrencySymbol, record.PrevBal) }}</td>

                                        <td><DatePicker :id="record.SID.toString()" wrapperClass="col-xs-12 m-b-0" :defaultVal='record.SDate' :is-Disabled='true' :displayAsLabel='true'></DatePicker></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">
                            {{ getLabelText('GN00001397') + ': (R) = ' + getLabelText('GN0000346') + ', (C) = ' + getLabelText('GN0000347') + ', (Cr) = ' + getLabelText('M0011') + ', (F) = ' + getLabelText('GN0000349') + ', (OH) = ' + getLabelText('GN0000345') }}
                        </div>

                    </div>
                </div>
            </div>
        </div>
`
}
