using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GCGame.Table;
using Games.GlobeDefine;
using Module.Log;

// 试炼副本统一的左侧进度信息面板
public class TestingCopyInfoCtr : MonoBehaviour {

    private void Awake()
    {
        hasReqRankInfo = false;
        InitRewPrefab();  //初始化4个
    }

    private void OnDestroy()
    {
        hasReqRankInfo = true;
    }

    // 标记能否关闭请求数据
    private bool hasReqRankInfo = false;        // 是否已经请求过数据
    public bool CanReqRankInfo
    {
        get
        {
            return !hasReqRankInfo;
        }
    }

    public static TestingCopyInfoCtr Instance;
    private void OnEnable()
    {
        Instance = this;
        //if (MissionDialogAndLeftTabsLogic.Instance())
        //{
        //    MissionDialogAndLeftTabsLogic.Instance().HideMissionDialog(false);
        //    MissionDialogAndLeftTabsLogic.SetSwitch(UIInfo.TestingCopyInfo);
        //}

        // 默认关闭排行榜信息,等待排行榜信息返回激活
        rankInfoPanel.SetActive(false);
        OnBtnShow();
    }

    private void AskForRank(int fubenID, int selectDiffcultyType)
    {
        Tab_TestingCopy testingCopy = TableManager.GetTestingCopyByID(fubenID, 0);
        int _NeedSendDiffcultyEnum = -1;

        if (testingCopy != null)
        {
            _NeedSendDiffcultyEnum = testingCopy.GetDiffcultyEnumValuebyIndex(selectDiffcultyType);
        }

        if(_NeedSendDiffcultyEnum != -1)
        {
            CG_REQ_RANK_LIST req = (CG_REQ_RANK_LIST)PacketDistributed.CreatePacket(MessageID.PACKET_CG_REQ_RANK_LIST);
            req.Ranktype = _NeedSendDiffcultyEnum;
            req.SendPacket();
        }
    }
    
    public void OnRankInfoPacket(GC_RET_RANK_LIST packet)
    {
        Tab_TestingCopy testingCopy = TableManager.GetTestingCopyByID(_CurFubenId, 0);
        if(testingCopy == null || packet.ranklistCount <= 0)
        {
            rankInfoPanel.SetActive(false);
            return;
        }
        _CopyName.text = testingCopy.TestingName;
        string playName_R = GetProValueStr((int)RankWindowNew.RankPropID.UserName, packet.GetRanklist(0));
        int maxLevel = (int)GetProValueInt((int)RankWindowNew.RankPropID.TestingCopyPassedLevel, packet.GetRanklist(0));

        rankInfoPanel.SetActive(true);
        rankPlayerName.text = playName_R;
        if(_CurFubenId == 6041)
        {
            rankPlayerInfo.text = StrDictionary.GetClientDictionaryString("#{6729}", maxLevel.ToString());
        }
        else
        {
            rankPlayerInfo.text = StrDictionary.GetClientDictionaryString("#{6734}", maxLevel.ToString());
        }
    }

    public void AskForInfo()
    {
        ReqTestingCopyMissionInfo req = new ReqTestingCopyMissionInfo();
        req._Flag = 1;
        req.SendMsg();
    }

    private void OnDisable()
    {
        Instance = null;
        if (MissionDialogAndLeftTabsLogic.Instance())
            MissionDialogAndLeftTabsLogic.Instance().HideMissionDialog(true);
    }

    public void OnSwitchBtnClick()
    {
        if (MissionDialogAndLeftTabsLogic.Instance())
        {
            MissionDialogAndLeftTabsLogic.Instance().HideMissionDialog(true);
            MissionDialogAndLeftTabsLogic.SetSwitch(UIInfo.TestingCopyInfo);
            MissionDialogAndLeftTabsLogic.Instance().SetSwitchBtn();
            UIManager.CloseUI(UIInfo.TestingCopyInfo);
        }
        else
        {
            UIManager.ShowUI(UIInfo.MissionInfoController, delegate (bool bSuccess, object param)
            {
                if(bSuccess)
                {
                    MissionDialogAndLeftTabsLogic.SetSwitch(UIInfo.TestingCopyInfo);
                    MissionDialogAndLeftTabsLogic.Instance().SetSwitchBtn();
                    UIManager.CloseUI(UIInfo.TestingCopyInfo);
                }
            });
        }
    }

    public Text _CopyName;
    public Text _CurLevel;
    public GameObject _CopyDescGO;               // 关卡详细描述显示控制
    public Text _CopyDescText;                        // 关卡详细描述
    public Text _ProgressDesc;
    public Text _ProgressValue;
    public GameObject _ProgressBarGO;               // 进度条控制
    public Slider _ProgressSlider;                  // 进图条

