using FGUI.ZM_Common_01;
using FGUI.ZM_Setting_07;
// using SGModule.ApplePay;
using SGModule.Common.Extensions;
using SGModule.Net;

using UnityEngine;

namespace RedHotRoast
{
    public class MenuUI : BaseUI
    {
        private MenuUICtrl ctrl;
        private MenuModel model;
        private FGUI.ZM_Setting_07.com_setting ui;
        private int selectIndex = -1;

        private int total_item;

        public MenuUI(MenuUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.MenuUI;
            this.ctrl = ctrl;
        }

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "ZM_Setting_07";
            uiInfo.assetName = "com_setting";
            uiInfo.layerType = UILayerType.Popup;
            uiInfo.isNeedOpenAnim = false;
            uiInfo.isNeedCloseAnim = false;
            uiInfo.isNeedUIMask = true;
        }

        #region 生命周期

        protected override void OnInit()
        {
            model = moduleManager.GetModel(ModelConst.MenuModel) as MenuModel;
        }

        protected override void OnClose()
        {

            CommonHelper.FadeOut(ui);

        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_Setting_07.com_setting;
        }

        protected override void OnOpenBefore(object args)
        {

            if (args != null)
            {
                var type = (int)args;
                ui.isHall.selectedIndex = type;  //type： 0是大厅  1是游戏
            }
            if (Screen.safeArea.y != 0)
            {
                ui.com_gold.y += Screen.safeArea.y;

            }
            ui.gift_switch.selectedIndex =  1;

            total_item = 8;
            selectIndex = DataMgr.PlayerAvatarId.Value;

            InitView();

        }

        protected override void OnOpen(object args)
        {
            CommonHelper.FadeIn(ui);

            // if (args != null)
            // {
            //     ui.menu.selectedIndex = (bool)args ? com_setting.Menu_settings : com_setting.Menu_person;

            // }
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            HallManager.Instance.AddChangeGiftSwitch(InitView);
            PreferencesDispatcher<int>.Instance.AddListener(DataMsg.playerAvatarId, UpdataAvatar);
            
        }

        protected override void RemoveListener()
        {
            HallManager.Instance.RemoveChangeGiftSwitch(InitView);
            PreferencesDispatcher<int>.Instance.RemoveListener(DataMsg.playerAvatarId, UpdataAvatar);
            
        }

        #endregion

        private void InitView()
        {
            ui.com_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}";

            var namStr = GameHelper.GetUserName();
            ui.edit_name.input.text = namStr;
            ui.edit_name.btn_amend.SetClick(SaveName);
            
            var headId = DataMgr.PlayerAvatarId.Value;
            GameHelper.SetSelfAvatar((ui.btn_head.head as head)?.load_avatar, headId);

