using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using System.Reflection;
using SPC.Kiosk.Base;
using SPC.Kiosk.Common;
using SPC.Kiosk.Popup.Model;
using SPC.Kiosk.Payments;
using SPC.Kiosk.DataHelper;
using System.Windows.Controls;
using System.Windows.Media;

namespace SPC.Kiosk.Popup.ViewModel
{
    /// <summary>
    /// HappyPointCertify.xaml에 대한 ViewModel
    /// </summary>
    public class VmHappyPointCertify : PopupViewModelBase 
    {


        #region [ Members ]
        private PosDataService posDataService = null;
        private ObservableCollection<M_ItemData> memberHistoryItems= new ObservableCollection<M_ItemData>();
        /// <summary>
        /// Member History Items
        /// </summary>
        public ObservableCollection<M_ItemData> MemberHistoryItems
        {
            get { return memberHistoryItems; }
            set { memberHistoryItems = value; PropertyChange("MemberHistoryItems"); }
        }
        private ObservableCollection<M_BasketItem> memberOrderBasket;
        /// <summary>
        /// Member Order Basket
        /// </summary>
        public ObservableCollection<M_BasketItem> MemberOrderBasket
        {
            get { return memberOrderBasket; }
            set { memberOrderBasket = value; PropertyChange("MemberOrderBasket"); }
        }

        private double memberHistoryItemsGridHeight = 310d;
        /// <summary>
        /// Member History Items Grid Height
        /// </summary>
        public double MemberHistoryItemsGridHeight
        {
            get { return memberHistoryItemsGridHeight; }
            set { memberHistoryItemsGridHeight = value; PropertyChange("MemberHistoryItemsGridHeight"); }
        }
        private double topGridMarginHeight = 0d;
        /// <summary>
        /// Top Grid Margin Height
        /// </summary>
        public double TopGridMarginHeight
        {
            get { return topGridMarginHeight; }
            set { topGridMarginHeight = value; PropertyChange("TopGridMarginHeight"); }
        }

        private string titileImage;
        /// <summary>
        /// Titile Image
        /// </summary>
        public string TitileImage
        {
            get { return titileImage; }
            set { titileImage = value; PropertyChange("TitileImage"); }
        }
        private string imageQR;
        /// <summary>
        /// Image QR
        /// </summary>
        public string ImageQR
        {
            get { return imageQR; }
            set { imageQR = value; PropertyChange("ImageQR"); }
        }

        private string imageUserType= ResourceManager.GetNximagePathAdd("happy_member_pink.gif", CommonValue.PBdesignImagesPath);
        /// <summary>
        /// 
        /// </summary>
        public string ImageUserType
        {
            get { return imageUserType; }
            set { imageUserType = value; PropertyChange("ImageUserType"); }
        }


        private List<M_Language> headerText;
        /// <summary>
        /// Top Header Text
        /// </summary>
        public List<M_Language> HeaderText
        {
            get { return headerText; }
            set { headerText = value; PropertyChange("HeaderText"); }
        }
        private List<M_Language> scanGuidText;
        /// <summary>
        /// Second Sub Header Text
        /// </summary>
        public List<M_Language> ScanGuidText
        {
            get { return scanGuidText; }
            set { scanGuidText = value; PropertyChange("ScanGuidText"); }
        }
        private List<M_Language> processingGuide;
        /// <summary>
        /// Processing Guide Text
        /// </summary>
        public List<M_Language> ProcessingGuide
        {
            get { return processingGuide; }
            set { processingGuide = value; PropertyChange("ProcessingGuide"); }
        }
        private List<M_Language> errorGuide;
        /// <summary>
        /// Error Guide Text
        /// </summary>
        public List<M_Language> ErrorGuide
        {
            get { return errorGuide; }
            set { errorGuide = value; PropertyChange("ErrorGuide"); }
        }
        private List<M_Language> infoGuid1Text;
        /// <summary>
        /// Bootom first infomation text
        /// </summary>
        public List<M_Language> InfoGuid1Text
        {
            get { return infoGuid1Text; }
            set { infoGuid1Text = value; PropertyChange("InfoGuid1Text"); }
        }
        private List<M_Language> infoGuid2Text;
        /// <summary>
        /// Bottom second infomation text
        /// </summary>
        public List<M_Language> InfoGuid2Text
        {
            get { return infoGuid2Text; }
            set { infoGuid2Text = value; PropertyChange("InfoGuid2Text"); }
        }
        private string processingGIF;
        /// <summary>
        /// Processing GIF
        /// </summary>
        public string ProcessingGIF
        {
            get { return processingGIF; }
            set { processingGIF = value; PropertyChange("ProcessingGIF"); }
        }
        private string errorImage;
        /// <summary>
        /// Read Barcode
        /// </summary>
        public string ErrorImage
        {
            get { return errorImage; }
            set { errorImage = value; PropertyChange("ErrorImage"); }
        }
        public bool certifyStartVisible = false;
        /// <summary>
        /// 인증 시작 화면 Visible
        /// </summary>
        public bool CertifyStartVisible
        {
            get { return certifyStartVisible; }
            set { certifyStartVisible = value; PropertyChange("CertifyStartVisible"); }
        }
        public bool certifyProcessingVisible = false;
        /// <summary>
        /// 인증 진행 화면 Visible
        /// </summary>
        public bool CertifyProcessingVisible
        {
            get { return certifyProcessingVisible; }
            set { certifyProcessingVisible = value; PropertyChange("CertifyProcessingVisible"); }
        }
        public bool processingErrorVisible = false;
        /// <summary>
        /// 인증 오류 화면 Visible
        /// </summary>
        public bool ProcessingErrorVisible
        {
            get { return processingErrorVisible; }
            set { processingErrorVisible = value; PropertyChange("ProcessingErrorVisible"); }
        }
        public bool certifySuccessVisible = false;
        /// <summary>
        /// 인증 완료 화면 Visible
        /// </summary>
        public bool CertifySuccessVisible
        {
            get { return certifySuccessVisible; }
            set { certifySuccessVisible = value; PropertyChange("CertifySuccessVisible"); }
        }
        private List<M_Language> processingMessageText;
        /// <summary>
        /// Number Pad Input Guide Text
        /// </summary>
        public List<M_Language> ProcessingMessageText
        {
            get { return processingMessageText; }
            set { processingMessageText = value; PropertyChange("ProcessingMessageText"); }
        }