    public GameObject _RewPanel;

    public GameObject _NextRefreshPanel;
    public Text _NextRefreshTime;
    public GameObject _RemainTimePanel;
    public Text _RemainTime;

    public Transform _RewParent;
    public GameObject _RewItemPrefab;

    // 排行榜相关
    public GameObject rankInfoPanel;
    public Text rankPlayerName;
    public Text rankPlayerInfo;

    //积分
    public GameObject _SnatchScorepanel;
    public UIImgText _Score;

    private int _TotalRemainTime;
    private int _TotalNextRefreshTime;
    private bool _HasOpenUI = false;

    private int _CurFubenId = -1;
    public int CurFubenId
    {
        get { return _CurFubenId; }
    }

    private int _Difficult = -1;
    public int Difficult
    {
        get { return _Difficult; }
    }

    private int _NextFreshTime = -1;
    public int NextFreshTime
    {
        get { return _NextFreshTime; }
    }

    public void OnPacket(UpdateTestingCopyInfo packet)
    {

        if (CanReqRankInfo)
        {
            AskForRank(packet._FubenId, packet._Difficult);
            hasReqRankInfo = true;
        }

        _Difficult = packet._Difficult;
        _CurFubenId = packet._FubenId;
        if (packet._IsRefreshProgress == 1)  //只刷新进度
        {
            InitProgress(packet._ProgressDesc, packet._CurProgress, packet._TotalProgress);
            return;
        }

        if(packet._isNeedProgress == 1)
        {
            _ProgressBarGO.SetActive(false);
        }
        else
        {
            _ProgressBarGO.SetActive(true);
        }

        Debug.LogError("packet._ExperimentScore : " + packet._ExperimentScore);
        if (!_Score.text.Equals(packet._ExperimentScore.ToString()))
            _Score.text = packet._ExperimentScore + "";

        if (packet._CopyDes != -1)
        {
            _CopyDescGO.SetActive(true);
            _CopyDescText.text = StrDictionary.GetClientDictionaryString("#{" + packet._CopyDes + "}");
        }
        else
        {
            _CopyDescGO.SetActive(false);
        }

        CreateRewItem(packet._awardItems);
        InitCurLevelDesc(packet._CurChallengeLevel, packet._CurLevelType);
        if (packet._TickCount != -1)
        {
            _RemainTimePanel.SetActive(true);
            InitRemainTime(packet._TickCount);
        }else
        {
            _RemainTimePanel.SetActive(false);
        }

        if(packet._NextRefreshTime != -1)
        {
            _RemainCountTime = 0.0f;
            _NextRefreshPanel.SetActive(true);
            _NextFreshTime = packet._NextRefreshTime;
            InitNextRefreshTime(packet._NextRefreshTime);
        }else
        {
            _NextRefreshPanel.SetActive(false);
        }

        InitProgress(packet._ProgressDesc, packet._CurProgress, packet._TotalProgress);
    }

    private enum LevelType
    {
        SneakAttack = 1,
        Welfare,
        Boss,
    }

    public void InitCurLevelDesc(int level, int type = -1)
    {
        _CurLevel.text = StrDictionary.GetClientDictionaryString("#{51807}", level);
        if(type != -1)
        {
            switch(type)
            {
                case (int)LevelType.Welfare:
                    _CurLevel.text += StrDictionary.GetClientDictionaryString("#{51808}");
                    break;
                case (int)LevelType.SneakAttack:
                    _CurLevel.text += StrDictionary.GetClientDictionaryString("#{51809}");
                    break;
                case (int)LevelType.Boss:
                    _CurLevel.text += StrDictionary.GetClientDictionaryString("#{51812}");
                    break;
            }
        }
    }

    public void InitProgress(string _Desc, int curValue, int totalValue)
    {
        _ProgressDesc.text = StrDictionary.GetServerDictionaryFormatString(_Desc);
        //_ProgressDesc.text = StrDictionary.GetClientDictionaryString("#{" + _DescID + "}");
        _ProgressValue.text = StrDictionary.GetClientDictionaryString("#{3318}", curValue, totalValue);
        _ProgressSlider.value = (float)curValue / (float)totalValue > 1 ? 1 : (float)curValue / (float)totalValue;
    }

    private bool _IsCountNextRefreshTime = false;
    public void InitNextRefreshTime(int time)
    {
        _TotalNextRefreshTime = time;
        if(_TotalNextRefreshTime > 0)
        {
            InitNextRefreshTimeDesc();
            _IsCountNextRefreshTime = true;
        }
    }

