#region HeadComments
/* ========================================================================
* Copyright (C) 2015 ArthunGame
*
* 作    者：Arthun
* 文件名称：GameLayoutInstance
* 功    能：游戏布局管理器
* 创建时间：2016/01/30 12:18:25
* 
* =========================================================================
*/
#endregion

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameLayoutInstance : MonoBehaviour
{
    public static GameLayoutInstance _instance;
    public static GameLayoutInstance GetInstance()
    {
        return _instance;
    }

    public Transform _AltarObj;//祭坛
    public Transform _door1;//门1
    public Transform _door2;//门2

    public AudioClip _backGround01;
    public AudioClip _backGround02;


    private int _createRoleCount = 0;//已创建的人物数量
    private Dictionary<int, RoleController> _roleMap = new Dictionary<int, RoleController>();

    private RoleController _Player;

    public List<Vector3> _LastEffectivePos = new List<Vector3>();
    public List<Vector3> _RoleRecordPosList = new List<Vector3>();
    public List<Vector3> _CameraRecordPosList = new List<Vector3>();
    public List<float> _delayTime = new List<float>();

    private Transform _SoulEffect;//灵魂特效
    private bool _IsPlayback = false;//是否回放
    private int _PlaybackIndex = 0;
    private float _temTime = 0f;

    private Vector3 _SoulStartPos = Vector3.zero;
    private Vector3 _SoulStartPos1 = Vector3.zero;
    private float _MinNum = 0f;

    void Awake()
    {
        _instance = this;
    }

    void Start()
    {
        Vector3 StartPos = Vector3.zero;
        var go = GameObject.Find("StartPos");
        if (go == null)
        {
            Debug.LogError("startPos == null");
        }
        else
        {
            StartPos = go.transform.position;
        }

        _Player = createRole(RoleType.PLAYER, StartPos);

        //for (int i = 0; i < 1; i++)
        //{
        //    _createRoleCount++;
        //    createRole(RoleType.FOLLOWPLAYER, _createRoleCount, StartPos);
        //}
    }

    void LateUpdate()
    {
        if(_IsPlayback)
        {
            _SoulStartPos1.y += Time.deltaTime * 10f;
            _SoulEffect.position = _SoulStartPos1;

            if (Vector3.Distance(_SoulEffect.position, _SoulStartPos) > 25f)
            {
                _temTime += Time.deltaTime;
                if (_delayTime.Count - 1 > _PlaybackIndex)
                {
                    if (_temTime < _delayTime[_delayTime.Count - 1 - _PlaybackIndex])
                        return;
                    _temTime = 0f;
                }

                if (_RoleRecordPosList.Count - 1 > _PlaybackIndex && _CameraRecordPosList.Count - 1 > _PlaybackIndex)
                {
                    CameraController.GetInstance().transform.position = _CameraRecordPosList[_CameraRecordPosList.Count - 1 - _PlaybackIndex];
                    //_SoulEffect.position = _RoleRecordPosList[_RoleRecordPosList.Count - 1 - _PlaybackIndex];
                    _PlaybackIndex++;
                }
                else
                {
                    _PlaybackIndex = 0;
                    _RoleRecordPosList.Clear();
                    _CameraRecordPosList.Clear();
                    _IsPlayback = false;

                    Destroy(_SoulEffect.gameObject);

                    _Player._IsControll = false;
                    CameraController.GetInstance()._Target = _Player.transform;
                    CameraController.GetInstance()._isLookTarget = false;
                    _Player.SetRoleAni(RoleAniState.WARSHOP);
                }

                //_SoulStartPos1 = Vector3.zero;
                //_SoulStartPos = Vector3.zero;
                //_IsPlayback = false;
            }

            //_temTime += Time.deltaTime;
            //if (_delayTime.Count - 1 > _PlaybackIndex)
            //{
            //    if (_temTime < _delayTime[_delayTime.Count - 1 - _PlaybackIndex])
            //        return;
            //    _temTime = 0f;
            //}

            //if (_RoleRecordPosList.Count - 1 > _PlaybackIndex && _CameraRecordPosList.Count - 1 > _PlaybackIndex)
            //{
            //    CameraController.GetInstance().transform.position = _CameraRecordPosList[_CameraRecordPosList.Count - 1 - _PlaybackIndex];
            //    _SoulEffect.position = _RoleRecordPosList[_RoleRecordPosList.Count - 1 - _PlaybackIndex];
            //    _PlaybackIndex++;
            //}
            //else
            //{
            //    _PlaybackIndex = 0;
            //    _RoleRecordPosList.Clear();
            //    _CameraRecordPosList.Clear();
            //    _IsPlayback = false;

            //    Destroy(_SoulEffect.gameObject);

            //    _Player._IsControll = true;
            //    CameraController.GetInstance()._Target = _Player.transform;
            //    CameraController.GetInstance()._isLookTarget = false;
            //}
        }
    }

    public void CreateNewRole(Vector3 pos)
    {
        var role = createRole(RoleType.PLAYER, pos);
        role._IsControll = false;
    }

    /// <summary>
    /// 创建角色
    /// </summary>
    /// <param name="type">类型</param>
    /// <param name="roleID">ID 保证每次创建出来的ID不重复</param>
    /// <returns></returns>
    RoleController createRole(RoleType type, Vector3 pos)
    {
        _createRoleCount++;
        GameObject go = (GameObject)Instantiate(Resources.Load("Roles/Role"), pos, Quaternion.identity);
        go.transform.name = string.Format("Name:{0} Index:{1}", "Role ", _createRoleCount);

        var role = go.GetComponent<RoleController>();

        role.InitialRole(type, _createRoleCount);
        role._OnDeathCallback += OnDeathCallback;
        if (type == RoleType.FOLLOWPLAYER)
        {
            role._FollowTarget = _Player;
        }

        _roleMap[role._roleID] = role;
        return role;
    }

    /// <summary>
    /// 死亡回调
    /// </summary>
    /// <param name="role"></param>
    void OnDeathCallback(RoleController role)
    {
        if (_roleMap.ContainsKey(role._roleID))
            _roleMap.Remove(role._roleID);

        StartCoroutine(ssssss(role.transform.position));
    }

    IEnumerator ssssss(Vector3 pos)
    {
        yield return new WaitForSeconds(1.5f);

        Vector3 lastEffectivePos = Vector3.zero;
        float dis = float.MaxValue;
        for (int i = 0; i < _LastEffectivePos.Count; i++)
        {
            float posDis = Vector3.Distance(pos, _LastEffectivePos[i]);
            if (posDis < dis && posDis > 6f)
                lastEffectivePos = _LastEffectivePos[i];
        }

        if (lastEffectivePos == Vector3.zero)
            lastEffectivePos = _LastEffectivePos[_LastEffectivePos.Count - 1];

        _Player = createRole(RoleType.PLAYER, lastEffectivePos);
        var go = (GameObject)Instantiate(Resources.Load("Prefab/Effects/Soul"));
        go.transform.position = pos;
        _SoulStartPos = pos;
        _SoulStartPos1 = _SoulStartPos;
        _SoulEffect = go.transform;
        CameraController.GetInstance()._Target = go.transform;
        _IsPlayback = true;
        _PlaybackIndex = 0;
        //_LastEffectivePos.Clear();
    }

    public void SetBackGroundMusic2()
    {
        AudioSource audio = this.transform.GetComponent<AudioSource>();
        audio.clip = _backGround02;
        audio.Play();
    }

}
