using System.Collections.Generic;
using FGUI.ZM_Common_01;
using UnityEngine;
using FairyGUI;
using FGUI.LG_Vip;
using SGModule.Common.Helper;
using SGModule.NetKit;
using SGModule.MarkdownKit;
using Newtonsoft.Json;
// using SGModule.ApplePay;
using SGModule.Net;
using System.Linq;
using SGModule.Common.Extensions;

public enum VipDay
{
    Week = 7,
    Month = 30,
    Year = 365
}

namespace RedHotRoast
{
    public class VipClubViewUI : BaseUI
    {
        private readonly List<string> _vipEquity1 = new();

        private readonly List<string> _vipEquity2 = new();

        private List<SubscriptionBenefits> _benefitsList = new List<SubscriptionBenefits>();
        private VipClubViewUICtrl ctrl;
        private VipClubViewModel model;
        private FGUI.LG_Vip.com_vip ui;

        public VipClubViewUI(VipClubViewUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.VipClubViewUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期

        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.VipClubViewModel) as VipClubViewModel;
        }

        protected override void OnClose()
        {
            if (_loader != null && !_loader.isDisposed && _loader.texture != null)
            {
                _loader.texture = null;
            }
            _loader = null;
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.LG_Vip.com_vip;
        }

        private List<VipClub> vip_list = new List<VipClub>();
        //这个要做下标，或者控制器的索引，所以从0开始（Vip是1，2，3）
        private int _level = 2;