        private List<M_Language> numPadGuidText;
        /// <summary>
        /// Number Pad Input Guide Text
        /// </summary>
        public List<M_Language> NumPadGuidText
        {
            get { return numPadGuidText; }
            set { numPadGuidText = value; PropertyChange("NumPadGuidText"); }
        }
        private List<M_Language> errorText;
        /// <summary>
        /// Process Error Text
        /// </summary>
        public List<M_Language> ErrorText
        {
            get { return errorText; }
            set { errorText = value; PropertyChange("ErrorText"); }
        }
        private bool isErrorBlink = false;
        /// <summary>
        /// Is Error Text Blink
        /// </summary>
        public bool IsErrorBlink
        {
            get { return isErrorBlink; }
            set { isErrorBlink = value; PropertyChange("IsErrorBlink"); }
        }
        private string formatedBarCode;
        /// <summary>
        /// Read Barcode Formated Text
        /// </summary>
        public string FormatedBarCode
        {
            get { return formatedBarCode; }
            set { formatedBarCode = value; PropertyChange("FormatedBarCode"); }
        }
        private string readBarCode;
        /// <summary>
        /// Read Barcode
        /// </summary>
        public string ReadBarCode
        {
            get { return readBarCode; }
            set { readBarCode = value; PropertyChange("ReadBarCode"); }
        }
        private bool showPhoneInput = false;
        /// <summary>
        /// Show Phone Input
        /// </summary>
        public bool ShowPhoneInput
        {
            get { return showPhoneInput; }
            set { showPhoneInput = value; PropertyChange("ShowPhoneInput"); }
        }
        private List<M_Language> showPhoneButtonText;
        /// <summary>
        /// Number Pad Input Guide Text
        /// </summary>
        public List<M_Language> ShowPhoneButtonText
        {
            get { return showPhoneButtonText; }
            set { showPhoneButtonText = value; PropertyChange("ShowPhoneButtonText"); }
        }

        private string inputNumbers = string.Empty;
        /// <summary>
        /// Number Pad Input Number
        /// </summary>
        public string InputNumbers
        {
            get { return inputNumbers; }
            set { inputNumbers = value; PropertyChange("InputNumbers"); }
        }

        private string memberNameText = string.Empty;
        /// <summary>
        /// Number Pad Input Number
        /// </summary>
        public string MemberNameText
        {
            get { return memberNameText; }
            set { memberNameText = value; PropertyChange("MemberNameText"); }
        }
        private string memberPointsText = string.Empty;
        /// <summary>
        /// Number Pad Input Number
        /// </summary>
        public string MemberPointsText
        {
            get { return memberPointsText; }
            set { memberPointsText = value; PropertyChange("MemberPointsText"); }
        }

        private double cancelButtonWidth = 650d;
        /// <summary>
        /// Cancel Button Width
        /// </summary>
        public double CancelButtonWidth
        {
            get { return cancelButtonWidth; }
            set { cancelButtonWidth = value; PropertyChange("CancelButtonWidth"); }
        }
        private List<M_Language> cancelButtonText;
        /// <summary>
        /// Cancel Button Text
        /// </summary>
        public List<M_Language> CancelButtonText
        {
            get { return cancelButtonText; }
            set { cancelButtonText = value; PropertyChange("CancelButtonText"); }
        }
        private List<M_Language> okButtonText;
        /// <summary>
        /// Ok Button Text
        /// </summary>
        public List<M_Language> OkButtonText
        {
            get { return okButtonText; }
            set { okButtonText = value; PropertyChange("OkButtonText"); }
        }
        public bool oKButtonEnabled = false;
        /// <summary>
        /// OK Button enabled
        /// </summary>
        public bool OKButtonEnabled
        {
            get { return oKButtonEnabled; }
            set { oKButtonEnabled = value; PropertyChange("OKButtonEnabled"); }
        }
        private double okButtonWidth = 650d;
        /// <summary>
        /// OK Button Width
        /// </summary>
        public double OKButtonWidth
        {
            get { return okButtonWidth; }
            set { okButtonWidth = value; PropertyChange("OKButtonWidth"); }
        }
        public bool numPadInputVisible = false;
        /// <summary>
        /// OK Button enabled
        /// </summary>
        public bool NumPadInputVisible
        {
            get { return numPadInputVisible; }
            set { numPadInputVisible = value; PropertyChange("NumPadInputVisible"); }
        }
        public bool numPadGuideVisible = true;
        /// <summary>
        /// OK Button enabled
        /// </summary>
        public bool NumPadGuideVisible
        {
            get { return numPadGuideVisible; }
            set { numPadGuideVisible = value; PropertyChange("NumPadGuideVisible"); }
        }

        public int numPadMaxLength;
        /// <summary>
        /// Number Pad Input Maxlength
        /// </summary>
        public int NumPadMaxLength
        {
            get { return numPadMaxLength; }
            set { numPadMaxLength = value; PropertyChange("NumPadMaxLength"); }
        }