            ui.btn_head.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PersonViewUI_Open);
            });
            ui.btn_back.SetClick(OnCloseView);
            ui.btn_music.SetClick(OnClickSetMusic);
            ui.btn_sound.SetClick(OnClickSoundBtn);

            ui.btn_privacy.menus.selectedIndex = btn_menu.Menus_privacy;
            ui.btn_terms.menus.selectedIndex = btn_menu.Menus_terms;
            ui.btn_official.menus.selectedIndex = btn_menu.Menus_official;
            //  ui.btn_credits.menus.selectedIndex = btn_menu.Menus_credits;
            ui.btn_privacy.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, 0); });
            ui.btn_terms.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, 1); });
            ui.btn_official.SetClick(() => { OpenBrowser.OpenURL("https://reddhotcompangost.com/"); });
            ui.btn_us.SetClick(() => { GameHelper.OpenEmail(); });
            //   ui.btn_credits.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, 2); });
            ui.btn_restore.SetClick(() =>
            {
                // ApplePayManager.Instance.AppleRestore((success, message) =>
                // {
                //     if (success)
                //     {
                //         Debug.Log("[barry] restore success: " + success);
                //         GameHelper.ShowTips("Restore_pur", true);
                //         SaveData.GetSaveObject().have_slot = success;
                //         DataMgr.VipLevel.Value = 3;
                //         DataMgr.VipExpirationTime.Value = ServerClock.GetCurrentServerTime() + 7 * 24 * 60 * 60;
                //     }
                //     else
                //     {
                //         GameHelper.ShowTips("recoverable_tips", true);
                //     }
                // });
            });

            ui.btn_language.SetClick(() => {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LanguageViewUI_Open);
            });
            SetUID();
            SetVersion();
            RefreshMusicUI();

            ui.btn_back_home.SetClick(() =>
            {
                GameDispatcher.Instance.Dispatch(GameMsg.ExitGame);
                if (!GameHelper.GetVipPrivilege(Subscription.RemoveInterstitialAd.As<int>()) && GameHelper.IsGiftSwitch())
                {
                    int random_ = UnityEngine.Random.Range(1, 100);
                    Debug.Log($"[back hall] SaveData.GetSaveObject().is_get_removead=========={SaveData.GetSaveObject().is_get_removead} ");
                    if (!SaveData.GetSaveObject().is_get_removead && random_ < GameHelper.GetCommonModel().HomeInterstitialAd)
                    {
                        //GameHelper.ShowInterstitial("BackHall");
                        // uiCtrlDispatcher.Dispatch(UICtrlMsg.AdcomingUI_Open);
                    }
                }

                CtrlCloseUI();
            });

        }
        
        private void UpdataAvatar(object obj = null)
        {
            var headId = DataMgr.PlayerAvatarId.Value;
            if (obj != null)
            {
                headId = obj.As<ChangeValue<int>>().newValue;
            }
            var head = ui.btn_head.head as head;
            if (head != null)
            {
                // var vipLevel = GameHelper.GetVipLevel();
                // if (vipLevel > 0)
                // {
                //     head.head.vip_loader.visible = true;
                //     head.vip_loader.url = $"ui://LG_Common/vip_{vipLevel}";
                // }
                // else
                // {
                //     head.vip_loader.visible = false;
                // }
                GameHelper.SetSelfAvatar(head.load_avatar, headId);
            }
        }
        
        private void SaveName()
        {
            var name = ui.edit_name.input.text;

            if (string.IsNullOrEmpty(name) || name.IsNullOrWhiteSpace())
            {
                GameHelper.ShowTips("empty_input", true);
                return;
            }

            // if (name.Equals(GameHelper.GetPlayerInviteCode()))
            // {
            //     return;
            // }

            if (name.Equals(DataMgr.PlayerName.Value)) return;

            GameHelper.ShowTips($"save_name",true);
            DataMgr.PlayerName.Value = name;
        }

        private void SetVersion()
        {
            // Debug.Log($"SetVersion====== {Application.version}");
            ui.text_version.SetVar("count", Application.version.ToString()).FlushVars();
        }

        private void SetUID()
        {
            ui.text_uid.SetVar("UID", GameHelper.GetLoginModel().Uid.ToString()).FlushVars();
        }

        public override void OnSwitchLanguage()
        {
            base.OnSwitchLanguage();

            SetVersion();

            SetUID();
        }

        private void OnCloseView()
        {
            // CloseMenu();
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Close, true);
            TimerHelper.mEasy.AddTimer(0.5f, () =>
           {
               CtrlCloseUI();
           });

        }

        private void OnClickSetMusic()
        {
            model.IsOpenMusic = !model.IsOpenMusic;
            RefreshMusicUI();
        }

        private void OnClickSoundBtn()
        {
            model.IsOpenEffect = !model.IsOpenEffect;
            RefreshMusicUI();
        }

        private void RefreshMusicUI()
        {
            ui.btn_music.on_off.selectedIndex =
                model.IsOpenMusic ? 1 : 0;
            ui.btn_sound.on_off.selectedIndex =
                model.IsOpenEffect ? 1 : 0;
        }
    }
}