    public void InitNextRefreshTimeDesc()
    {
        _NextRefreshTime.text = StrDictionary.GetClientDictionaryString("#{1794}", _TotalNextRefreshTime);
    }

    private bool _IsCountRemainTime = false;
    private int _CopyEndTime = 0;
    private int _MistakeVal = 1;  //两秒容错 客户端提前两秒结束
    public void InitRemainTime(int time)
    {
        _CopyEndTime = time - _MistakeVal;
        _TotalRemainTime = _CopyEndTime - GlobalData.ServerAnsiTime;
        if(_TotalRemainTime > 0)
        {
            InitRemainTimeDesc();
            _IsCountRemainTime = true;
        }else
        {
            _TotalRemainTime = 0;
            _IsCountRemainTime = false;
            InitRemainTimeDesc();
        }
    }

    public void InitRemainTimeDesc()
    {
        _RemainTime.text = StrDictionary.GetClientDictionaryString("#{1794}", _TotalRemainTime);
    }

    public Text _ExitBtnDesc;
    private int _ExitRemainTime = -1;
    private bool _IsCountExitTime = false;
    public void CountExitTime()
    {
        if (_CurFubenId == -1)
        {
            LogModule.ErrorLog("CurFubenId is -1");
            return;
        }

        Tab_Fuben fuben = TableManager.GetFubenByID(_CurFubenId, 0);
        if (fuben == null)
        {
            return;
        }
        _ExitRemainTime = fuben.LeaveDelay;
        if (_ExitRemainTime <= 0)
        {
            _IsCountExitTime = false;
            return;
        }
        _IsCountExitTime = true;
        //SetExitBtnDesc();
    }

    // 控制按钮上的倒计时显示
    // 现在暂时不需要了
    private void SetExitBtnDesc()
    {
        _ExitBtnDesc.text = StrDictionary.GetClientDictionaryString("#{1719}", _ExitRemainTime);
    }

    private float _RemainCountTime = 0.0f;
    private float _NextFreshCountTime = 0.0f;
    private float _ExitCountTime = 0.0f;
    void Update()
    {
        if(_IsCountExitTime)
        {
            if(_ExitRemainTime > 0)
            {
                _ExitCountTime += Time.deltaTime;
                if (_ExitCountTime >= 1.0f)
                {
                    _ExitRemainTime --;
                    _ExitCountTime = 1.0f - _ExitCountTime;
                    //SetExitBtnDesc();
                }
            }else
            {
                if(!_IsCountExitTime)
                {
                    _IsCountExitTime = false;
                    _ExitRemainTime = 0;
                }
            }
        }

        if (_IsCountRemainTime)
        {
            if (_TotalRemainTime > 0)
            {
                _RemainCountTime += Time.deltaTime;
                if (_RemainCountTime >= 1.0f)
                {
                    _RemainCountTime = 1 - _RemainCountTime;
                    _TotalRemainTime = _CopyEndTime - GlobalData.ServerAnsiTime;
                    InitRemainTimeDesc();
                }
            }
            else
            {
                _IsCountRemainTime = false;
                if (_TotalRemainTime != 0)
                {
                    _TotalRemainTime = 0;
                    InitRemainTimeDesc();
                }
            }
        }

        if (_IsCountNextRefreshTime)
        {
            if (_TotalNextRefreshTime > 0)
            {
                _NextFreshCountTime += Time.deltaTime;
                if (_NextFreshCountTime >= 1.0f)
                {
                    _NextFreshCountTime = 1 - _NextFreshCountTime;
                    _TotalNextRefreshTime--;
                    InitNextRefreshTimeDesc();
                }
            }
            else
            {
                _IsCountNextRefreshTime = false;
                if (_TotalNextRefreshTime != 0)
                {
                    _TotalNextRefreshTime = 0;
                    InitRemainTimeDesc();
                }
            }
        }
    }

    private List<GameObject> _RewItemObjList = new List<GameObject>();
    public void CreateRewItem(List<MarketingActAwardItem> _RewList)
    {
        if(_RewList.Count <= 0)
        {
            _RewPanel.SetActive(false);
            return;
        }
        _RewPanel.SetActive(true);

        if(_RewList.Count > _RewItemObjList.Count)
        {
            for(int index = 0; index < _RewItemObjList.Count; index++)
            {
                _RewItemObjList[index].SetActive(true);
                _RewItemObjList[index].GetComponent<CopySceneRewardItem>().InitItem(_RewList[index].awardSubType, _RewList[index].awardNum);
            }
        }else
        {
            for(int index = _RewList.Count; index < _RewItemObjList.Count; index++)
            {
                _RewItemObjList[index].SetActive(false);
            }

            for(int index = 0; index < _RewList.Count; index++)
            {
                _RewItemObjList[index].SetActive(true);
                _RewItemObjList[index].GetComponent<CopySceneRewardItem>().InitItem(_RewList[index].awardSubType, _RewList[index].awardNum);
            }
        }
    }