        private List<M_Language> memberPointsHeaderText;
        /// <summary>
        /// Cancel Button Text
        /// </summary>
        public List<M_Language> MemberPointsHeaderText
        {
            get { return memberPointsHeaderText; }
            set { memberPointsHeaderText = value; PropertyChange("MemberPointsHeaderText"); }
        }
        private string languageButttonImage;
        /// <summary>
        /// Read Barcode Formated Text
        /// </summary>
        public string LanguageButttonImage
        {
            get { return languageButttonImage; }
            set { languageButttonImage = value; PropertyChange("LanguageButttonImage"); }
        }
        private bool languageButttonVisibel;
        /// <summary>
        /// Language Select Button Visible
        /// </summary>
        public bool LanguageButttonVisibel
        {
            get { return languageButttonVisibel; }
            set { languageButttonVisibel = value; PropertyChange("LanguageButttonVisibel"); }
        }
        private CertifyWindowType certifyWindow = CertifyWindowType.CertifyStart;
        /// <summary>
        /// Current  View Window
        /// </summary>
        public CertifyWindowType CertifyWindow
        {
            get { return certifyWindow; }
            set { certifyWindow = value; PropertyChange("CertifyWindow"); }
        }
        private double popupWidth = 1300;
        /// <summary>
        /// Popup Whidth (For Calculate OK Button Width)
        /// </summary>
        public double PopupWidth
        {
            get { return popupWidth; }
            set { popupWidth = value; PropertyChange("PopupWidth"); }
        }

        private List<M_Language> bellButtonText;
        /// <summary>
        /// Barcode Scan Login Button Text
        /// </summary>
        public List<M_Language> BellButtonText
        {
            get { return bellButtonText; }
            set { bellButtonText = value; PropertyChange("BellButtonText"); }
        }
        private List<M_Language> talkButtonText;
        /// <summary>
        /// Mobile Login Button Text
        /// </summary>
        public List<M_Language> TalkButtonText
        {
            get { return talkButtonText; }
            set { talkButtonText = value; PropertyChange("TalkButtonText"); }
        }

        /// <summary>
        /// HappyPoint 인증 정보
        /// </summary>
        public M_HappyPointReturn HappyPointReturn { get; set; }

        /// <summary>
        /// OK Click Command
        /// </summary>
        public ICommand OkCommand { get; protected set; }         

        /// <summary>
        /// Cancel Click Command
        /// </summary>
        public ICommand CancelCommand { get; protected set; }
        public ICommand SwitchPhoneCommand { get; protected set; }

        /// <summary>
        /// Bell Button Command
        /// </summary>
        public ICommand BellButtonCommand { get; protected set; }
        /// <summary>
        /// Talk Button Command
        /// </summary>
        public ICommand TalkButtonCommand { get; protected set; }


        public bool openOptionPopup = true;
        /// <summary>
        /// OK Button enabled
        /// </summary>
        public bool OpenOptionPopup
        {
            get { return openOptionPopup; }
            set { openOptionPopup = value; PropertyChange("openOptionPopup"); }
        }
        /// <summary>
        /// Selected Data
        /// </summary>
        public M_ItemData SelectedData { get; protected set; }
        /// <summary>
        /// Get Option Popup Return
        /// </summary>
        public M_PopupReturn GetOptionPopupReturn { get; set; }
        private bool MemberProcessStart = false;
        private posHappyPoint posHappyPoint = null;
        private Task ProcessTask = null;
        private string certifyKey = string.Empty;


        private ParentPage _popupParentPage;
        /// <summary>
        /// Popup Parent Page
        /// </summary>
        public ParentPage PopupParentPage
        {
            get { return _popupParentPage; }
            set { _popupParentPage = value; PropertyChange("PopupParentPage"); }
        }
        private string cashReceipButtonBackground;
        /// <summary>
        /// CashReceip Button Background
        /// </summary>
        public string CashReceipButtonBackground
        {
            get { return cashReceipButtonBackground; }
            set { cashReceipButtonBackground = value; PropertyChange("CashReceipButtonBackground"); }
        }
        private string cashTypePersonButtonNormal;
        /// <summary>
        /// CashType Person Button Normal
        /// </summary>
        public string CashTypePersonButtonNormal
        {
            get { return cashTypePersonButtonNormal; }
            set { cashTypePersonButtonNormal = value; PropertyChange("CashTypePersonButtonNormal"); }
        }
        private string cashTypePersonButtonDisable;
        /// <summary>
        /// CashType Person Button Disable
        /// </summary>
        public string CashTypePersonButtonDisable
        {
            get { return cashTypePersonButtonDisable; }
            set { cashTypePersonButtonDisable = value; PropertyChange("CashTypePersonButtonDisable"); }
        }
        private bool cashTypePersonEnable = false;
        /// <summary>
        /// CashType Serson Enabled
        /// </summary>
        public bool CashTypePersonEnable
        {
            get { return cashTypePersonEnable; }
            set { cashTypePersonEnable = value; PropertyChange("CashTypePersonEnable"); }
        }
        private string cashTypeCompanyButtonNormal;
        /// <summary>
        /// CashType Company Button Normal
        /// </summary>
        public string CashTypeCompanyButtonNormal
        {
            get { return cashTypeCompanyButtonNormal; }
            set { cashTypeCompanyButtonNormal = value; PropertyChange("CashTypeCompanyButtonNormal"); }
        }
        private string cashTypeCompanyButtonDisable;
        /// <summary>
        /// CashType Company Button Disable
        /// </summary>
        public string CashTypeCompanyButtonDisable
        {
            get { return cashTypeCompanyButtonDisable; }
            set { cashTypeCompanyButtonDisable = value; PropertyChange("CashTypeCompanyButtonDisable"); }
        }
        public bool cashTypeCompanyEnable = true;
        /// <summary>
        /// CashType Serson Enabled
        /// </summary>
        public bool CashTypeCompanyEnable
        {
            get { return cashTypeCompanyEnable; }
            set { cashTypeCompanyEnable = value; PropertyChange("CashTypeCompanyEnable"); }
        }

