using System;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.Xpo;
using Newtonsoft.Json;
using Nuvolar.Module.StaticClass;

namespace Nuvolar.Module.Controllers
{
    public partial class NAV_Online_VC : ViewController
    {
        public NAV_Online_VC()
        {
            InitializeComponent();
            // Target required Views (via the TargetXXX properties) and create their Actions.
        }
        protected override void OnActivated()
        {
            base.OnActivated();
            Frame.GetController<InvoiceVC>().FireNAVmanageInvoiceFinalWork += FireNAVmanageInvoiceFinalWork;
            Frame.GetController<OrderInVC>().FireNAVmanageInvoiceFinalWork += FireNAVmanageInvoiceFinalWork;
        }

        private void FireNAVmanageInvoiceFinalWork(InvoiceHeader _InvoiceHeader)
        {
            XPObjectSpace _ocur = View.ObjectSpace as XPObjectSpace;
            this.NAV_manageInvoice(_InvoiceHeader, _ocur);
        }

        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            // Access and customize the target View control.
        }
        protected override void OnDeactivated()
        {
            Frame.GetController<InvoiceVC>().FireNAVmanageInvoiceFinalWork -= FireNAVmanageInvoiceFinalWork;
            base.OnDeactivated();
        }
        /// <summary>
        /// Adószám ellenőrzése a kiválasztott ügyfelek alapján
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aNAV_queryTaxpayer_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            XPObjectSpace _ocur = View.ObjectSpace as XPObjectSpace;
            Customers _Customers = View.SelectedObjects[0] as Customers;
            CustomersFrom _CustomersFrom = _ocur.FindObject<CustomersFrom>(CriteriaOperator.Parse("IsDefault=True"));
            var _postData = new
            {
                customersfrom = _CustomersFrom.Oid.ToString(),
                taxPayer = _Customers.VATNumber.Substring(0, 8),
                softwareId = "123456789123456789",
                softwareName = "3C ERP System",
                softwareOperation = "ONLINE_SERVICE",
                softwareMainVersion = "17.2.3",
                softwareDevName = "3C Távközlési Kft.",
                softwareDevContact = "http:\\3ctelecom.hu",
                softwareDevCountryCode = "HU",
                softwareDevTaxNumber = "10644209-2-43"
            };

            RestAPI.ExecuteRootePOST("onlineinvoice/querytaxpayer", true, JsonConvert.SerializeObject(_postData));
            var _StatusCode = RestAPI.StatusCode;
            var _StatusDescription = RestAPI.StatusMessage;

