using System;
using BingoBrain.Core;
using BingoBrain.HotFix;
using DontConfuse;
using FGUI.ACommon;
using Newtonsoft.Json;
using Spine.Unity;
using UnityEngine;

namespace BingoBrain
{
    public class PettyAwardUI : BaseUI
    {
        private PettyAwardUICtrl ctrl;
        private PettyAwardModel model;
        private FGUI.ZM_Petty.com_petty_award ui;
        private Action closeCallback;
        public PettyAwardUI(PettyAwardUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.PettyAwardUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期
        protected override void OnInit()
        {
            //model = ModuleManager.Instance.GetModel(ModelConst.PettyAwardModel) as PettyAwardModel;
        }

        protected override void OnClose()
        {
            closeCallback?.Invoke();
        }

        protected override void OnBind()
        {
            ui = baseUI as FGUI.ZM_Petty.com_petty_award;
        }

        protected override void OnOpenBefore(object args)
        {

            InitView();
        }

        protected override void OnOpen(object args)
        {
            //open_sign = (System.Action)args;
        }

        protected override void OnHide()
        {
        }

        protected override void OnDisplay(object args)
        {
        }
        #endregion

        #region 消息
        protected override void AddListener()
        {

        }
        protected override void RemoveListener()
        {

        }
        #endregion


        private int _mLastState;
        //初始化页面逻辑
        private void InitView()
        {
            _mLastState = SaveData.GetSaveobject().PettyState;
            Debug.Log($"PettyState============: {SaveData.GetSaveobject().PettyState}");
            var num = GameHelper.GetCommonModel().SmallReward;
            ui.com_get_panel.text_reward.text = $"{GameHelper.Get102Str(num)} USD";


            ui.com_get_panel.btn_get.SetClick(GotoEnterAccount);
            ui.btn_close.SetClick(() =>
            {
                if (ui.state.selectedIndex == 4)
                {
                    GotoEnterAccount();
                }
                else
                {
                    CtrlCloseUI();
                }
            });

            if (_mLastState == 0)
            {
                // SkeletonAnimation sk = FXManager.Instance.SetFx<SkeletonAnimation>(ui.anim, Fx_Type.fx_petty_reward, ref closeCallback);
                SkeletonAnimation sk = null;
                FX.Instance.SetFx<SkeletonAnimation>(ui.anim, Fx_Type.fx_petty_reward,
                    ps =>
                    {
                        //  ps.transform.localPosition = new Vector3(0, 195, 0);
                        sk = ps;

                    }, closeCallback);

                sk.state.SetAnimation(0, "newbie_reward_an01", false);

                sk.state.Complete += (a) =>
                {
                    sk.state.SetAnimation(0, "newbie_reward_an02", true);
                    ui.btn_gerAward.SetClick(() =>
                    {
                        ui.btn_gerAward.visible = false;
                        sk.state.SetAnimation(0, "newbie_reward_an03", false);
                        sk.state.Complete += (a) =>
                        {
                            ui.state.selectedIndex = 1;
                            SaveData.GetSaveobject().PettyState = 1;
                            ui.anim.visible = false;
                        };
                    });

                };
            }
            else
            {
                GotoPanel(_mLastState);
            }
        }

        private void GotoPanel(int index)
        {
            switch (index)
            {
                case 1:
                    ui.state.selectedIndex = 1;
                    break;
                case 2:
                    ui.state.selectedIndex = 2;
                    GotoEnterAccount();
                    break;
                case 3:
                    ui.state.selectedIndex = 3;
                    GotoDetail();
                    break;
            }
        }

        private void GotoEnterAccount()
        {
            ui.state.selectedIndex = 2;
            SaveData.GetSaveobject().PettyState = 2;
            if (!SaveData.GetSaveobject().PettyAccount.IsNullOrWhiteSpace())
            {
                ui.com_account.com_email.enter_email.text = SaveData.GetSaveobject().PettyAccount;
            }
            if (!SaveData.GetSaveobject().PettyFirstName.IsNullOrWhiteSpace())
            {
                ui.com_account.com_first_name.enter_first_name.text = SaveData.GetSaveobject().PettyFirstName;
            }
            if (!SaveData.GetSaveobject().PettyLastName.IsNullOrWhiteSpace())
            {
                ui.com_account.com_last_name.enter_last_name.text = SaveData.GetSaveobject().PettyLastName;
            }

            ui.com_account.btn_confirm.SetClick(ConfirmClick);
        }

        private void ConfirmClick()
        {
            var account = ui.com_account.com_email.enter_email.text.Replace(" ", "");
            if (account == "")
            {
                GameHelper.ShowTips("Please enter the correct account information", true);
                return;
            }

            if (!GameHelper.CheckAccountValidly(account))
            {
                GameHelper.ShowTips("Please enter the correct account information", true);
                return;
            }

            var fname = ui.com_account.com_first_name.enter_first_name.text.Replace(" ", "");
            if (!GameHelper.CheckNameValidly(fname))
            {
                GameHelper.ShowTips("Please enter the correct account information", true);
                return;
            }

            var lname = ui.com_account.com_last_name.enter_last_name.text.Replace(" ", "");
            if (!GameHelper.CheckNameValidly(lname))
            {
                GameHelper.ShowTips("Please enter the correct account information", true);
                return;
            }

            SaveData.GetSaveobject().PettyAccount = account;
            SaveData.GetSaveobject().PettyFirstName = fname;
            SaveData.GetSaveobject().PettyLastName = lname;

            GotoSecondConfirm(account, fname, lname);

        }

        private void GotoSecondConfirm(string account, string fname, string lname)
        {
            ui.state.selectedIndex = 4;
            PaymentMsg info = new PaymentMsg
            {
                email = account,
                first_name = fname,
                last_name = lname
            };

            ui.com_second_confirm.text_account.SetVar("account", account).FlushVars();
            ui.com_second_confirm.text_first_name.SetVar("name", fname).FlushVars();
            ui.com_second_confirm.text_last_name.SetVar("name", lname).FlushVars();

            ui.com_second_confirm.btn_confirm.SetClick(() =>
            {
                ui.com_second_confirm.btn_confirm.enabled = false;
                NetworkKit.PostWithHeader<object>("shop/payOutUserInfo", info, (isSuccess, obj) =>
                {
                    Debug.Log("[petty ui]-------------payOutUserInfo---" + JsonConvert.SerializeObject(info));
                    if (isSuccess)
                    {
                        GotoDetail();
                    }
                    else
                    {
                        GameHelper.ShowTips("Failed to save information., please try again");
                        ui.com_second_confirm.btn_confirm.enabled = true;
                    }
                });
            });
        }

        private void GotoDetail()
        {
            ui.state.selectedIndex = 3;
            SaveData.GetSaveobject().PettyState = 3;

            var pettyAmount = SaveData.GetSaveobject().PettyAmount;
            if (pettyAmount != 0)
            {
                ui.com_detail.text_amount.SetVar("num", GameHelper.Get102Str(pettyAmount)).FlushVars();
            }
            else
            {
                var num = GameHelper.GetCommonModel().SmallReward;
                ui.com_detail.text_amount.SetVar("num", GameHelper.Get102Str(num)).FlushVars();
                SaveData.GetSaveobject().PettyAmount = num;
            }

            var pettyDateTime = SaveData.GetSaveobject().PettyDateTime;
            if (!pettyDateTime.IsNullOrWhiteSpace())
            {
                ui.com_detail.text_data.SetVar("data", pettyDateTime).FlushVars();
            }
            else
            {
                var dateTime = DateTime.Now.ToString("yyyy.MM.dd");
                ui.com_detail.text_data.SetVar("data", dateTime).FlushVars();
                SaveData.GetSaveobject().PettyDateTime = dateTime;
            }

            var pettyOrderID = SaveData.GetSaveobject().PettyOrderID;
            if (!pettyOrderID.IsNullOrWhiteSpace())
            {
                ui.com_detail.text_order.SetVar("order", pettyOrderID).FlushVars();
            }
            else
            {
                string datePart = DateTime.Now.ToString("yyyyMMdd");
                System.Random random = new System.Random();
                string randomPart = random.Next(1000, 9999).ToString(); // 生成1000-9999之间的四位数
                ui.com_detail.text_order.SetVar("order", datePart + randomPart).FlushVars();

                SaveData.GetSaveobject().PettyOrderID = datePart + randomPart;
            }


            ui.com_detail.text_email.SetVar("email", SaveData.GetSaveobject().PettyAccount).FlushVars();

            var pettyDataLimit = SaveData.GetSaveobject().PettyDataLimit;
            if (pettyDataLimit != 0)
            {
                ui.com_detail.text_limit.SetVar("day", pettyDataLimit.ToString()).FlushVars();
            }
            else
            {
                var day = GameHelper.GetCommonModel().ProcessingTime;
                ui.com_detail.text_limit.SetVar("day", day.ToString()).FlushVars();
                SaveData.GetSaveobject().PettyDataLimit = day;
            }
        }
    }
}
namespace DontConfuse
{
    public class PaymentMsg
    {
        public string email;
        public string first_name;
        public string last_name;
    }
}