        private bool bellButtonEnable = false;
        /// <summary>
        /// Bell Button Enable
        /// </summary>
        public bool BellButtonEnable
        {
            get { return bellButtonEnable; }
            set { bellButtonEnable = value; PropertyChange("BellButtonEnable"); }
        }
        private bool talkButtonEnable = true;
        /// <summary>
        /// Talk Button Enable
        /// </summary>
        public bool TalkButtonEnable
        {
            get { return talkButtonEnable; }
            set { talkButtonEnable = value; PropertyChange("TalkButtonEnable"); }
        }
        #endregion

        #region [ Ctor ]
        /// <summary>
        /// Ctor
        /// </summary>
        public VmHappyPointCertify()
        {
            posDataService = new PosDataService();
            OkCommand = new Command(OkCommandHandler);
            CancelCommand = new Command(CancelCommandHandler);
            SwitchPhoneCommand = new Command(SwitchPhoneCommandHandler);
            this.PropertyChanged += VmHappyPointCertify_PropertyChanged;
            TitileImage = ResourceManager.GetNximagePathAdd("img_gif_barcode_happy.gif", CommonValue.PBdesignImagesPath);
            ProcessingGIF = ResourceManager.GetNximagePathAdd("ic_alert_ing2.gif", CommonValue.PBdesignImagesPath);
            ImageQR = ResourceManager.GetNximagePathAdd("Img_qr.png", CommonValue.PBdesignImagesPath);
            ErrorImage = ResourceManager.GetNximagePathAdd("ic_alert_error.png", CommonValue.PBdesignImagesPath);
            HeaderText = Languages.GetMessages("LBL0134");
            MemberPointsHeaderText = Languages.GetMessages("LBL0054");
            ProcessingMessageText = Languages.GetMessages("LBL0087");
            ProcessingGuide = Languages.GetMessages("LBL0017");
            ErrorGuide = Languages.GetMessages("LBL0017");
            ErrorText = new List<M_Language>();
            NumPadMaxLength = 11;
            NumPadGuidText = Languages.GetMessages("LBL0091");
            ShowPhoneButtonText = new List<M_Language>
            {
                new M_Language { Type=SupportLanguageType.ko,LanguageData="전화번호로 로그인 >>" }
            };
            ShowLanguageType = CommonValue.CommonLanguageType;
            posHappyPoint = new posHappyPoint();
            CertifyWindow = CertifyWindowType.CertifyStart;
            ShowPhoneInput = false;
            
            BellButtonCommand = new Command(BellButtonCommandHandler);
            TalkButtonCommand = new Command(TalkButtonCommandHandler);


            CashReceipButtonBackground = ResourceManager.GetNximagePathAdd("img_check_bg.png", CommonValue.PBdesignImagesPath);
            CashTypePersonButtonNormal = ResourceManager.GetNximagePathAdd("btn_check_n.png", CommonValue.PBdesignImagesPath);
            CashTypePersonButtonDisable = ResourceManager.GetNximagePathAdd("btn_check_s.png", CommonValue.PBdesignImagesPath);
            CashTypeCompanyButtonNormal = ResourceManager.GetNximagePathAdd("btn_check_n.png", CommonValue.PBdesignImagesPath);
            CashTypeCompanyButtonDisable = ResourceManager.GetNximagePathAdd("btn_check_s.png", CommonValue.PBdesignImagesPath);
        }
        /// <summary>
        /// Dispose
        /// </summary>
        public new void Dispose()
        {
            this.TitileImage = null;
            this.ProcessingGIF = string.Empty;
            this.ErrorImage = string.Empty;
            this.PropertyChanged -= VmHappyPointCertify_PropertyChanged;
            if (posDataService != null)
            {
                posDataService.Dispose();
                posDataService = null;
            }
            if (ProcessTask != null)
            {
                ProcessTask.Dispose();
                ProcessTask = null;
            }
            if (posHappyPoint != null)
            {
                HappyPointRemoveEvents();
                posHappyPoint.Dispose();
                posHappyPoint = null;
            }
            base.Dispose();
        }
        #endregion Ctor

        #region [ Method ]
        private void AddItem2Basket(M_ItemData _itemData)
        {
            var option = new List<M_ItemOptionGroup>();
            var itemCount = 1;
            var unitPrice = _itemData.Price;
            if (_itemData.IsOption)
            {
                SelectedData = _itemData;
                GetOptionPopupReturn = null;
                OpenOptionPopup = true;
                try
                {
                    if (GetOptionPopupReturn is M_PopupReturn popupReturn)
                    {
                        if (popupReturn.TimeOut)
                        {
                            IsTimeout = true;
                            option = null;
                        }
                        else
                        {
                            if (popupReturn.PopupArgs is M_OptionReturn getOption)
                            {
                                option = getOption.Options;
                                itemCount = getOption.ItemCount;
                                unitPrice = getOption.PriceWithOption;
                            }
                            else
                            {
                                option = null;
                            }
                        }
                    }
                    else
                    {
                        option = null;
                    }
                }
                catch
                {
                    option = null;
                }
                finally
                {
                    OpenOptionPopup = false;
                }
                if (option == null) return;
            }
            else
            {
                option = null;
                itemCount = 1;
                unitPrice = _itemData.Price;
            }
            var getNewOrderBasket = posDataService.AddItemToBasket(MemberOrderBasket
                                                            , itemCount
                                                            , unitPrice
                                                            , CommonValue.PBdesignImagesPath
                                                            , _itemData
                                                            , option);
            if (getNewOrderBasket is ObservableCollection<M_BasketItem>) MemberOrderBasket = getNewOrderBasket;

        }

