using FairyGUI;
using BingoBrain.Core;
using BingoBrain.HotFix;
using FGUI.JTask;
using UnityEngine;
using Newtonsoft.Json;
using DontConfuse;

namespace BingoBrain
{
    public class SomsionUI : BaseUI
    {
        private SomsionUICtrl ctrl;
        private SomsionModel model;
        private com_task ui;

        public SomsionUI(SomsionUICtrl ctrl) : base(ctrl)
        {
            uiName = UIConst.SomsionUI;
            this.ctrl = ctrl;
        }

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

        #region 生命周期

        protected override void OnInit()
        {
            model = ModuleBoardk.GetModel(ModelConst.SomsionModel) as SomsionModel;
        }

        protected override void OnClose()
        {
            ui?.FadeOut();
            WebviewManager.Instance.SetDarkThough(true);
        }

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

        protected override void OnOpenBefore(object args)
        {
            WebviewManager.Instance.SetDarkThough(false);
            Audio.Instance.PlayDynamicEffect("pop_open");
            ui.list_task.itemRenderer = ItemRenderer;
            ui.list_task.numItems = PreferencesMgr.Instance.ActiveMissions.Count;
            ui.closeButton.SetClick(() =>
            {
                Audio.Instance.PlayDynamicEffect("button");
                CtrlCloseUI();
            });
            RefreshTime();
            Hall.Instance.UpdateSecondEvent += RefreshTime;

        }

        private void RefreshTime()
        {
            ui.text_time.text = model.GetNextReTimeStr;
        }

        internal void ItemRenderer(int index, GObject item)
        {

            com_Singletask _Singletask = item as com_Singletask;
            if (GameHelper.IsGiftSwitch()) _Singletask.gift.selectedIndex = 1;
            Task task = PreferencesMgr.Instance.ActiveMissions[index];
            Debug.Log(JsonConvert.SerializeObject(PreferencesMgr.Instance.ActiveMissions));
            TaskList taskVO = GameHelper.GetConfig<TaskListModel>().GetData(task.Id);
            _Singletask.text_taskname.text = taskVO.taskName.Replace("%s", taskVO.taskNum.ToString());
            string val = string.Empty;
            if (task.RewardId == 101)
            {
                val = GameHelper.GetNoDecimalUnitStr(task.RewardSum);
            }

            if (task.RewardId == 102)
            {
                val = $"{GameHelper.Get102Str((decimal)task.RewardSum)}";
            }

            _Singletask.text_num.text = val;
            switch (taskVO.rewardID)
            {
                case 101:
                    _Singletask.cont_currency.selectedIndex = com_Singletask.Currency_coin;
                    break;
                case 102:
                    _Singletask.cont_currency.selectedIndex = com_Singletask.Currency_diam;
                    break;
            }

            // TextureHelper.GetItemIcon(taskVO.rewardID, tx => { _Singletask.loader_reward.texture = tx; });
            _Singletask.cont_collect.selectedIndex = com_Singletask.Collect_none;
                    _Singletask.text_progress.text = task.Progress + "/" + task.MaxProgress;
            if (task.IsReward)
            {
                _Singletask.com_task_pb.TweenValue(task.MaxProgress, 0.3f);
                _Singletask.com_task_pb.max = task.MaxProgress;
                _Singletask.btn_task.cont_button.selectedIndex = btn_task.Button_done;
                _Singletask.cont_collect.selectedIndex = 2;
            }
            else
            {
                _Singletask.com_task_pb.max = task.MaxProgress;
                if (task.Progress >= task.MaxProgress)
                {
                    _Singletask.btn_task.cont_button.selectedIndex = btn_task.Button_collect;
                    _Singletask.cont_collect.selectedIndex = com_Singletask.Collect_collect;

                    _Singletask.com_task_pb.TweenValue(task.MaxProgress, 0.3f);
                    _Singletask.btn_task.SetClick(() => { OnClickTaskBtn(_Singletask, task); });
                }
                else
                {
                    _Singletask.btn_task.cont_button.selectedIndex = btn_task.Button_num;

                    //  _Singletask.btn_task.text_num.text = task.Progress + "/" + task.MaxProgress;


                    _Singletask.com_task_pb.TweenValue(task.Progress, 0.3f);
                    _Singletask.btn_task.SetClick(OnClickGoPlay);
                }
            }
        }

        private void OnClickTaskBtn(com_Singletask singletask, Task task)
        {
            Audio.Instance.PlayDynamicEffect("button");
            if (task.IsReward)
            {
                return;
            }

            if (task.Progress < task.MaxProgress)
            {
                OnClickGoPlay();
                return;
            }

            // 领取奖励
            if (task.IsMulti)
            {
                GameHelper.GetRewardExtra(task.RewardId, (decimal)task.RewardSum, task.cont_index, isSuccess =>
                {
                    if (!isSuccess)
                    {
                        gameDispatcher.Dispatch(BingoInfo.ShowGameOver);
                    }
                });
            }
            else
            {
                GameHelper.GetRewardOnly(task.RewardId, (decimal)task.RewardSum, RewardOrigin.DailyTask);
            }

            if (!PreferencesMgr.Instance.FinishTaskList.Contains(task.Id))
            {
                PreferencesMgr.Instance.FinishTaskList.Add(task.Id);
                PreferencesMgr.Instance.SaveFinishTaskList();
            }

            singletask.btn_task.onClick.Clear();
            task.IsReward = true;
            singletask.cont_collect.selectedIndex = com_Singletask.Collect_none;
            singletask.btn_task.cont_button.selectedIndex = btn_task.Button_done;
            PreferencesMgr.Instance.SaveActiveMissions();
        }

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

        #endregion

        private void OnClickGoPlay()
        {
            CtrlCloseUI();
            GameDispatcher.Instance.Dispatch(BingoInfo.MainTab,0);
        }
    }
}