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

public class TestingCopyBase : MonoBehaviour {

    public int _FubenId;                                // 副本ID/场景ID
    public GameObject _SingleChallengeBtn;              // 单人挑战按钮
    public GameObject _TeamChallengeBtn;                // 团队挑战按钮
    public GameObject _SweepBtn;                        // 一键扫荡按钮

    public Text _RuleText;                              // 规则描述
    public UIImgText _BestPassedLevel;                  // 最高通关层数
    public GameObject _RemainTimeObj;                   // 剩余挑战显示
    public UIImgText _RemainChallengeTimesText;         // 剩余挑战次数(数字)
    public GameObject _MaxPerfectLevelObj;              // 最高完美通关次数
    public UIImgText _MaxPerfectLevel;                  // 最高完美通关次数(数字)


    public UIContainerBase _RewContainer;               // 奖品列表
    
    public UICameraTexture _ModelCamera;                // 相机渲染贴图
    public List<GameObject> _DiffcultyBtnList;          // 难度按钮

    protected int _RemainChallengeTimes;                  // 剩余挑战次数
    protected int _CurSelectedDiffcultyType = (int)TestingCopyDiffcultyType.Simple; //默认解锁难度

    public enum TestingCopyDiffcultyType
    {
        Simple = 0,
        Normal = 1,
        Hard = 2,
        Hell = 3,
    }

    private enum ChallengeType
    {
        Single = 0,
        Team,
        Sweep,
    }   

    private void Awake()
    {
        if(getOnceRewardBtn != null)
        {
            getOnceRewardBtn.onClick.AddListener(OnOnceAwardBtnClick);
            getBtnImg = getOnceRewardBtn.GetComponent<Image>();
        }

        _TestingCopyTab = TableManager.GetTestingCopyByID(_FubenId, 0);
        if (_TestingCopyTab == null)
        {
            LogModule.ErrorLog("Can't find id in testingCopy, id is : " + _FubenId);
            return;
        }
    }

    public void OnEnable()
    {
        AskForInfo();
        SetChallengeBtn();
    }

    private void Start()
    {
        InitTestingCopyBaseInfoById();
    }

    protected Tab_TestingCopy _TestingCopyTab = null;
    public virtual void InitTestingCopyBaseInfoById()
    {
        _CurSelectedDiffcultyType = (int)TestingCopyDiffcultyType.Simple;

        SetRule();
        HideAllDiffcultyBtn();
        InitRewContainer();
        SetChallengeBtn();
    }

    protected List<TestingRewardItemInfo> rewItemList;
    public virtual void InitRewContainer()
    {
        Tab_CopySceneReward copySceneRew = TableManager.GetCopySceneRewardByID(_TestingCopyTab.RewardId, 0);
        if(copySceneRew == null)
        {
            return;
        }

        rewItemList = new List<TestingRewardItemInfo>();
        for (int index = 0; index < copySceneRew.getRewardCountCount(); index++)
        {
            rewItemList.Add(new TestingRewardItemInfo(copySceneRew.GetRewardItemIDbyIndex(index), copySceneRew.GetRewardCountbyIndex(index)));
        }
        _RewContainer.InitContentItem(rewItemList);
    }

    public void SetChallengeBtn()
    {
        _SingleChallengeBtn.SetActive(_TestingCopyTab.CanSingleChallenge == 1);
        _TeamChallengeBtn.SetActive(_TestingCopyTab.CanTeamChallenge == 1);

        Tab_NewCopyBase newCopybase = TableManager.GetNewCopyBaseByID(_FubenId, 0);
        if(newCopybase != null)
        {
            _SweepBtn.SetActive(false);
            for (int index = 0; index < newCopybase.getFastSweepConditionCount(); index++)
            {
                if(!newCopybase.GetFastSweepConditionbyIndex(index).Equals("-1"))
                {
                    _SweepBtn.SetActive(true);
                    ShowSweepLimit();
                }
            }
        }
    }

    public void HideAllDiffcultyBtn()
    {
        for(int index = 0;  index < _DiffcultyBtnList.Count; index++)
        {
            if(_DiffcultyBtnList[index].activeInHierarchy)
                _DiffcultyBtnList[index].SetActive(false);
        }
    }

    public void SetRule()
    {
        if (_RuleText != null)
        {
            _RuleText.text = _TestingCopyTab.TestingRule;
        }
    }