        private void InitError()
        {
            LastAccessTime = DateTime.Now;
            ErrorText = new List<M_Language>();
            IsErrorBlink = false;
        }
        private void HappyPointCreateEvents()
        {
            if (posHappyPoint != null)
            {
                posHappyPoint.ReadStart += PosHappyPoint_ReadStart;
                posHappyPoint.ReadEnd += PosHappyPoint_ReadEnd;
                posHappyPoint.ErrorEvent += PosHappyPoint_ErrorEvent;
                posHappyPoint.ErrorMessageEvent += PosHappyPoint_ErrorMessageEvent;
            }
        }
        private void HappyPointRemoveEvents()
        {
            if (posHappyPoint != null)
            {
                posHappyPoint.ReadStart -= PosHappyPoint_ReadStart;
                posHappyPoint.ReadEnd -= PosHappyPoint_ReadEnd;
                posHappyPoint.ErrorEvent -= PosHappyPoint_ErrorEvent;
                posHappyPoint.ErrorMessageEvent -= PosHappyPoint_ErrorMessageEvent;
            }
        }
        private void DoHappyPointCertify()
        {
            
            if (posHappyPoint != null)
            {
                HappyPointCreateEvents();
                var processTask = new Task(() => posHappyPoint.StartCertifyProcessing(certifyKey));
                processTask.Start();
                processTask.Wait();
                HappyPointRemoveEvents();
                if (posHappyPoint.ProcessOK)
                {
                    CertifyWindow = CertifyWindowType.CertifySuccess;
                }
                else
                {
                    CertifyWindow = CertifyWindowType.ProcessingError;
                }
                TimerEnabled = true;
                MemberProcessStart = false;
                processTask = null;
            }

        }
        private void DoBarCodeHappyPointCertify()
        {
            InputNumbers = string.Empty;
            FormatedBarCode = ReadBarCode.GetEncriptCardNo();
            certifyKey = ReadBarCode;
            CertifyWindow = CertifyWindowType.CertifyProcessing;
        }

        private void SetImageUserType()
        {
            if (HappyPointReturn is M_HappyPointReturn)
            {
                if (HappyPointReturn.IsCompanyMember)
                {
                    ImageUserType = ResourceManager.GetNximagePathAdd("happy_member_spc.png", CommonValue.PBdesignImagesPath);
                }
                else
                {
                    switch (HappyPointReturn.MemberLevel)
                    {
                        case HappyPointMemberLevel.VIP:
                            ImageUserType = ResourceManager.GetNximagePathAdd("happy_member_platinum.png", CommonValue.PBdesignImagesPath);
                            break;
                        case HappyPointMemberLevel.Gold:
                            ImageUserType = ResourceManager.GetNximagePathAdd("happy_member_gold.png", CommonValue.PBdesignImagesPath);
                            break;
                        default: //PINK && None => Pink
                            ImageUserType = ResourceManager.GetNximagePathAdd("happy_member_pink.png", CommonValue.PBdesignImagesPath);
                            break;
                    }
                }
            }
        }

