using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Windows.Forms;
using System.Drawing;
using SPC.Kiosk.Base;
using SPC.Kiosk.Common;
using System.Windows.Threading;
using SPC.Kiosk.Popup.Model;
using SPC.Kiosk.Popup.ViewModel;
using SPC.Kiosk.DataHelper;
namespace SPC.Kiosk.Popup
{
    /// <summary>
    /// MobileHappyCoupon.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MobileHappyCoupon : Window
    {
        #region [  Members  ]
        private int ScreenNo { get; set; } = 0;
        private VmMobileHappyCoupon ViewModel { get; set; }
        private double GetPayments { get; set; }
        private List<M_BasketItem> GetBasketItems { get; set; }

        #endregion Members

        #region [ Ctor ]
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="_mobileCompany"></param>
        /// <param name="_totalPayment"></param>
        public MobileHappyCoupon(List<M_BasketItem> _getBasketItems, double _getPayments)
        {
            GetPayments = _getPayments;
            GetBasketItems = _getBasketItems;
            InitializeComponent();
            this.ContentRendered += MobileHappyCoupon_ContentRendered;
            this.Loaded += MobileHappyCoupon_Loaded;
            this.Left = Screen.AllScreens[ScreenNo].WorkingArea.Left;
            this.Top = Screen.AllScreens[ScreenNo].WorkingArea.Top;
            this.Width = Screen.AllScreens[ScreenNo].Bounds.Width;
            this.Height = Screen.AllScreens[ScreenNo].Bounds.Height;

        }

        #endregion Ctor

        #region [  Methods  ]
        private void OpenWindow()
        {
            var OpenAnimations = Animations.GetOpenAnimation(this.FrameBase
                                                           , OpenCloseAnimationType.FullSizeUp
                                                           , this.FrameBase.Height
                                                           , 0.5
                                                           , 0.2);
            if (OpenAnimations != null)
            {
                OpenAnimations.Completed += OpenAnimations_Completed;
                OpenAnimations.Begin();
            }
        }
        private void CloseWindow()
        {
            var CloseAnimation = Animations.GetCloseAnimation(this.FrameBase
                                                            , OpenCloseAnimationType.FullSizeDown
                                                            , this.FrameBase.Height
                                                            , 0.5
                                                            , 0.2);
            if (CloseAnimation != null)
            {
                CloseAnimation.Completed += CloseAnimation_Completed;
                CloseAnimation.Begin();
            }
        }
        private void ChangeWindow()
        {
            //this.Dispatcher.Invoke((Action)(() =>
            //{
            try
            {
                var _target = this.FrameData;
                var targetAnimation = new Storyboard();
                var centerX = _target.ActualWidth / 2;
                var centerY = _target.ActualHeight / 2;
                _target.RenderTransform = new ScaleTransform(1, 1, centerX, centerY);
                var flipXAni = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(0.2)));
                Storyboard.SetTarget(flipXAni, _target);
                Storyboard.SetTargetProperty(flipXAni, new PropertyPath("RenderTransform.ScaleX"));
                targetAnimation.Children.Add(flipXAni);
                targetAnimation.Completed += TargetAnimation_Completed;
                targetAnimation.Begin();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "ChangeWindow()", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            //}));
        }

        private void TargetAnimation_Completed(object sender, EventArgs e)
        {
            if (this.ViewModel.CouponWindow.Equals(MobileCouponWindowType.CouponStart))
            {
                this.BarCode.IsEnabled = true;
                this.BarCode.Focus();
            }
            else
            {
                this.BarCode.IsEnabled = false;
            }
        }

        #endregion Methods

        #region [ Event Handlers ]
        private void OpenAnimations_Completed(object sender, EventArgs e)
        {
            if (this.ViewModel.CouponWindow.Equals(MobileCouponWindowType.CouponStart))
            {
                this.BarCode.IsEnabled = true;
                this.BarCode.Focus();
            }
            else
            {
                this.BarCode.IsEnabled = false;
            }
        }
        private void CloseAnimation_Completed(object sender, EventArgs e)
        {
            this.ContentRendered -= MobileHappyCoupon_ContentRendered;
            this.Loaded += MobileHappyCoupon_Loaded;
            this.BarCode.PreviewKeyDown -= BarCode_PreviewKeyDown;
            this.BarCode.LostFocus -= BarCode_LostFocus;
            this.ViewModel.Dispose();
            this.Close();
        }

        private void MobileHappyCoupon_ContentRendered(object sender, EventArgs e)
        {
            this.FrameBase.Width = 1300;
            this.FrameBase.Height = 1010;
            OpenWindow();
        }