    #region 消息请求和接受

    public void AskForInfo()
    {
        ReqTestingCopyInfo req = new ReqTestingCopyInfo();
        req._FubenId = _FubenId;
        req.SendMsg();
    }

    #endregion

    #region 进入副本条件判断

    // 是否等级
    private bool IsLevelEnough()
    {
        if (GameManager.gameManager.PlayerDataPool.MainPlayerBaseAttr.Level < _TestingCopyTab.UnlockLevel)
        {
            GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{7245}"));
            return false;
        }
        return true;
    }

    // 是否处于不可退出的场景
    private bool IsInSpecialScene()
    {
        Tab_SceneClass sceneClass = TableManager.GetSceneClassByID(GameManager.gameManager.RunningScene, 0);
        if (sceneClass == null)
        {
            return true;
        }

        if (sceneClass.CanEnterSpecialActivity != 1)
        {
            GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{51001}"));
            return true;
        }
        return false;
    }

    // 是否在执行不可退出的任务
    private bool IsDoingSpecialMission()
    {
        foreach (var mission in GameManager.gameManager.MissionManager.MissionList.m_aMission)
        {
            Tab_MissionBase missionBase = TableManager.GetMissionBaseByID(mission.Value.m_nMissionID, 0);
            if (missionBase != null)
            {
                if (missionBase.MissionType == (int)Games.Mission.MISSIONTYPE.MISSION_GUILDPAOSHANG)
                {
                    GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{51002}"));
                    return true;
                }
            }
        }

        return false;
    }

    #endregion


    // 是否剩余挑战次数充足
    private bool IsHaveChallengeTimes()
    {
        if(_RemainChallengeTimes == 0)
        {
            GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{51000}"));
            return false;
        }
        return true;
    }

    public void OnSingleBtnClcik()
    {
        _ChallengeType = (int)ChallengeType.Single;
        if (!IsLevelEnough())
        {
            return;
        }

        if(!IsHaveChallengeTimes())
        {
            return;
        }

        if (!GameManager.gameManager.PlayerDataPool.IsHaveTeam())
        {
            if (IsInSpecialScene() || IsDoingSpecialMission())
            {
                return;
            }else
            {
                ReqEnterCopy();
            }
        }
        else
        {
            if (IsInSpecialScene() || IsDoingSpecialMission())
            {
                return;
            }
            else
            {
                ////脱离队伍
                //MessageBoxLogic.OpenOKCancelBox(StrDictionary.GetClientDictionaryString("#{51800}"), "", delegate () {
                //    ReqEnterCopy();
                //}, delegate () {
                //    UIManager.CloseUI(UIInfo.MessageBox);
                //});

                // 现改为不需要请求脱离队伍
                ReqEnterCopy();
            }
        }
    }

    private int _ChallengeType;
    public void ReqEnterCopy()
    {
        CG_REQ_ENTER_COPY req = (CG_REQ_ENTER_COPY)PacketDistributed.CreatePacket(MessageID.PACKET_CG_REQ_ENTER_COPY);
        req.SetCopyid(_FubenId);
        req.SetDeffcultyType(_CurSelectedDiffcultyType);
        req.SetChallengeType(_ChallengeType);
        req.SendPacket();

        if(_ChallengeType != (int)ChallengeType.Sweep)
            UIManager.CloseUI(UIInfo.CopyScenePanelCtr);
    }

    public void OnTeamBtnClick()
    {
        _ChallengeType = (int)ChallengeType.Team;
        if (IsInSpecialScene() || !IsLevelEnough() || IsDoingSpecialMission() || !IsHaveChallengeTimes())
        {
            return;
        }

        //没有组队
        if (!GameManager.gameManager.PlayerDataPool.IsHaveTeam())
        {
            MessageBoxLogic.OpenOKCancelBox(StrDictionary.GetClientDictionaryString("#{51801}"), "", delegate () {
                if (false == GameManager.gameManager.PlayerDataPool.IsHaveTeam() &&
                        null != Singleton<ObjManager>.GetInstance().MainPlayer)
                {
                    UIManager.CloseUI(UIInfo.MessageBox);
                    UIManager.ShowUI(UIInfo.TeamCreateRoot, delegate (bool bSuccess, object param)
                    {
                        if (bSuccess)
                        {
                            Hashtable hash = new Hashtable();
                            hash["index"] = _TestingCopyTab.TargetId;
                            Games.Events.EventDispatcher.Instance.SendMessage(Games.Events.EventId.SELECTTEAMCREATEWNDITEM, hash);
                        }
                    });
                }
            }, delegate () {
                UIManager.CloseUI(UIInfo.MessageBox);
            });
            return;
        }

        //不是队长
        if (!GameManager.gameManager.PlayerDataPool.TeamInfo.IsCaptain())
        {
            GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{5795}"));
            return;
        }

        //人数不足
        if(GameManager.gameManager.PlayerDataPool.TeamInfo.GetTeamMemberCount() < _TestingCopyTab.TeamChellangeNeedMembers)
        {
            GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{51004}", _TestingCopyTab.TeamChellangeNeedMembers));
            return;
        }

        ReqEnterCopy();
    }