        private void SetOrderHistory(string _custCD)
        {
            if (!string.IsNullOrEmpty(_custCD))
            {
                using (var dataHelper = new CommonDataHelper())
                {
                    string[] orderHistoryArray = dataHelper.GetCustBuyHistory(_custCD);
                    if (orderHistoryArray is string[] && orderHistoryArray.Length > 0)
                    {
                        List<string> orderHistoryList = null;
                        if (orderHistoryArray is string[] && orderHistoryArray.Length > 0)
                        {
                            orderHistoryList = new List<string>();
                            var historyKeys = string.Format("'{0}'", string.Join("','", orderHistoryArray));
                            var historyItems = dataHelper.GetItemsData(historyKeys);
                            //var historyItems = dataHelper.GetItemsData().GetRange(0,5);
                            if (historyItems is List<M_ItemData>)
                            {
                                foreach (var aItem in historyItems)
                                {

                                    aItem.BadgeHeight = 30;
                                    aItem.BadgeOrientation = Orientation.Horizontal;
                                    if (aItem.BadgeImages is List<string> && aItem.BadgeImages.Count > 0)
                                    {
                                        var newBadgeImages = new List<string>();
                                        foreach (var aBadgeImage in aItem.BadgeImages)
                                        {
                                            var strBadgeImage = ResourceManager.GetNximagePathAdd(aBadgeImage, CommonValue.PBdesignImagesPath);
                                            if (!string.IsNullOrEmpty(strBadgeImage))
                                            {
                                                newBadgeImages.Add(strBadgeImage);
                                            }
                                        }
                                        aItem.BadgeImages = newBadgeImages;
                                    }
                                    if (aItem.Option is List<M_ItemOptionGroup> && aItem.Option.Count > 0)
                                    {
                                        foreach (var aOptionGRP in aItem.Option)
                                        {
                                            if (aOptionGRP is M_ItemOptionGroup)
                                            {
                                                aOptionGRP.ImageFile = aOptionGRP.Index.Equals(0)
                                                                    ? "ic_option_takein.png"
                                                                    : aOptionGRP.Index.Equals(1)
                                                                    ? "ic_option_shot.png"
                                                                    : "ic_option_candle.png";
                                            }
                                        }
                                    }
                                    var itemImage = ResourceManager.GetItemImage(aItem.ImageFile, CommonValue.ItemDefaultImage);//파일 없을 경우 DefaultImage로
                                    aItem.DataParameter = new M_AnimationButton
                                    {
                                        NormalBrush = itemImage,
                                        DragCursorImage = itemImage,
                                        DisableBrush = ResourceManager.GetNximagePathAdd("img_contents_soldout.png", CommonValue.PBdesignImagesPath),
                                        Width = 60,
                                        Height = 60,
                                        Margin = new Thickness(80, 10, 95, 25),
                                        BrushStretch = Stretch.Fill,
                                        DragCursorHotSpot = HotSpotType.Center,
                                        ClickAnimationType = ButtonAnimationType.None,
                                        CircleBackBrush = "Transparent",
                                        CircleTextBruch = "Transparent",
                                        Enabled = !aItem.IsSoldOut,
                                        CircleText = string.Empty,
                                    };
                                    aItem.BaseTextBlock = new M_TextBlock()
                                    {
                                        LanguageData = dataHelper.GetLaguageData("PROD", aItem.ItemCode),
                                        TextSize = 20,
                                        Width = 210,
                                        Height = 50,
                                        TextBrush = "Black",
                                        TextFontFamily = "NanumSquare",
                                        TextVerticalAlignment = VerticalAlignment.Center,
                                        TextMargin = new Thickness(5, 0, 20, 0),
                                        TextWeight = FontWeights.Bold,
                                        TextWrapping = TextWrapping.Wrap
                                    };
                                    aItem.AdditionTextBlock = new M_TextBlock()
                                    {
                                        LanguageData = new List<M_Language>
                                        {
                                            new M_Language{ Type = SupportLanguageType.ko, LanguageData = string.Format("￦{0:#,##0}", aItem.Price)},
                                        },
                                        TextSize = 26,
                                        Width = 210,
                                        Height = 30,
                                        TextBrush = "#1469cc",
                                        TextFontFamily = "NanumSquare",
                                        TextVerticalAlignment = VerticalAlignment.Top,
                                        TextMargin = new Thickness(5, 5, 20, 0),
                                        TextWeight = FontWeights.Bold,
                                    };
                                    orderHistoryList.Add(aItem.ItemCode);
                                }
                            }
                            MemberHistoryItems = new ObservableCollection<M_ItemData>(historyItems);
                            HappyPointReturn.OrderHistoryItems = orderHistoryList;
                        }
                    }
                }
            }
        }
        private void SetCertifyView()
        {
            if (ShowPhoneInput)
            {
                InputNumbers = string.Empty;
                CancelButtonWidth = PopupWidth / 2;
                OKButtonWidth = PopupWidth / 2;
                OKButtonEnabled = false;
                //OkButtonText = Languages.GetMessages("BTN0011");
                //CancelButtonText = Languages.GetMessages("BTN0016");
                //ShowPhoneButtonText = new List<M_Language>
                //            {
                //                new M_Language { Type=SupportLanguageType.ko,LanguageData="바코드 스캔 로그인 >>" }
                //            };
                TalkButtonEnable = false;
                BellButtonEnable = true;
            }
            else
            {
                CancelButtonWidth = PopupWidth;
                OKButtonWidth = 0d;
                OKButtonEnabled = false;
                //CancelButtonText = Languages.GetMessages("BTN0016");
                ShowPhoneButtonText = new List<M_Language>
                            {
                                new M_Language { Type=SupportLanguageType.ko,LanguageData="전화번호로 로그인 >>" }
                            };
                TalkButtonEnable = true;
                BellButtonEnable = false;

            }
        }
        #endregion Method

        #region [ Event Handlers ]

        private void CancelCommandHandler(object obj)
        {
            TimerEnabled = false;
            ReturnValue = new M_PopupReturn
            {
                OKAnswer = false,
                TimeOut = false,
                ReturnLanguage = ShowLanguageType,
                PopupArgs = null
            };
            CanWindowClose = true;
        }

        private void OkCommandHandler(object obj)
        {
            switch (CertifyWindow)
            {
                case CertifyWindowType.CertifyStart:
                    certifyKey = InputNumbers;
                    CertifyWindow = CertifyWindowType.CertifyProcessing;
                    break;
                case CertifyWindowType.ProcessingError:
                    CertifyWindow = CertifyWindowType.CertifyStart;
                    break;
                case CertifyWindowType.CertifySuccess:
                    ReturnValue = new M_PopupReturn
                    {
                        OKAnswer = true,
                        TimeOut = false,
                        ReturnLanguage = ShowLanguageType,
                        PopupArgs = HappyPointReturn,
                        PopupSubArgs = MemberOrderBasket is ObservableCollection<M_BasketItem>
                                     ? MemberOrderBasket.ToList()
                                     : null
                    };
                    if (ProcessTask != null) ProcessTask.Wait();
                    CanWindowClose = true;
                    break;
            }
           
        }
        private void SwitchPhoneCommandHandler(object obj)
        {
            ShowPhoneInput = !ShowPhoneInput;
        }

        private void PosHappyPoint_ErrorMessageEvent(string ErrorString)
        {
            ErrorText = new List<M_Language>
            {
                new M_Language
                {
                    Type = SupportLanguageType.ko,
                    LanguageData = ErrorString.Replace("\n"," ").Replace("\r","")
                },
            };
            IsErrorBlink = true;
            
        }