    public void InitRewPrefab()
    {
        for (int index = 0; index < 4; index++)
        {
            GameObject obj = GameObject.Instantiate(_RewItemPrefab);
            obj.transform.SetParent(_RewParent);
            obj.transform.localPosition = Vector3.zero;
            obj.transform.localRotation = Quaternion.Euler(Vector3.zero);
            obj.transform.localScale = Vector3.one;
            obj.SetActive(false);
            _RewItemObjList.Add(obj);
        }
    }

    // 退出副本回调
    // 由于试炼副本统一使用该脚本,在退出副本处理,会涉及到其他具体副本的UI控制
    public void OnExitBtnClick()
    {
        //if(GameManager.gameManager.PlayerDataPool.IsHaveTeam() && GameManager.gameManager.PlayerDataPool.TeamInfo.TeamID != GlobeVar.INVALID_ID)
        //{
        //    MessageBoxLogic.OpenOKCancelBox(StrDictionary.GetClientDictionaryString("#{51805}"), "",
        //        () => {
        //            if (null != Singleton<ObjManager>.GetInstance().MainPlayer)
        //            {
        //                //Singleton<ObjManager>.GetInstance().MainPlayer.ReqLeaveTeam();
        //                ExitCopyScene();
        //            }
        //        });

        //    return;
        //}

        MessageBoxLogic.OpenOKCancelBox(StrDictionary.GetClientDictionaryString("#{51810}"), "", ExitCopyScene);
    }

    private void ExitCopyScene()
    {
        CG_LEAVE_COPYSCENE send = (CG_LEAVE_COPYSCENE)PacketDistributed.CreatePacket(MessageID.PACKET_CG_LEAVE_COPYSCENE);
        send.NoParam = 1;
        send.SendPacket();

        // 一夫当关副本
        if (TestingCopyBuffInfoCtr.Instance != null)
        {
            UIManager.CloseUI(UIInfo.BuffsStateInfo);
        }

        // 关闭本UI
        UIManager.CloseUI(UIInfo.TestingCopyInfo);
    }

    #region 排行榜数据操作函数

    long GetProValueInt(int proID, RankElemStruct ranklist)
    {
        if (ranklist == null)
            return -1;
        for (int i = 0; i < ranklist.numberfieldsCount; i++)
        {
            RankFieldNumberStruct numberInfo = ranklist.GetNumberfields(i);
            if (proID == numberInfo.Propid)
                return numberInfo.Propvalue;
        }
        return -1;
    }

    string GetProValueStr(int proID, RankElemStruct ranklist)
    {
        if (ranklist == null)
            return "";
        for (int i = 0; i < ranklist.stringfieldsCount; i++)
        {
            RankFieldStringStruct stringInfo = ranklist.GetStringfields(i);
            if (proID == stringInfo.Propid)
                return stringInfo.Propvalue;
        }
        return "";
    }
    #endregion

    #region move
    public ObjectTween _MoveTo;
    public RectTransform _TitleBGRec;
    public GameObject _ShowBtn;
    public GameObject _HideBtn;
    public GameObject _InfoPanel;

    private bool isShow = false;
    public void OnBtnShow()
    {
        ShowPanel();
        _ShowBtn.SetActive(false);
        _HideBtn.SetActive(true);
        isShow = true;
    }

    public void OnBtnHide()
    {
        HidePanel();
        _ShowBtn.SetActive(true);
        _HideBtn.SetActive(false);
        isShow = false;
    }

    public void OnTitleBtn()
    {
        if (isShow)
        {
            OnBtnHide();
        }
        else
        {
            OnBtnShow();
        }
    }

    public void ShowPanel()
    {
        _MoveTo.Reset();
        _MoveTo.destantPos = new Vector3(0, 0, 0);

        GCGame.Utils.HideMainTopRightUI();
        _TitleBGRec.sizeDelta = new Vector2(300, _TitleBGRec.sizeDelta.y);
        _InfoPanel.gameObject.SetActive(true);
    }

    public void HidePanel()
    {
        _MoveTo.Reset();
        _MoveTo.destantPos = new Vector3(0, -192, 0);

        GCGame.Utils.ShowMainTopRightUI();
        _TitleBGRec.sizeDelta = new Vector2(230, _TitleBGRec.sizeDelta.y);
        _InfoPanel.gameObject.SetActive(false);
    }
    #endregion
}