    private bool CanSweep()
    {
        Tab_NewCopyBase newCopyBase = TableManager.GetNewCopyBaseByID(_FubenId, 0);
        if (newCopyBase == null)
        {
            LogModule.ErrorLog("newCopyBase is null, id : " + _FubenId);
            return false;
        }

        if(!IsHaveChallengeTimes())
        {
            return false;
        }

        for(int index = 0; index < newCopyBase.getFastSweepPramCount(); index++)
        {
            if(!newCopyBase.GetFastSweepConditionbyIndex(index).Equals("-1"))
            {
                switch(newCopyBase.GetFastSweepConditionbyIndex(index))
                {
                    case 1:
                        {
                            if(GameManager.gameManager.PlayerDataPool.MainPlayerBaseAttr.Level < newCopyBase.GetFastSweepPrambyIndex(index))
                            {
                                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{48105}", newCopyBase.GetFastSweepPrambyIndex(index)));
                                return false;
                            }
                        }
                        break;
                    case 2:
                        {
                            if(GameManager.gameManager.PlayerDataPool.VipCost< newCopyBase.GetFastSweepPrambyIndex(index))
                            {
                                var param = newCopyBase.GetFastSweepPrambyIndex(index);
                                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{44077}", param));
                                //switch (param)
                                //{
                                //    case 1:
                                //        GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{48110}"));
                                //        break;
                                //    case 2:
                                //        GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{48111}"));
                                //        break;
                                //    case 3:
                                //        GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{48112}"));
                                //        break;
                                //}
                                return false;
                            }
                        }
                        break;
                    case 3:
                        {
                            if (GameManager.gameManager.PlayerDataPool.MonthlyCardDayRemain <= 0)
                            {
                                GUIData.AddNotifyData("44057");
                                return false;
                            }
                        }
                        break;
                    case 4:
                        {
                            if (GlobalData.OpenServerDays < newCopyBase.GetFastSweepPrambyIndex(index))
                            {
                                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{48107}", GlobalData.OpenServerDays - newCopyBase.GetFastSweepPrambyIndex(index)));
                                return false;
                            }
                        }
                        break;
                    case 5:
                        {
                            if(GlobalData.CreateRoleDays < newCopyBase.GetFastSweepPrambyIndex(index))
                            {
                                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{48107}", GlobalData.OpenServerDays - newCopyBase.GetFastSweepPrambyIndex(index)));
                                return false;
                            }
                        }
                        break;
                }
            }
        }
        return true;
    }

    public void OnSweepBtnClick()
    {
        _ChallengeType = (int)ChallengeType.Sweep;

        if(!IsLevelEnough())
        {
            return;
        }

        if(!IsHaveChallengeTimes())
        {
            return;
        }

        if(CanSweep())
        {
            ReqEnterCopy();
        }
    }

    public List<GameObject> _DiffcultyMarkIcon;


    public void ShowCurDiffcultyTypeBestpassedLevel()
    {
        if (_BestPassedLevel != null)
        {
            _BestPassedLevel.text = _PacketBestassedLevelList[_CurSelectedDiffcultyType];
        }
    }