        private void PosHappyPoint_ErrorEvent(posHappyPoint.ErrorCode _errorCode)
        {
            //TODO: 공통에 에러 메세지 등록 핋요
            //ErrorText = Languages.GetMessages(_errorCode.ToString());

            ErrorText = new List<M_Language>
            {
                new M_Language
                {
                    Type = SupportLanguageType.ko,
                    LanguageData = _errorCode.ToString()
                },
            };
            IsErrorBlink = true;
        }

        private void PosHappyPoint_ReadStart(object sender)
        {
            MemberProcessStart = true;
            TimerEnabled = false;
        }
        private void PosHappyPoint_ReadEnd(object sender)
        {
            if (sender is posHappyPoint getPosposHappyPoint)
            {
                if (getPosposHappyPoint.ProcessOK)
                {
                    HappyPointReturn = new M_HappyPointReturn
                    {
                        MyHappyCoupons = getPosposHappyPoint.MyHappyCoupons,
                        IsFavoriteStore = getPosposHappyPoint.IsFavoriteStore,
                        IsCompanyMember = getPosposHappyPoint.IsCompanyMember,
                        MemberName = getPosposHappyPoint.MemberName,
                        MemberNumber = getPosposHappyPoint.MemberNumber,
                        MemberCode = getPosposHappyPoint.CertifyKey,
                        IsAppMamber = getPosposHappyPoint.IsAppMamber,
                        MemberLevel = getPosposHappyPoint.MemberLevel.StartsWith("VIP")
                                    ? HappyPointMemberLevel.VIP
                                    : getPosposHappyPoint.MemberLevel.StartsWith("G")
                                    ? HappyPointMemberLevel.Gold
                                    : HappyPointMemberLevel.Pink,
                        MemberPoint = getPosposHappyPoint.MemberPoint,
                        UseablePoint = getPosposHappyPoint.UseablePoint,
                        NeedPassword = getPosposHappyPoint.NeedPassword,
                        ReservePoint = getPosposHappyPoint.CanReservePoint,
                        IsCardNoUsed = getPosposHappyPoint.CertifyKey.Replace("=", "").Replace("@", "").Length.Equals(16)
                    };

                    // 포인트 멤버이름 : 핸드폰번호 시 [고객]
                    MemberNameText = HappyPointReturn.IsCardNoUsed ? HappyPointReturn.MemberName : "고객";
                    MemberPointsHeaderText = HappyPointReturn.IsCardNoUsed ? Languages.GetMessages("LBL0054") : new List<M_Language>();

                    SetImageUserType();
                    //주문이력 조회 기능 
                    //SetOrderHistory("1011175065"); //Test
                    if (HappyPointReturn.IsCardNoUsed) SetOrderHistory(HappyPointReturn.MemberNumber);  //Prod
                    // 핸드폰 로그인 시 안보여도 포인트는 가지고 있어야 한다.
                    MemberPointsText = HappyPointReturn.IsCardNoUsed ? string.Format("{0}P", HappyPointReturn.MemberPoint.ToString("#,##0")) : string.Empty;
                }
            }
        }

