using Dont_Confuse;
using FairyGUI;
using FGUI.Setting_07;
using IgnoreOPS;
using SGModule.ApplePay;
using UnityEngine;
using btn_head = FGUI.Common_01.btn_head;

// using FGUI.G006_menu;

namespace ChillConnect
{
    public class PersonViewUI : BaseUI
    {
        private PersonViewUICtrl ctrl;
        private PersonViewModel model;
        private int _selectIndex = -1;

        private const int TotalItem = 8;

        private com_person ui;

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

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

        #region 生命周期

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

        protected override void OnClose()
        {
            WebviewManager.ShezhiACT(true);
        }

        protected override void OnBind()
        {
            ui = baseUI as com_person;
        }

        protected override void OnOpenBefore(object args)
        {

            // if (Screen.safeArea.y != 0)
            // {
            //     ui.title.y += Screen.safeArea.y;
            // }
            WebviewManager.ShezhiACT(false);
            _selectIndex = DataMgr.PlayerAvatarId.Value;

            InitView();
        }

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

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            HallManager.Instance.AddChangeGiftSwitch(InitView);
        }

        protected override void RemoveListener()
        {
            HallManager.Instance.RemoveChangeGiftSwitch(InitView);
        }

        #endregion

        private void InitView()
        {
            SetVersion();
            SetUID();
            SetHeadPic();

            var namStr = GameHelper.GetUserName();
            ui.edit_name.input.text = namStr;

            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://www.ballcrushbest.fun"); });

            ui.btn_us.SetClick(() => { GameHelper.OpenEmail(); });

            ui.btn_music.on_off.selectedIndex =
                model.IsOpenMusic ? btn_music_on_off.On_off_off : btn_music_on_off.On_off_on;
            ui.btn_sound.on_off.selectedIndex =
                GRoot.inst.soundVolume > 0 ? btn_music_on_off.On_off_off : btn_music_on_off.On_off_on;

            ui.btn_music.SetClick(SetMusic);
            ui.btn_sound.SetClick(SetSound);

            ui.btn_close.SetClick(() =>
            {
                ui.hide.Play(UpdateUserInfo);

            });
            ui.list.itemRenderer = UpdateItem;
            ui.list.numItems = TotalItem;
            if (GameHelper.IsGiftSwitch())
            {
               // ui.btn_restore.visible = false;
            }
            else
            {
                ui.btn_us.visible = true;
            }
            ui.btn_restore.SetClick(() =>
            {
                ApplePayManager.Instance.AppleRestore((success, message) =>
                {
                    if (success)
                    {
                        GameHelper.ShowTips("Restore Purchases Success!");
                        // SaveData.GetSaveObject().is_get_packreward = success;
                        SaveData.GetSaveObject().have_slot = success;
                        GameDispatcher.Instance.Dispatch(GameMsg.noads_refresh);
                    }
                    else
                    {
                        // Debug.Log("[barry] restore failed: " + success);
                        GameHelper.ShowTips("There are no recoverable transactions");
                    }
                });
            });
        }

        private void UpdateItem(int index, GObject items)
        {
            Debug.Log($"updateItem============index =={index}");
            var currentIndex = index + 1;
            var head = items as btn_item_head;
            var imgHead = head.head as btn_head;

            TextureHelper.SetAvatarToLoader(currentIndex, imgHead.load_avatar);
            head.head_select.selectedIndex = _selectIndex == currentIndex
                ? btn_item_head.Head_select_select
                : btn_item_head.Head_select_none;

            head.SetClick(() =>
            {
                _selectIndex = currentIndex;
                ui.list.numItems = TotalItem;

                SetHeadPic();
            });
        }

        private void SetHeadPic()
        {
            SetAvatar();

            var head = ui.head as btn_head;
            if (head == null) return;
            TextureHelper.SetAvatarToLoader(_selectIndex, head.load_avatar);
        }

        private void SetMusic()
        {
            model.IsOpenMusic = !model.IsOpenMusic;

            ui.btn_music.on_off.selectedIndex = model.IsOpenMusic
                ? btn_music_on_off.On_off_off
                : btn_music_on_off.On_off_on;


        }

        private void SetSound()
        {
            var sound = GRoot.inst.soundVolume;
            sound = sound > 0 ? 0 : 1;

            GRoot.inst.soundVolume = sound;
            PlayerPrefs.SetFloat("soundVolume", sound);
            ui.btn_sound.on_off.selectedIndex = sound > 0
                ? btn_music_on_off.On_off_off
                : btn_music_on_off.On_off_on;
        }
        private void SetVersion()
        {
            // Debug.Log($"SetVersion====== {Application.version}");
            ui.text_version.SetVar("count", Application.version).FlushVars();
        }

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

        private void SetAvatar()
        {
            if (_selectIndex != -1 && _selectIndex != DataMgr.PlayerAvatarId.Value)
            {
                DataMgr.PlayerAvatarId.Value = _selectIndex;
            }
        }


        private void UpdateUserInfo()
        {
            SaveName();

            CtrlCloseUI();
        }

        private void SaveName()
        {
            var name = ui.edit_name.input.text;

            if (string.IsNullOrEmpty(name) || name.IsNullOrWhiteSpace())
            {
                GameHelper.ShowTips("The input cannot be null", true);
                return;
            }

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

            // GameHelper.ShowTips("Name changed successfully");
            DataMgr.PlayerName.Value = name;
        }

    }
}