using System;
using FairyGUI;
using FGUI.G006_menu;
using UnityEngine;

namespace ScrewsMaster
{
    public class MenuUI : BaseUI
    {
        private MenuUICtrl ctrl;
        private MenuModel model;
        private FGUI.G006_menu.com_menu ui;

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

        protected override void SetUIInfo(UIInfo uiInfo)
        {
            uiInfo.packageName = "G006_menu";
            uiInfo.assetName = "com_menu";
            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.G006_menu.com_menu;
        }

        protected override void OnOpenBefore(object args)
        {
          //  var mode = (int)args;
            //  ui.switchgift.selectedIndex = mode;

            InitView();
        }

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

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            PreferencesDispatcher<string>.Instance.AddListener(PreferencesMsg.playerName, OnChangeName);
            PreferencesDispatcher<int>.Instance.AddListener(PreferencesMsg.playerAvatarId, OnChangeAvatar);
            HallManager.Instance.AddChangeGiftSwitch(InitView);
        }

        protected override void RemoveListener()
        {
            PreferencesDispatcher<string>.Instance.RemoveListener(PreferencesMsg.playerName, OnChangeName);
            PreferencesDispatcher<int>.Instance.RemoveListener(PreferencesMsg.playerAvatarId, OnChangeAvatar);
            HallManager.Instance.RemoveChangeGiftSwitch(InitView);
        }

        #endregion

        private void InitView()
        {
            if (GameHelper.IsGiftSwitch())
            {
                ui.switchgift.selectedIndex = 1;
            }
            else
            {
                ui.switchgift.selectedIndex = 0;
            }
            InitButtons();

            SetUID();
            SetVersion();
            RefreshMusicUI();
        }

        private void InitButtons()
        {
            ui.btn_pri.btn_state.selectedIndex = ui.btn_pri._Btn_state__1;
            ui.btn_terms.btn_state.selectedIndex = ui.btn_pri._Btn_state__2;
            ui.btn_contact.btn_state.selectedIndex = ui.btn_pri._Btn_state__3;

            ui.btn_close.SetClick(OnCloseView);
            ui.btn_music.SetClick(OnClickSetMusic);
            ui.btn_sound.SetClick(OnClickSoundBtn);
            ui.btn_contact.SetClick(OnClickContact);
            ui.btn_record.SetClick(OnClickRedeem);
            ui.btn_pri.SetClick(OnClickPrivacy);
            ui.btn_terms.SetClick(OnClickTerms);

            ui.ExitBtn.SetClick(() =>
            {
                CloseMenu();
                ShowScrews.Instance.TrackGameCompletion(false);
                ShowScrews.Instance.ClearLevelData();

                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Open);
            });
            ui.btn_restore.SetClick(() =>
            {
                PurchasingManager.Instance.IosRestore((success, message) =>
                {
                    // Debug.Log("[barry] restore success message: " + message);
                    if (success)
                    {
                        // Debug.Log("[barry] restore success: " + success);
                        GameHelper.ShowTips("Restore Purchases Success!");
                        SaveData.GetSaveobject().is_get_removead = success;
                        SaveData.GetSaveobject().is_get_battlepass = success;
                        SaveData.GetSaveobject().have_slot = success;
                        GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack);
                        GameDispatcher.Instance.Dispatch(GameMsg.BuyPack);
                        GameHelper.SetPayBox1(true);
                        GameHelper.SetPayBox2(true);
                        SaveData.saveDataFunc();
                    }
                    else
                    {
                        // Debug.Log("[barry] restore failed: " + success);
                        GameHelper.ShowTips("There are no recoverable transactions");
                    }
                });
                CtrlCloseUI();
            });
        }

        private void ItemRenderer(int index, GObject item)
        {
            var btnLang = item as btn_lang;
            var langVO = ConfigSystem.GetConfig<LangDisplayModel>().dataList[index];
            btnLang.text_lang.text = langVO.name;
            btnLang.onClick.Set(() =>
            {
                model.CurrLangId = langVO.id;
            });
            if (langVO.id == model.CurrLangId)
            {
                btnLang.cont_btn.selectedIndex = btn_lang.Btn_select;
            }
            else
            {
                btnLang.cont_btn.selectedIndex = btn_lang.Btn_none;
            }
        }

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

            SetVersion();
            SetUID();
        }

        private void SetUID()
        {
            ui.text_uid.text = $"UID:{GameHelper.GetLoginModel().uid}";
        }

        private void SetVersion()
        {
            ui.text_version.text = $"Version:{Application.version}";
        }

        private void CloseMenu(Action action = null)
        {
            CtrlCloseUI();
            action?.Invoke();
        }

        private void OnChangeName(ChangeValue<string> obj)
        {
        }

        private void OnChangeAvatar(ChangeValue<int> obj)
        {
        }

        private void OnCloseView()
        {
            CloseMenu();
        }

        private void OnClickRedeem()
        {
            CloseMenu(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MakeupRecordUI_Open); });
        }

        private void OnClickLanguage()
        {
            CloseMenu();
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LanguageWinUI_Open);
        }

        private void OnClickAvatar()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open);
        }

        private void OnClickProfile()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open);
        }

        private void OnClickPrivacy()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open);
        }

        private void OnClickTerms()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, true);
        }

        private void OnClickContact()
        {
             GameHelper.OpenEmail();
            //Application.OpenURL("https://official.nutboltparty.fun/");
        }

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

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

        private void RefreshMusicUI()
        {
            ui.btn_music.cont_button.selectedIndex =
                model.IsOpenMusic ? btn_switch_music.Button_on : btn_switch_music.Button_off;
            ui.btn_sound.cont_button.selectedIndex =
                model.IsOpenEffect ? btn_switch_sound.Button_on : btn_switch_sound.Button_off;
        }
    }
}