            if (_StatusCode == 200)
            {


                dynamic _ResultJSON = JsonConvert.DeserializeObject(_StatusDescription);

                if (_ResultJSON.status.ToString() == "OK")
                {
                    if (_ResultJSON.taxpayerValidity["0"].ToString() == "false")
                    {
                        _ocur.Session.ExecuteNonQuery(string.Format("UPDATE Customers set NAV_valid = 0,NAV_queryDate=NOW() WHERE Oid = '{0}'",
                            _Customers.Oid.ToString()));
                    }
                    if (_ResultJSON.taxpayerValidity["0"].ToString() == "true")
                    {
                        _ocur.Session.ExecuteNonQuery(string.Format("UPDATE Customers set NAV_valid = 1,NAV_queryDate=NOW() WHERE Oid = '{0}'",
                            _Customers.Oid.ToString()));
                    }
                    Application.ShowViewStrategy.ShowMessage("Adószám ellenőrzés megtörtént !", InformationType.Success, 2000, InformationPosition.Bottom);
                }
                if (_ResultJSON.status.ToString() == "ERROR")
                {
                    string _ERROR = "Adószám ellenőrzés nem történt meg !";
                    _ERROR += " [" + _ResultJSON.xml.result.message.ToString() + "]";
                    Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);
                }
            }
            else
            {
                string _ERROR = "Adószám ellenőrzés nem történt meg !";
                _ERROR += " [" + _StatusDescription.ToString() + "]";
                Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);
            }
        }

        private void aNAV_manageInvoice_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            XPObjectSpace _ocur = View.ObjectSpace as XPObjectSpace;
            InvoiceHeader _InvoiceHeader = View.SelectedObjects[0] as InvoiceHeader;
            this.NAV_manageInvoice(_InvoiceHeader,_ocur);
            (View as ListView).CollectionSource.Reload();
        }
        private void NAV_manageInvoice(InvoiceHeader _InvoiceHeader,XPObjectSpace _ocur)
        {
            string _operation = "CREATE";

            if (_InvoiceHeader.IsStorno)
            {
                _operation = "STORNO";
            }
            var _postData = new
            {
                documentnumber = _InvoiceHeader.DocumentNumber,
                customersfrom = _InvoiceHeader.CustomersFrom.Oid.ToString(),
                operation = _operation,
                technicalAnnulment = false,
                softwareId = "123456789123456789",
                softwareName = "3C ERP System",
                softwareOperation = "ONLINE_SERVICE",
                softwareMainVersion = "17.2.3",
                softwareDevName = "3C Távközlési Kft.",
                softwareDevContact = "http:\\3ctelecom.hu",
                softwareDevCountryCode = "HU",
                softwareDevTaxNumber = "10644209-2-43"

            };

            RestAPI.ExecuteRootePOST("onlineinvoice/manageinvoice", true, JsonConvert.SerializeObject(_postData));
            var _StatusCode = RestAPI.StatusCode;
            var _StatusDescription = RestAPI.StatusMessage;

            if (_StatusCode == 200)
            {
                dynamic _ResultJSON = JsonConvert.DeserializeObject(_StatusDescription);

                if (_ResultJSON.status.ToString() == "OK")
                {
                    _ocur.Session.ExecuteNonQuery(string.Format("UPDATE InvoiceHeader set NAV_transactionID='{0}' WHERE Oid = '{1}'", _ResultJSON.transactionId["0"].ToString(), _InvoiceHeader.Oid.ToString()));

                    Application.ShowViewStrategy.ShowMessage("A számla beküldése megtörtént !", InformationType.Success, 2000, InformationPosition.Bottom);
                }
                if (_ResultJSON.status.ToString() == "ERROR")
                {
                    string _ERROR = "A számla beküldése nem történt meg !";
                    _ERROR += " [" + _ResultJSON.xml.result.message.ToString() + "]";
                    Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);
                }
            }
            else
            {
                string _ERROR = "A számla beküldése nem történt meg !";
                _ERROR += " [" + _StatusDescription + "]";
                Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);
            }


        }

        private void aNAV_queryInvoiceStatus_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            XPObjectSpace _ocur = View.ObjectSpace as XPObjectSpace;
            InvoiceHeader _InvoiceHeader = View.SelectedObjects[0] as InvoiceHeader;

            var _postData = new
            {
                documentnumber = _InvoiceHeader.DocumentNumber,
                customersfrom = _InvoiceHeader.CustomersFrom.Oid.ToString(),
                transactionId = _InvoiceHeader.NAV_transactionId,
                softwareId = "123456789123456789",
                softwareName = "3C ERP System",
                softwareOperation = "ONLINE_SERVICE",
                softwareMainVersion = "17.2.3",
                softwareDevName = "3C Távközlési Kft.",
                softwareDevContact = "http:\\3ctelecom.hu",
                softwareDevCountryCode = "HU",
                softwareDevTaxNumber = "10644209-2-43"

            };

            RestAPI.ExecuteRootePOST("onlineinvoice/queryinvoicestatus", true, JsonConvert.SerializeObject(_postData));
            var _StatusCode = RestAPI.StatusCode;
            var _StatusDescription = RestAPI.StatusMessage;

            if (_StatusCode == 200)
            {
                dynamic _ResultJSON = JsonConvert.DeserializeObject(_StatusDescription);

                if (_ResultJSON.status.ToString() == "OK")
                {
                    _ocur.Session.ExecuteNonQuery(string.Format("UPDATE InvoiceHeader set NAV_InvoiceStatus='{0}',NAV_queryDate=NOW() WHERE Oid = '{1}'",
                        _ResultJSON.processingResults.processingResult.invoiceStatus.ToString(), _InvoiceHeader.Oid.ToString()));
                    //_ResultJSON.processingResults.processingResult.technicalValidationMessages[0].message.ToString()

                    if (_ResultJSON.processingResults.processingResult.technicalValidationMessages != null)
                    {
                        Application.ShowViewStrategy.ShowMessage(_ResultJSON.processingResults.processingResult.technicalValidationMessages[0].message.ToString(),
                            InformationType.Error, 10000, InformationPosition.Bottom);
                    }
                    if (_ResultJSON.processingResults.processingResult.businessValidationMessages != null)
                    {
                        Application.ShowViewStrategy.ShowMessage(_ResultJSON.processingResults.processingResult.businessValidationMessages.message.ToString(),
                            InformationType.Error, 10000, InformationPosition.Bottom);
                    }
                    Application.ShowViewStrategy.ShowMessage("A számla státusz lekérdezése megtörtént !", InformationType.Success, 2000, InformationPosition.Bottom);
                }
                if (_ResultJSON.status.ToString() == "ERROR")
                {

                }
            }
            else
            {
                string _ERROR = "A számla státusz ellenőrzés nem történt meg !";
                _ERROR += " [" + _StatusDescription + "]";
                Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);
            }
        }

        private void aNAV_queryInvoiceData_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            InvoiceHeader _InvoiceHeader = View.SelectedObjects[0] as InvoiceHeader;

            var _postData = new
            {
                invoiceNumber = _InvoiceHeader.DocumentNumber,
                customersfrom = _InvoiceHeader.CustomersFrom.Oid.ToString(),
                softwareId = "123456789123456789",
                softwareName = "3C ERP System",
                softwareOperation = "ONLINE_SERVICE",
                softwareMainVersion = "17.2.3",
                softwareDevName = "3C Távközlési Kft.",
                softwareDevContact = "http:\\3ctelecom.hu",
                softwareDevCountryCode = "HU",
                softwareDevTaxNumber = "10644209-2-43"

            };

            RestAPI.ExecuteRootePOST("onlineinvoice/queryinvoicedata", true, JsonConvert.SerializeObject(_postData));
            var _StatusCode = RestAPI.StatusCode;
            var _StatusDescription = RestAPI.StatusMessage;
            if (_StatusCode == 200)
            {
                dynamic _ResultJSON = JsonConvert.DeserializeObject(_StatusDescription);

                if (_ResultJSON.status.ToString() == "OK")
                {
                    if (_ResultJSON.queryResults.availablePage.ToString() == "0")
                    {
                        string _ERROR = "A számla adat ellenőrzés megtörtént ! Nincs elérhető adat!";

                        Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Warning, 5000, InformationPosition.Bottom);
                    }
                    if (_ResultJSON.queryResults.availablePage.ToString() != "0")
                    {
                        string _ERROR = "A számla adat ellenőrzés megtörtént !";

                        Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Success, 5000, InformationPosition.Bottom);
                    }
                }
                if (_ResultJSON.status.ToString() == "ERROR")
                {
                    string _ERROR = "A számla adat ellenőrzés nem történt meg !";
                    _ERROR += " [" + _ResultJSON.technicalValidationMessages.message.ToString() + "]";
                    Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);
                }
            }
            else
            {
                string _ERROR = "A számla státusz ellenőrzés nem történt meg !";
                _ERROR += " [" + _StatusDescription + "]";
                Application.ShowViewStrategy.ShowMessage(_ERROR, InformationType.Error, 5000, InformationPosition.Bottom);

            }

        }
    }
}