        private GLoader _loader = new GLoader();
        protected override void OnOpenBefore(object args)
        {
            _loader = ui.bg_loader;
            SetBenefits();
            if (Screen.safeArea.y != 0)
            {
                ui.group_.y += 68;
            }
            if (GameHelper.IsGiftSwitch())
            {
                var fileName = GameHelper.GetBackgroundName(4);
                TextureHelper.SetImgLoader(ui.bg_loader, fileName, null, "Background/", FolderNames.BackgroundName);
            }

            TrackKit.SendEvent(ADEventTrack.Subscription, ADEventTrack.Property.vip_show_page);

            // 检查VIP是否过期
            GameHelper.CheckVipExpiration();

            _level = GameHelper.GetVipLevel() > 0 ? GameHelper.GetVipLevel() - 1 : 2;
            if (args != null) _level = (int)args;

            vip_list = ConfigSystem.GetConfig<VipClub>();
            InitView();
            // ui.text_terms.text=
            // Debug.Log(MarkdownDataMgr.TryGetValue("user", out MarkdownData data));
            // Debug.Log(JsonConvert.SerializeObject(data));\

            ui.btn_terns.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, 1);
            });
            ui.btn_pri.SetClick(() =>
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, 0);
            });

            if (GameHelper.IsGiftSwitch())
            {
                int random_ = Random.Range(0, 100);
                bool need_open = false;
                if (random_ < GameHelper.GetCommonModel().VIPGuideRate)
                {
                    if (GameHelper.GetVipLevel() > 0 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().VIPGuide)
                    {


                        // List<int> unlocklist = new List<int>();
                        if ((GameHelper.GetCommonModel().Live == 1) &&
                            (GameHelper.GetLevel() >= GameHelper.GetCommonModel().LivePreview) &&
                            (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockLive[1]))
                        {
                            // if (DataMgr.IsUnlockLive.Value < 0) //未解锁。
                            // {
                            //  unlocklist.Add(0);
                            need_open = true;
                            // }
                        }

                        if ((GameHelper.GetCommonModel().Secret == 1) &&
                            (GameHelper.GetLevel() >= GameHelper.GetCommonModel().SecretPreview) &&
                            (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockSecret[1]))
                        {
                            // if (DataMgr.IsUnlockSecret.Value < 0) //未解锁。
                            // {
                            // unlocklist.Add(1);
                            need_open = true;
                            //   }
                        }
                        // if ((GameHelper.GetCommonModel().Assitant == 1) &&
                        // (GameHelper.GetLevel() >= GameHelper.GetCommonModel().AssitantPreview))
                        // {
                        //     // if (DataMgr.IsUnlockSecret.Value < 0) //未解锁。
                        //     // {
                        //     // unlocklist.Add(1);
                        //     need_open = true;
                        //     //   }
                        // }
                    }

                    if (need_open) uiCtrlDispatcher.Dispatch(UICtrlMsg.SubUnlockUI_Open);
                    else if (GameHelper.GetVipLevel() < 0 && GameHelper.GetLevel() >= GameHelper.GetCommonModel().VIPGuide)
                    {
                        uiCtrlDispatcher.Dispatch(UICtrlMsg.SubUnlockUI_Open);
                    }
                }

            }
        }

        protected override void OnOpen(object args)
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }

        #endregion

        #region 消息

        protected override void AddListener()
        {
            GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.AddListener(GameMsg.BuyVip, InitView);
        }

        protected override void RemoveListener()
        {
            GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success);
            GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, InitView);
        }

        #endregion

        void pay_success(object str)
        {
            string type = (string)str;
            string purch_number = "";

            if (type.StartsWith("vip_club"))
            {
                InitView();
            }
        }

        //初始化页面逻辑
        private void InitView(object a = null)
        {
            resetVipLevel();

            ui.btn_week.text_price.text = GameHelper.getPrice((decimal)vip_list[0].DiscountPrice);
            ui.btn_month.text_price.text = GameHelper.getPrice((decimal)vip_list[1].DiscountPrice);
            ui.btn_year.text_price.text = GameHelper.getPrice((decimal)vip_list[2].DiscountPrice);
            ui.btn_week.text_price_old.text = GameHelper.getPrice((decimal)vip_list[0].Price);
            ui.btn_month.text_price_old.text = GameHelper.getPrice((decimal)vip_list[1].Price);
            ui.btn_year.text_price_old.text = GameHelper.getPrice((decimal)vip_list[2].Price);

            ui.btn_close.SetClick(CtrlCloseUI);
            ui.btn_restore.visible = !GameHelper.IsGiftSwitch();
            ui.btn_restore.SetClick(() =>
            {
                // ApplePayManager.Instance.AppleRestore((success, message) =>
                // {
                //     Debug.Log($"[barry] restore success message: {message}---- {JsonConvert.SerializeObject(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;
                //
                //         InitView();
                //     }
                //     else
                //     {
                //         GameHelper.ShowTips("recoverable_tips", true);
                //     }
                // });
            });

            SetSubBtnState(_level, (int)VipDay.Year);

            ui.btn_week.SetClick(() => { SetSubBtnState(0, (int)VipDay.Week); });

            ui.btn_month.SetClick(() => { SetSubBtnState(1, (int)VipDay.Month); });

            ui.btn_year.SetClick(() => { SetSubBtnState(2, (int)VipDay.Year); });


            ui.btn_sub.SetClick(() =>
            {
                if (ui.btn_sub.is_buy.selectedIndex == 1) return;

                string _type = "vip_club" + _level;
                ApplePayClass maxPayData = new ApplePayClass
                {
                    amount = (int)System.Math.Round(vip_list[_level].DiscountPrice * 100),
                    sku = PurchasingManager.GetPaySku(GetTypeByIndex(_level)),
                    currency = "USD",
                    shopName = _type
                };
                MaxPayManager.Instance.Buy(maxPayData);
            });


        }

        private void resetVipLevel(object obj = null)
        {
            var lv = GameHelper.GetVipLevel() > 0 ? GameHelper.GetVipLevel() : 0;
            ui.vip_lv.selectedIndex = lv;


            ui.vip_icon_loader.visible = lv > 0;
            ui.vip_icon_loader.url = $"ui://LG_Common/vip_{lv}";
        }

        private PayType GetTypeByIndex(int index)
        {
            return index switch
            {
                0 => PayType.weekly_subscription,
                1 => PayType.monthly_subscription,
                2 => PayType.yearly_subscription,
                _ => PayType.weekly_subscription
            };
        }

        private void SetSubBtnState(int index, int day)
        {
            Debug.Log($"lvele============{index}");

            _level = index;
            ui.btn_sub.title = Language.GetContentParams("vip_buy", new[] {GameHelper.getPrice((decimal)vip_list[index].DiscountPrice), day.ToString()});

            ui.btn_week.img_select.visible = index == 0;
            ui.btn_month.img_select.visible = index == 1;
            ui.btn_year.img_select.visible = index == 2;

            ui.list.itemRenderer = ItemRenderer;
            ui.list.numItems = GameHelper.IsGiftSwitch() ? _vipEquity2.Count : _vipEquity1.Count;

            //vip等级（1:7天 2:30天 3:365天）
            var selectIndex = 0;
            if (_level <= GameHelper.GetVipLevel() - 1) //比如：如果订阅了30天，则30天和7天的订阅按钮隐藏，显示已订阅
            {
                selectIndex = 1;
            }

            ui.btn_sub.is_buy.selectedIndex = selectIndex;

        }

        private void ItemRenderer(int index, GObject obj)
        {
            var item = (item_viplist)obj;
            // if (index == Subscription.UnlockAssitant.As<int>() - 1)
            // {
            //     item.visible = false;
            //     return;
            // }
            if (GameHelper.IsGiftSwitch())
            {
                var state = 1;
                var equityText = GameHelper.getLanguageByKey(_vipEquity2[index]);

                if (vip_list[_level].SubscriptionBenefits2.Contains(index + 1))
                {
                    state = 0;
                }

                item.title.text = equityText;
                item.have.selectedIndex = state;
                item.icon_loader.url = $"ui://LG_Vip/icon_{index + 1}";
            }
            else
            {
                // if (vip_list[_level].SubscriptionBenefits1 != null &&
                //     index < vip_list[_level].SubscriptionBenefits1.Length)
                // {
                // var benefits = vip_list[_level].SubscriptionBenefits1[index] - 1;
                // 可以在这里使用 benefits 变量进行后续操作
                var state = 1;
                if (vip_list[_level].SubscriptionBenefits1.Contains(_vipEquity1_id_list[index]))
                {
                    state = 0;
                }
                if (vip_list[_level].SubscriptionBenefits1 != null &&
                    index < vip_list[_level].SubscriptionBenefits1.Length)
                {
                    var benefits = vip_list[_level].SubscriptionBenefits1[index] - 1;
                    item.title.text = GameHelper.getLanguageByKey(_benefitsList[benefits].key);
                }
                item.have.selectedIndex = state;
                if (index == 0) item.icon_loader.url = $"ui://LG_Vip/icon_3";
                if (index == 1) item.icon_loader.url = $"ui://LG_Vip/icon_5";
                if (index == 2) item.icon_loader.url = $"ui://LG_Vip/icon_6";
                if (index == 3) item.icon_loader.url = $"ui://LG_Vip/icon_6";
                // item.icon_loader.visible = false;
                // }
            }
        }
        private void SetBenefits()
        {
            _benefitsList = ConfigSystem.GetConfig<SubscriptionBenefits>();
            Debug.Log(JsonConvert.SerializeObject(_benefitsList));
            const int vipTypeStandard = 1;

            if (_benefitsList == null) return;

            foreach (var vip in _benefitsList.Where(vip => vip != null))
            {
                if (vip.Type == vipTypeStandard)
                {
                    _vipEquity2.Add(vip.key);
                }
                else
                {
                    _vipEquity1.Add(vip.key);
                    Debug.Log(JsonConvert.SerializeObject(vip));
                    _vipEquity1_id_list.Add(vip.id);
                }
            }
            Debug.Log(JsonConvert.SerializeObject(_vipEquity1_id_list));

        }
        private List<int> _vipEquity1_id_list = new List<int>();
        //Vip权益内容列表
    }
}