    //设置波数 剩余次数 解锁难度
    protected List<string> _PacketBestassedLevelList;
    protected List<int> _MaxPerfectPassedLevelList = new List<int>();
    public virtual void OnPacketRet(RetTestingCopyInfo packet)
    {
        _PacketBestassedLevelList = new List<string>();
        for (int index = 0; index < packet._BestPassedLevelList.Count; index++)
        {
            _PacketBestassedLevelList.Add(packet._BestPassedLevelList[index]);
        }

        _MaxPerfectPassedLevelList = packet._MaxPerfectLevelList;

        ShowDiffcultyBtns(packet._UnLockDiffcultyLevel);
        SetRemainChallengeTimes(packet._RemainTimes);

        if (packet._Reward != null)
        {
            onceRewards = packet._Reward;
        }

        OnDiffcultyBtnClick(_CurSelectedDiffcultyType);
    }

    public void SetBestPassedLevel(int bestPassedLevel)
    {
        if (_BestPassedLevel != null)
        {
            _BestPassedLevel.text = bestPassedLevel.ToString();
        }
    }

    public void SetRemainChallengeTimes(int _Times)
    {
        _RemainChallengeTimes = _Times;
        if (_Times == -1)
        {
            _RemainTimeObj.SetActive(false);
        }
        else
        {
            _RemainTimeObj.SetActive(true);
            if (_RemainChallengeTimesText != null)
            {
                _RemainChallengeTimesText.text = _Times.ToString();
            }
        }

    }

    private int _CurUnLockDiffcultyLevel = 0;  //-1默认不显示
    public void ShowDiffcultyBtns(int _Diffculty)
    {
        _CurUnLockDiffcultyLevel = _Diffculty;

        if(_Diffculty == -1 || _Diffculty == 0)
        {
            HideAllDiffcultyBtn();
        }
        else
        {
            for (int index = 0; index < _DiffcultyBtnList.Count; index++)
            {
                _DiffcultyBtnList[index].SetActive(index <= _Diffculty);
            }
        }
    }

    public void OnRankBtnClick()
    {
        UIManager.ShowUI(UIInfo.TestingRankPanel, delegate(bool bSucess, object param) {
            if(bSucess)
            {
                TestingRankPanelCtr.Instance.SetFuBtnId(_FubenId, _CurSelectedDiffcultyType);
            }
        });
    }

    #region 左下角里程碑奖励

    private List<CopyOnceReward> onceRewards;
    //public TestingRewardItem onceRewardItem;
    public Text onceRewardsDesc;
    public Button getOnceRewardBtn;
    private bool canGet = false;
    public Color disableColor;
    public Color enableColor;
    public GameObject onceRewardPanel;
    public Transform _EffectPoint;              // 特效挂载点
    private Image getBtnImg;

    // 显示当前难度的一次性奖励:dif 难度
    private void ShowOnceAward(int dif)
    {
        if (onceRewards != null && dif < onceRewards.Count)
        {
            onceRewardPanel.SetActive(true);
            onceRewardsDesc.text = StrDictionary.GetClientDictionaryString("#{6735}", onceRewards[dif]._Layer);

            getBtnImg.color = disableColor;
            _EffectPoint.gameObject.SetActive(false);
            canGet = false;
            if (onceRewards[dif]._RewardState == 1)
            {
                getBtnImg.color = enableColor;
                canGet = true;
                _EffectPoint.gameObject.SetActive(true);
            }
        }
        else
        {
            onceRewardPanel.SetActive(false);
        }
    }

    public void OnDiffcultyBtnClick(int _Index)
    {
        _CurSelectedDiffcultyType = _Index;
        for (int index = 0; index < _DiffcultyBtnList.Count; index++)
        {
            _DiffcultyMarkIcon[index].SetActive(index == _Index);
        }
        ShowCurDiffcultyTypeBestpassedLevel();

        ShowOnceAward(_CurSelectedDiffcultyType);
        OnShowMaxPerfectPassLevle();
    }

    public void OnShowMaxPerfectPassLevle()
    {
        if(_MaxPerfectLevel != null && _MaxPerfectLevelObj != null)
        {
            if (_MaxPerfectPassedLevelList.Count > _CurSelectedDiffcultyType)
            {
                _MaxPerfectLevelObj.SetActive(true);
                _MaxPerfectLevel.text = _MaxPerfectPassedLevelList[_CurSelectedDiffcultyType].ToString();
            }
            else
            {
                _MaxPerfectLevelObj.SetActive(false);
            }
        }
        else if (_MaxPerfectLevelObj != null)
        {
            _MaxPerfectLevelObj.SetActive(false);
        }
    }

