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

public class CarView : MonoBehaviour
{
    public Transform m_targetParentTrans;//障碍物父节点
    private float m_maxSpeed = 100.0f;//最大速度
    private float m_addSpeed = 9.5f;//加速度
    private float m_curSpeed = 0.0f;//当前速度
    private bool m_bControlMouseUp = false;//松手减速
    private bool m_bIsCanMove = false;//是否能开车
    private BoxCollider[] m_targetTrans;//所有目标
    private BoxCollider m_curTargetTrans;//当前抓的目标
    private Vector3 m_offset;//偏移值
    private int m_totalNum = 0;//货物总数量
    private Vector3 m_targetScreenVec;//当前物体对应的屏幕坐标
    private bool m_bTrunX = false;//是否转弯
    private bool m_bTrunXOver = false;//是否转弯结束
    private Rigidbody m_rigidBody;//自身刚体
    private Dictionary<BoxCollider, bool> m_dicBox = new Dictionary<BoxCollider, bool>();
   
    // Start is called before the first frame update
    void Start()
    {
        m_targetTrans = m_targetParentTrans.GetComponentsInChildren<BoxCollider>();
        for(int i = 0;i<m_targetTrans.Length;i++)
        {
            m_dicBox.Add(m_targetTrans[i], false);
        }
        m_rigidBody = GetComponent<Rigidbody>();
    }
    private void OnCollisionEnter(Collision other)
    {
        if (other.collider.gameObject.CompareTag("Target"))
        {
            BoxCollider varBox = other.collider.gameObject.GetComponent<BoxCollider>();
            if (m_dicBox.ContainsKey(varBox))
            {
                m_dicBox[varBox] = true;
            }
        }
    }
    private void OnCollisionExit(Collision other)
    {
        if (other.collider.gameObject.CompareTag("Target"))
        {
            BoxCollider varBox = other.collider.gameObject.GetComponent<BoxCollider>();
            if (m_dicBox.ContainsKey(varBox))
            {
                m_dicBox[varBox] = false;
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (!BattleCtrl.instance.isStartBattle || BattleCtrl.instance.isEndBattle)
        {
            return;
        }
        if (Input.GetMouseButtonDown(0))
        {
            Clicked();
        }
        if (Input.GetMouseButton(0))
        {
            m_bControlMouseUp = false;
            if (m_bIsCanMove)
            {
                if (m_curSpeed < m_maxSpeed)
                {
                    m_curSpeed += Time.deltaTime * m_addSpeed;
                }
                if(m_bTrunXOver)
                {
                    m_rigidBody.velocity = -Vector3.right * m_curSpeed;
                }
                else
                {
                    m_rigidBody.velocity = -Vector3.forward * m_curSpeed;
                }
                //transform.Translate(-Vector3.forward * m_curSpeed, Space.Self);
            }
            if(m_curTargetTrans && !m_bIsCanMove)
            {
                m_curTargetTrans.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                Input.mousePosition.y, m_targetScreenVec.z)) + m_offset;
            }
            if(!m_bIsCanMove && m_curTargetTrans) 
            {
                //十字架位置
                float varX = (Input.mousePosition.x - Screen.width / 2f) / (Screen.width / GlobalConfig.NormalWidth);
                float varY = (Input.mousePosition.y - Screen.height / 2f) / (Screen.width / GlobalConfig.NormalWidth);
                BattleCtrl.instance.battleUI.SetSymbolPos(varX, varY);
            }
        }
        else if (Input.GetMouseButtonUp(0))
        {
            m_bControlMouseUp = true;
            m_curTargetTrans = null;
            BattleCtrl.instance.battleUI.SetSymbolPos(0, 0);
            int varIndex = 0;
            GameServices.timerServices.Push(this, 1.5f, delegate
            {
                if(!m_bIsCanMove)
                {
                    if (m_targetTrans != null)
                    {
                        for (int i = 0; i < m_targetTrans.Length; i++)
                        {
                            if (m_targetTrans[i].transform.position.y >= 2.5f)
                            {
                                varIndex++;
                            }
                        }
                    }
                    if (varIndex >= 3)
                    {
                        m_bIsCanMove = true;
                        for (int i = 0; i < m_targetTrans.Length; i++)
                        {
                            Rigidbody varBody = m_targetTrans[i].GetComponent<Rigidbody>();
                            if (varBody)
                            {
                                varBody.constraints = RigidbodyConstraints.FreezeRotationY;
                            }
                        }
                    }
                }
            });
        }
        if(m_bControlMouseUp)
        {
            if (m_bIsCanMove)
            {
                if (m_curSpeed > 0)
                {
                    m_curSpeed -= Time.deltaTime * m_addSpeed;
                }
                else
                {
                    m_bControlMouseUp = false;
                }
                if (m_bTrunXOver)
                {
                    m_rigidBody.velocity = -Vector3.right * m_curSpeed;
                }
                else
                {
                    m_rigidBody.velocity = -Vector3.forward * m_curSpeed;
                }
                //transform.Translate(-Vector3.forward * m_curSpeed, Space.Self);
            }
        }
        //确保最低位置
        if(m_curTargetTrans)
        {
            Vector3 varPos = m_curTargetTrans.transform.position;
            if (varPos.y < 0.5f)
            {
                varPos.y = 0.5f;
            }
            if(m_dicBox.ContainsKey(m_curTargetTrans) && m_dicBox[m_curTargetTrans])
            {
                varPos.y = 3.0f;
            }
            m_curTargetTrans.transform.position = varPos;
        }
        transform.localRotation = Quaternion.Euler(0, transform.localEulerAngles.y, 0);
        UpdateTurn();
    }
    //返回剩余物体个数
    public int GetLeftBoxNum()
    {
        int varIndex = 0;
        if (m_targetTrans != null)
        {
            for (int i = 0; i < m_targetTrans.Length; i++)
            {
                if (m_targetTrans[i].transform.position.y >= 2.5f)
                {
                    varIndex++;
                }
            }
        }
        return varIndex;
    }
    void Clicked()
    {
        if(m_bIsCanMove)
        {
            return;
        }
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit hit = new RaycastHit();

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider && hit.collider.gameObject.CompareTag("Target"))
            {
                for(int i = 0;i<m_targetTrans.Length;i++)
                {
                    if(string.Equals(hit.collider.name,m_targetTrans[i].name))
                    {
                        m_curTargetTrans = m_targetTrans[i];
                        break;
                    }
                }
                m_targetScreenVec = Camera.main.WorldToScreenPoint(m_curTargetTrans.transform.position);
                //偏移值=物体的世界坐标，减去转化之后的鼠标世界坐标（z轴的值为物体屏幕坐标的z值）
                m_offset = m_curTargetTrans.transform.position - Camera.main.ScreenToWorldPoint(new Vector3
                (Input.mousePosition.x, Input.mousePosition.y, m_targetScreenVec.z));
            }
        }
    }
    //开始拐弯
    public void SetTurn()
    {
        m_bTrunX = true;
    }
    void UpdateTurn()
    {
        if(m_bTrunX)
        {
            m_rigidBody.angularVelocity = Vector3.up*m_curSpeed/2;
            Vector3 varVec3 = m_rigidBody.velocity;
            varVec3.x = -Vector3.right.x*m_curSpeed/2;
            varVec3.z = -Vector3.forward.z*m_curSpeed;
            m_rigidBody.velocity = varVec3;
            if (transform.localEulerAngles.y >= 90.0f && transform.localEulerAngles.y <= 180.0f)
            {
                m_bTrunX = false;
                m_bTrunXOver = true;
                m_rigidBody.angularVelocity = Vector3.zero;
                transform.localEulerAngles = Vector3.up * 90.0f;
                m_rigidBody.velocity = Vector3.zero;
            }
        }
    }
    private void OnDestroy()
    {
        m_targetTrans = null;
        m_curTargetTrans = null;
    }
}