        private void MobileHappyCoupon_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.DataContext is VmMobileHappyCoupon viewModel)
            {
                this.ViewModel = viewModel;
                this.ViewModel.PropertyChanged += ViewModel_PropertyChanged;
                this.ViewModel.Payments += GetPayments;
                this.ViewModel.BasketData = GetBasketItems;
                this.ViewModel.IsTimeoutPopup = false;
            }
            this.LostFocus += MobileHappyCoupon_LostFocus;
            this.BarCode.PreviewKeyDown += BarCode_PreviewKeyDown;
            this.BarCode.LostFocus += BarCode_LostFocus;
            this.FrameBase.Width = 0;
            this.FrameBase.Height = 0;

        }
        private void MobileHappyCoupon_LostFocus(object sender, RoutedEventArgs e)
        {
            this.Focus();
        }
        private void BarCode_LostFocus(object sender, RoutedEventArgs e)
        {
            this.BarCode.Focus();
        }

        private void BarCode_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (sender is System.Windows.Controls.TextBox textBox
                && (e.Key.Equals(Key.Enter) || e.Key.Equals(Key.Return))
                && !string.IsNullOrEmpty(textBox.Text))
            {
                this.ViewModel.ReadBarCode = textBox.Text.Trim();
                textBox.Text = string.Empty;
            }
        }


        private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "CanWindowClose":
                    if (this.ViewModel.CanWindowClose)
                    {
                        CloseWindow();
                    }
                    break;
                case "CouponWindow":
                    ChangeWindow();
                    break;
            }
        }
        #endregion Event Handlers
        private void OpenErrorPopup(List<M_Language> _errorMessage)
        {
            this.ViewModel.TimerEnabled = false;
            try
            {
                var miniPopup = new M_MiniPopup
                {
                    Icon = MiniPopupIcon.AddCoupon,
                    DisplayLanguage = this.ViewModel.ShowLanguageType,
                    Message = _errorMessage,
                    OkButtonText = Languages.GetMessages("BTN0039"),
                    IsCencalButton = false,
                    TimeoutSeconds = 10,
                };
                var MiniPopupWin = new MiniPopup(miniPopup);
                MiniPopupWin.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "OpenErrorPopup()", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                this.ViewModel.TimerEnabled = true;
            }
        }
        private long GetUsingValue()
        {
            long result = 0L;
            try
            {
                M_PopupReturn getInput = null;
                var newPasswordPopup = new NumPadPopup(this.ViewModel.ShowLanguageType
                                                       , Languages.GetMessages("LBL0122")
                                                       ,false
                                                       ,false
                                                       ,6
                                                       ,0);
                newPasswordPopup.ShowDialog();
                if (newPasswordPopup.DataContext is VmNumPadPopup viewModel)
                {
                    getInput = viewModel.ReturnValue;
                }
                newPasswordPopup.DataContext = null;
                newPasswordPopup = null;
                if (getInput is M_PopupReturn)
                {
                    if (getInput.OKAnswer)
                    {
                        result = long.Parse("0"+(string)getInput.PopupArgs);
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetUsingValue()", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = 0L;
            }
            return result;

        }
        private void CoupnDatas_CouponSelect(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is M_MobileCouponDetail mobileCouponDetail)
            {
                //if (mobileCouponDetail.BrandCode.StartsWith())
                if (mobileCouponDetail.RequestPrice.Equals(0))
                {
                    var canUsingPrice = mobileCouponDetail.CanUsingPrice;
                    var maxUsingPrice = long.Parse((this.ViewModel.Payments - this.ViewModel.TotalCouponAmount).ToString());
                    var maxCanInputPrice = maxUsingPrice <= canUsingPrice
                                         ? maxUsingPrice
                                         : canUsingPrice;
                    if (maxUsingPrice > 0)
                    {
                        switch (mobileCouponDetail.Type)
                        {
                            case MobileCouponType.NormalValue:
                            case MobileCouponType.ValueLimit:
                                var inputValue = GetUsingValue();
                                if (inputValue > 0)
                                {
                                    if (inputValue > maxCanInputPrice)
                                    {
                                        OpenErrorPopup(Languages.GetMessages("LBL0033"));
                                    }
                                    else if (inputValue % 10 > 0)
                                    {
                                        OpenErrorPopup(Languages.GetMessages("LBL0020"));
                                    }
                                    else
                                    {
                                        mobileCouponDetail.RequestPrice = inputValue;
                                        mobileCouponDetail.DiscountPrice = inputValue;
                                    }
                                }
                                break;
                            case MobileCouponType.ValueFixed:
                                if (canUsingPrice > maxUsingPrice)
                                {
                                    OpenErrorPopup(Languages.GetMessages("LBL0033"));
                                }
                                else
                                {
                                    mobileCouponDetail.RequestPrice = canUsingPrice;
                                    mobileCouponDetail.DiscountPrice = canUsingPrice;
                                }
                                break;
                            default:
                                if (canUsingPrice > maxUsingPrice)
                                {
                                    OpenErrorPopup(Languages.GetMessages("LBL0033"));
                                }
                                else
                                {
                                    if (mobileCouponDetail.Option.Equals(MobileCouponOptionType.ItemFixed))
                                    {
                                        var exitItem = false;
                                        using (var newPosDataService = new PosDataService())
                                        {
                                            exitItem = newPosDataService.IsExistITEM_PLU_CD(mobileCouponDetail.ItemCodeKey);
                                        }
                                        if (exitItem)
                                        {
                                            mobileCouponDetail.RequestPrice = canUsingPrice;
                                            mobileCouponDetail.DiscountPrice = canUsingPrice;
                                        }
                                        else
                                        {
                                            OpenErrorPopup(Languages.GetMessages("LBL0064"));
                                        }
                                    }
                                    else
                                    {
                                        mobileCouponDetail.RequestPrice = canUsingPrice;
                                        mobileCouponDetail.DiscountPrice = canUsingPrice;
                                    }
                                }
                                break;
                        }
                    }
                }
                else
                {
                    mobileCouponDetail.RequestPrice = 0;
                    mobileCouponDetail.DiscountPrice = 0;
                }
            }
        }
    }

}
