using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class PostureController : MonoBehaviour
{
    public List<EquipmentCommon> redObjs = new List<EquipmentCommon>();
    public List<EquipmentCommon> blueObjs = new List<EquipmentCommon>();
    private DeviceManager deviceManager;
    public Transform redContanier;
    public Transform blueContanier;
    public DeviceBtnItem deviceBtnItem;
    public RawImage redShowImage;
    public RawImage blueShowImage;
    private DroneViewDisplay droneViewDisplay;

    public Button upBtn;
    public Button downBtn;
    public float distance;
    public bool isScale = false;
    /// <summary>
    /// 卫星影像
    /// </summary>
    public Camera satelliteImagery;

    public Coroutine currentCoroutine;
    public RectTransform rect;

    // Start is called before the first frame update
    void Awake()
    {
        deviceManager = DeviceManager.Instance;
        droneViewDisplay = DroneViewDisplay.Instance;
        upBtn.onClick.AddListener(OnUp);
        downBtn.onClick.AddListener(OnDown);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (RectTransformUtility.RectangleContainsScreenPoint(rect, Input.mousePosition))
            {
                float mouseX = Input.GetAxis("Mouse X") * 10f * Time.deltaTime;
                float mouseY = Input.GetAxis("Mouse Y") * 10f * Time.deltaTime;
                satelliteImagery.transform.Translate(Vector3.down * mouseY * 60f);
                satelliteImagery.transform.Translate(Vector3.left * mouseX * 60f);
            }
        }
    }

    private void OnUp()
    {
        distance = satelliteImagery.orthographicSize;
        distance += 100;
        if (distance >= 1120)
        {
            distance = 1120;
            //currentCoroutine = null;
            return;
        }
        satelliteImagery.orthographicSize = distance;
        //if (currentCoroutine == null)
        //{
        //    isScale = true;
        //    currentCoroutine = StartCoroutine(Merge(distance));
        //}
    }

    private void OnDown()
    {
        distance = satelliteImagery.orthographicSize;
        distance -= 100;
        if (distance <= 200f)
        {
            distance = 200f;
            //currentCoroutine = null;
            return;
        }
        satelliteImagery.orthographicSize = distance;
        //if (currentCoroutine == null)
        //{
        //    isScale = true;
        //    currentCoroutine = StartCoroutine(Merge(distance));
        //}
    }

    private IEnumerator Merge(float targetPoint)
    {
        while (isScale)
        {
            Debug.Log("update");
            satelliteImagery.orthographicSize = Mathf.Lerp(satelliteImagery.orthographicSize, targetPoint, Time.deltaTime * 20f);
            if (Mathf.Abs(targetPoint - satelliteImagery.orthographicSize) < 0.1)
            {
                isScale = false;
                currentCoroutine = null;
            }
            yield return new WaitForSeconds(0.01f);
        }
    }





    private void OnEnable()
    {
        if (currentCoroutine != null)
        {
            currentCoroutine = null;
        }
        redShowImage.transform.parent.gameObject.SetActive(false);
        blueShowImage.transform.parent.gameObject.SetActive(false);
        GetSceneInfo();
    }
    /// <summary>
    /// red  地面设备   blue 无人机
    /// </summary>
    private void GetSceneInfo()
    {
        redObjs = deviceManager.devices.Where(x => x != null && x.gameObject.layer == 11).ToList();
        blueObjs = deviceManager.devices.Where(x => x != null && x.gameObject.layer == 12).ToList();
        if (redContanier.childCount > 0)
        {
            for (int i = 0; i < redContanier.childCount; i++)
            {
                Destroy(redContanier.GetChild(i).gameObject);
            }
        }
        if (blueContanier.childCount > 0)
        {
            for (int i = 0; i < blueContanier.childCount; i++)
            {
                Destroy(blueContanier.GetChild(i).gameObject);
            }
        }
        for (int i = 0; i < redObjs.Count; i++)
        {
            CreatDeviceItem(redContanier, redObjs[i].name, redObjs[i].deviceID, 0);
            redObjs[i].onDeviceDelete += RemoveItem;
        }
        for (int i = 0; i < blueObjs.Count; i++)
        {
            CreatDeviceItem(blueContanier, blueObjs[i].name, blueObjs[i].deviceID, 1);
            blueObjs[i].onDeviceDelete += RemoveBlueItem;
        }
    }

    /// <summary>
    /// 实时更新设备列表
    /// </summary>

    public void RemoveItem(string id)
    {
        UnmannedAerialVehicleManage temp = null;
        for (int i = 0; i < redObjs.Count; i++)
        {
            if (redObjs[i].deviceID == id)
            {
                temp = redObjs[i].GetComponent<UnmannedAerialVehicleManage>();
                redObjs.Remove(redObjs[i]);
                return;
            }
        }
        FormationManager.Instance.RemoveAppointWRJ(temp);
    }

    public void RemoveBlueItem(string id)
    {
        for (int i = 0; i < blueObjs.Count; i++)
        {
            if (blueObjs[i].deviceID == id)
            {
                blueObjs.Remove(blueObjs[i]);
                return;
            }
        }
    }

    private void CreatDeviceItem(Transform contanier, string objName, string id, int redOrBlue)
    {
        DeviceBtnItem obj = Instantiate(deviceBtnItem, contanier);
        obj.SetInfo(id, objName);

        obj.selfBtn.onClick.AddListener(() =>
        {
            if (redOrBlue == 0)
            {
                if (objName.Contains("电子侦察无人机"))
                {
                    redShowImage.transform.parent.GetComponent<Mask>().enabled = true;
                }
                else
                {
                    redShowImage.transform.parent.GetComponent<Mask>().enabled = false;
                }
            }
            if (redOrBlue == 1)
            {
                if (objName.Contains("频谱探测") || objName.Contains("雷达"))
                {
                    blueShowImage.transform.parent.GetComponent<Mask>().enabled = true;
                }
                else
                {
                    blueShowImage.transform.parent.GetComponent<Mask>().enabled = false;
                }
            }
            OnDeviceBtn(id, redOrBlue);
        });

    }

    private void OnDeviceBtn(string id, int redOrBlue)
    {
        if (droneViewDisplay.renderTextureTo(id) == null)
        {
            redShowImage.transform.parent.gameObject.SetActive(false);
            blueShowImage.transform.parent.gameObject.SetActive(false);
            return;
        }
        if (string.IsNullOrEmpty(id)) return;
        if (redOrBlue == 0)
        {
            redShowImage.transform.parent.gameObject.SetActive(true);
            redShowImage.texture = droneViewDisplay.renderTextureTo(id);
        }
        else
        {
            blueShowImage.transform.parent.gameObject.SetActive(true);
            blueShowImage.texture = droneViewDisplay.renderTextureTo(id);

        }
    }
}