        private void VmHappyPointCertify_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                switch (e.PropertyName)
                {
                    case "IsTimeout":
                        if (IsTimeout)
                        {
                            switch (CertifyWindow)
                            {
                                case CertifyWindowType.CertifyStart:
                                case CertifyWindowType.CertifySuccess:
                                case CertifyWindowType.ProcessingError:
                                    ReturnValue = new M_PopupReturn
                                    {
                                        OKAnswer = false,
                                        TimeOut = true,
                                        ReturnLanguage = ShowLanguageType,
                                        PopupArgs = null
                                    };
                                    break;
                            }
                            if (ProcessTask != null) ProcessTask.Wait();
                            CanWindowClose = true;
                        }
                        break;
                    case "ShowLanguageType":
                        switch (ShowLanguageType)
                        {
                            case SupportLanguageType.ko:
                                LanguageButttonImage = ResourceManager.GetNximagePathAdd("btn_language_kor.png", CommonValue.PBdesignImagesPath);
                                break;
                            case SupportLanguageType.en:
                                LanguageButttonImage = ResourceManager.GetNximagePathAdd("btn_language_eng.png", CommonValue.PBdesignImagesPath);
                                break;
                            case SupportLanguageType.ja:
                                LanguageButttonImage = ResourceManager.GetNximagePathAdd("btn_language_jap.png", CommonValue.PBdesignImagesPath);
                                break;
                            case SupportLanguageType.zh:
                                LanguageButttonImage = ResourceManager.GetNximagePathAdd("btn_language_chi.png", CommonValue.PBdesignImagesPath);
                                break;
                        }
                        break;
                    case "ShowPhoneInput":
                        SetCertifyView();                        
                        break;
                    case "NumPadInputVisible":
                        NumPadGuideVisible = !NumPadInputVisible;
                        break;
                    case "InputNumbers":
                        NumPadInputVisible = InputNumbers.Length > 0;
                        if (NumPadInputVisible)
                        {
                            InitError();
                            ReadBarCode = string.Empty;
                        }
                        OKButtonEnabled = InputNumbers.Length.Equals(10) || InputNumbers.Length.Equals(11);
                        break;
                    case "ReadBarCode":
                        if (!MemberProcessStart)
                        {
                            InitError();
                            switch (ReadBarCode.Length)
                            {
                                case 17:
                                    readBarCode = ReadBarCode.Substring(0, 16);
                                    DoBarCodeHappyPointCertify();
                                    break;
                                case 16:
                                    DoBarCodeHappyPointCertify();
                                    break;
                                default:
                                    FormatedBarCode = string.Empty;
                                    OKButtonEnabled = false;
                                    break;
                            }
                        }
                        break;
                    case "CertifyWindow":
                        CertifyStartVisible = false;
                        CertifyProcessingVisible = false;
                        ProcessingErrorVisible = false;
                        CertifySuccessVisible = false;
                        switch (CertifyWindow)
                        {
                            case CertifyWindowType.CertifyStart:
                                CertifyStartVisible = true;
                                break;
                            case CertifyWindowType.CertifyProcessing:
                                CertifyProcessingVisible = true;
                                break;
                            case CertifyWindowType.ProcessingError:
                                ProcessingErrorVisible = true;
                                break;
                            case CertifyWindowType.CertifySuccess:
                                CertifySuccessVisible = true;
                                break;
                        }
                        break;
                    case "CertifyStartVisible":
                    case "PopupParentPage":
                        if (CertifyStartVisible)
                        {
                            if (PopupParentPage == ParentPage.PBPaymentsWindow)
                            {
                                HeaderText = Languages.GetMessages("LBL0135");
                                ScanGuidText = Languages.GetMessages("LBL0136");
                                OkButtonText = Languages.GetMessages("BTN0039");
                                CancelButtonText = Languages.GetMessages("BTN0033");
                                BellButtonText = new List<M_Language>() { new M_Language() { LanguageData = "바코드스캔", Type = SupportLanguageType.ko } };
                                TalkButtonText = new List<M_Language>() { new M_Language() { LanguageData = "휴대폰", Type = SupportLanguageType.ko } };
                            }
                            else
                            {
                                HeaderText = Languages.GetMessages("LBL0134");
                                ScanGuidText = Languages.GetMessages("LBL0137");
                                OkButtonText = Languages.GetMessages("BTN0011");
                                CancelButtonText = Languages.GetMessages("BTN0016");
                                BellButtonText = new List<M_Language>() { new M_Language() { LanguageData = "바코드스캔 로그인", Type = SupportLanguageType.ko } };
                                TalkButtonText = new List<M_Language>() { new M_Language() { LanguageData = "휴대폰 로그인", Type = SupportLanguageType.ko } };
                            }

                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            SetCertifyView();
                            TimeOutSeconds = CommonValue.TimeOutSeconds;
                        }
                        break;
                    case "CertifyProcessingVisible":
                        if (CertifyProcessingVisible)
                        {
                            ScanGuidText = new List<M_Language>();
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            CancelButtonWidth = 0d;
                            OKButtonWidth = 0d;
                            LanguageButttonVisibel = false;
                            if (ProcessTask != null) ProcessTask.Wait();
                            ProcessTask = new Task(DoHappyPointCertify);
                            ProcessTask.Start();
                        }
                        break;
                    case "ProcessingErrorVisible":
                        if (ProcessingErrorVisible)
                        {
                            if (PopupParentPage == ParentPage.PBPaymentsWindow)
                            {
                                HeaderText = Languages.GetMessages("LBL0135");
                                ScanGuidText = Languages.GetMessages("LBL0136");
                                OkButtonText = Languages.GetMessages("BTN0007");
                                CancelButtonText = Languages.GetMessages("BTN0033");
                                BellButtonText = new List<M_Language>() { new M_Language() { LanguageData = "바코드스캔", Type = SupportLanguageType.ko } };
                                TalkButtonText = new List<M_Language>() { new M_Language() { LanguageData = "휴대폰", Type = SupportLanguageType.ko } };
                            }
                            else
                            {
                                HeaderText = Languages.GetMessages("LBL0134");
                                ScanGuidText = Languages.GetMessages("LBL0137");
                                OkButtonText = Languages.GetMessages("BTN0007");
                                CancelButtonText = Languages.GetMessages("BTN0033");
                                BellButtonText = new List<M_Language>() { new M_Language() { LanguageData = "바코드스캔 로그인", Type = SupportLanguageType.ko } };
                                TalkButtonText = new List<M_Language>() { new M_Language() { LanguageData = "휴대폰 로그인", Type = SupportLanguageType.ko } };
                            }

                            ScanGuidText = new List<M_Language>();
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            CancelButtonWidth = PopupWidth / 2;
                            OKButtonWidth = PopupWidth / 2;
                            OKButtonEnabled = true;
                            TimeOutSeconds = 10d;
                            LanguageButttonVisibel = false;
                        }
                        break;
                    case "CertifySuccessVisible":
                        if (CertifySuccessVisible)
                        {
                            if (PopupParentPage == ParentPage.PBPaymentsWindow)
                            {
                                HeaderText = Languages.GetMessages("LBL0135");
                                OkButtonText = Languages.GetMessages("BTN0039");
                                ScanGuidText = Languages.GetMessages("LBL0141");
                            }
                            else
                            {                                
                                HeaderText = Languages.GetMessages("LBL0134");
                                OkButtonText = Languages.GetMessages("BTN0039");
                                ScanGuidText = Languages.GetMessages("LBL0141");
                            }

                            CancelButtonWidth = 0d;
                            OKButtonWidth = PopupWidth;
                            OKButtonEnabled = true;
                            TimeOutSeconds = CommonValue.TimeOutSeconds;
                            LanguageButttonVisibel = false;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "VmHappyPointCertify_PropertyChanged()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        private void BellButtonCommandHandler(object obj)
        {

            //BellButtonEnable = false;
            ShowPhoneInput = !ShowPhoneInput;

        }
        private void TalkButtonCommandHandler(object obj)
        {
            //TalkButtonEnable = false;
            ShowPhoneInput = !ShowPhoneInput;
        }

        #endregion Event Handlers


    }

}