    public void OnOnceAwardBtnClick()
    {
        if (onceRewards == null)
        {
            return;
        }

        if (canGet == true)
        {
            ReqGetCopyOnceReward req = new ReqGetCopyOnceReward();
            req._FubenId = this._FubenId;
            req._Difficult = _CurSelectedDiffcultyType;
            req._NodeId = onceRewards[_CurSelectedDiffcultyType]._NodeId;
            req.SendMsg();
        }
        else
        {
            CopyOnceReward awardItem = onceRewards[_CurSelectedDiffcultyType];
            UIManager.ShowUI(UIInfo.TestingCopyOnceAwardTip, 
                (bool isSuccess, object param) =>
                {
                    CopyOnceReward award = param as CopyOnceReward;
                    if (isSuccess == true)
                    {
                        TestingCopyOnceAwardTipCtr.Instance.Show(award._NodeId, award, getOnceRewardBtn.transform.position);
                    }
                },
                awardItem);
        }
    }

    #endregion

    #region 扫荡按钮下描述控制

    public Image fastMoneyImg;
    public Text _OneKeySweepConditionDesc;

    public void ShowSweepLimit()
    {
        //快速
        Tab_NewCopyBase newCopyBase = TableManager.GetNewCopyBaseByID(_FubenId, 0);
        if (newCopyBase == null)
        {
            LogModule.ErrorLog("ERROR, NewCopyBase id is : " + _FubenId);
            return;
        }

        var fastConditionDesc = "";
        var isFastConditionPassed = true;
        for (int index = 0; index < newCopyBase.getFastSweepConditionCount(); index++)
        {
            if (newCopyBase.GetFastSweepConditionbyIndex(index) != -1)
            {
                var param = newCopyBase.GetFastSweepPrambyIndex(index);
                switch (newCopyBase.GetFastSweepConditionbyIndex(index))
                {
                    case 1:
                        {
                            if (GameManager.gameManager.PlayerDataPool.MainPlayerBaseAttr.Level < param)
                            {
                                isFastConditionPassed = false;
                                fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44070}", param);
                                continue;
                            }
                        }
                        break;
                    case 2:
                        {
                            if (GameManager.gameManager.PlayerDataPool.VipCost < param)
                            {
                                isFastConditionPassed = false;
                                GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{44077}", param));
                                //switch (param)
                                //{
                                //    case 1:
                                //        fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44062}");
                                //        break;
                                //    case 2:
                                //        fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44063}");
                                //        break;
                                //    case 3:
                                //        fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44063}");
                                //        break;
                                //}
                                continue;
                            }
                        }
                        break;
                    case 3:
                        {
                            if (GameManager.gameManager.PlayerDataPool.MonthlyCardDayRemain <= 0)
                            {
                                isFastConditionPassed = false;
                                fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44061}");
                                continue;
                            }
                        }
                        break;
                    case 4:
                        {
                            if (GlobalData.OpenServerDays < param)
                            {
                                isFastConditionPassed = false;
                                fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44065}", param);
                                continue;
                            }
                        }
                        break;
                    case 5:
                        {
                            if (GlobalData.CreateRoleDays < param)
                            {
                                isFastConditionPassed = false;
                                fastConditionDesc += StrDictionary.GetClientDictionaryString("#{44066}", param);
                                continue;
                            }
                        }
                        break;
                }
            }
        }

        if (isFastConditionPassed && newCopyBase.FastSweepConsumeType != -1)
        {
            fastMoneyImg.gameObject.SetActive(true);
            _OneKeySweepConditionDesc.gameObject.SetActive(false);
            LoadAssetBundle.Instance.SetImageSprite(fastMoneyImg, UICurrencyItem.GetCurrencySprite((MONEYTYPE)newCopyBase.FastSweepConsumeSubType), delegate (bool isSucess, GameObject obj)
            {
                fastMoneyImg.SetNativeSize();
            });
            _OneKeySweepConditionDesc.text = newCopyBase.FastSweepConsumeNum.ToString();
        }
        else
        {
            fastMoneyImg.gameObject.SetActive(false);
            _OneKeySweepConditionDesc.gameObject.SetActive(true);
            _OneKeySweepConditionDesc.text = fastConditionDesc;
        }
    }

    public void OnScoreBtn()
    {
        YuanBaoShopLogic.OpenShopForJiFenItem(11, -1);
    }
    #endregion
}