using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

delegate void CheckInput();
public class mainGameScaleMove : MonoBehaviour
{
    private CheckInput checkInput = null;
    private Vector2 tempVector = new Vector2(0, 0);
    private Vector2 defvalueVector = new Vector2(-90000, -90000);
    private Vector2 nowScale = new Vector2();
    private Vector2 nowPos = new Vector2();
    private Vector2 nowSize = new Vector2();
    private bool skipDoubleScale = false;
    public float OldTouchCurrDis = -1000;
    public float minScale = 0.25f;
    public float maxScale = 1.25f;//8f;
    public List<GameObject> ignoreList = new List<GameObject>();
    private List<System.Object> logTempList = null;
    private Vector2 winPrvePos = new Vector2(-90000, -90000);
    public List<Sprite> DebugSprites = new List<Sprite>();
    public Vector2 NowPos
    {
        get { return nowPos; }
    }
    public Vector2 NowScale
    {
        get
        {
            return nowScale;
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        logTempList = new List<object>();
        logTempList.Add("");
        logTempList.Add("");
        logTempList.Add("");
        logTempList.Add("");
        setCheckInput();
        Vector3 tempVector3;
        Quaternion quaternion;
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            itemChild.GetLocalPositionAndRotation(out tempVector3, out quaternion);
            itemChild.SetLocalPositionAndRotation(tempVector3, quaternion);
            if(i == 0)
            {
                nowPos = new Vector2(tempVector3.x,tempVector3.y);
                nowScale = itemChild.localScale;
                Rect rect = GetComponent<RectTransform>().rect;
                nowSize = new Vector2(rect.width, rect.height);
            }
        }
    }
    private void setCheckInput()
    {
        if (checkInput == null)
        {
            checkInput = utilsTools.IsPhone ? checkInputByPhone : checkInputByComputer;
        }
    }
    
    void checkInputByPhone()
    {
        if (Input.touchCount == 2)
        {
            clearOneTouchBegin();
            Touch touch1 = Input.GetTouch(0);
            Touch touch2 = Input.GetTouch(1);
            if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved)
            {
                if (skipDoubleScale) return;
                onDoubleTouchHandler(Vector2.Distance(touch1.position, touch2.position));
            }
            else
            {
                OldTouchCurrDis = -1000;
            }
            skipDoubleScale = false;
            //else
            //{

            //}
        } else if (Input.touchCount == 1)
        {
            var oneTouch = Input.GetTouch(0);
            TouchPhase touchPhase = oneTouch.phase;
            if(touchPhase == TouchPhase.Began)
            {
                Debug.Log("one Click begin");
                onOneTouchBegin(oneTouch.position);
            }
            else if(touchPhase == TouchPhase.Moved)
            {
                if (utilsTools.ContainsKey(gameObject, "oneTouchBegin") == false) return;
                Debug.Log("one Click move");
                onOneTouchMove(oneTouch.position, oneTouch.deltaPosition);
            }else if(touchPhase == TouchPhase.Ended)
            {
                if (utilsTools.ContainsKey(gameObject, "oneTouchBegin") == false) return;
                Debug.Log("one Click end");
                onOneTouchEnd(oneTouch.position, oneTouch.deltaPosition);
            }else if(touchPhase == TouchPhase.Canceled)
            {
                clearOneTouchBegin();
            }
        }
    }
    void onDoubleTouchHandler(float nowTouchDistance)
    {
        if(OldTouchCurrDis < -999)
        {
            OldTouchCurrDis = nowTouchDistance;
            return;
        }
        var nowOffset = (nowTouchDistance - OldTouchCurrDis) * 0.002f;
        if(nowOffset < 0)
        {
            if (nowScale.x + nowOffset < minScale)
            {
                skipDoubleScale = true;
                nowOffset = 0.8f;
            }
        }else if(nowOffset > 0)
        {
            if(nowScale.x + nowOffset > maxScale)
            {
                skipDoubleScale = true;
                return;
            }
        }
        nowScale = new Vector2(nowScale.x + nowOffset,nowScale.y + nowOffset) ;
        OldTouchCurrDis = nowTouchDistance;
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            itemChild.localScale = nowScale;
        }
    }
    void clearOneTouchBegin()
    {
        Debug.Log("one Click clear");
        utilsTools.delUserDataByKey(gameObject, "oneTouchBegin");
    }
    bool checkMouseInIgnoreList(Vector2 vector)
    {
        for (int i = 0; i < ignoreList.Count; i++)
        {
            if (ignoreList[i] == null) continue;
            RectTransform checkRectTransform = ignoreList[i].transform.GetComponent<RectTransform>();
            var newLocalPos = utilsTools.ScreenToUILocalPos(checkRectTransform, vector);
            if (checkRectTransform.rect.Contains(newLocalPos)) return true;
        }
        return false;
    }
    //左键点击 右键缩放
    void checkInputByComputer()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if(utilsTools.ContainsKey(gameObject, "oneTouchBegin") == false)
            {
                if (checkMouseInIgnoreList(Input.mousePosition))
                {
                    winPrvePos.x = -9000000;
                    return;
                }
                winPrvePos = Input.mousePosition;
                onOneTouchBegin(Input.mousePosition);
                return;
            }
            Vector2 diff =  new Vector2(Input.mousePosition.x + winPrvePos.x,Input.mousePosition.y + winPrvePos.y);
            onOneTouchMove(Input.mousePosition, diff);
        }else if(utilsTools.ContainsKey(gameObject, "oneTouchBegin"))
        {
            Vector2 diff = new Vector2(Input.mousePosition.x + winPrvePos.x, Input.mousePosition.y + winPrvePos.y);
            onOneTouchEnd(Input.mousePosition, diff);
        }
    }
    private void onOneTouchBegin(Vector2 vector2)
    {
        if(checkMouseInIgnoreList(vector2) == false)
            utilsTools.setUserData(gameObject, "oneTouchBegin", vector2);
    }
    private void onOneTouchMove(Vector2 nowPos,Vector2 delatPos)
    {
        Vector3 tempVector3 = new Vector3(0, 0);
        Quaternion quaternion = new Quaternion();
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            if(i == 0)
            {
                itemChild.GetLocalPositionAndRotation(out tempVector3, out quaternion);
                float width = nowScale.x * nowSize.x;
                float height = nowScale.y * nowSize.y;
                if(delatPos.x < 0 && (tempVector3.x + delatPos.x) < (width / -2))
                {
                    delatPos.x = 0;
                }else if(delatPos.x > 0 && (tempVector3.x + delatPos.x) > (width / 2))
                {
                    delatPos.x = 0;
                }
                if(delatPos.y < 0 && (tempVector3.y + delatPos.y) < (height / -2))
                {
                    delatPos.y = 0;
                }
                else if(delatPos.y > 0 && (tempVector3.y + delatPos.y) > (height / 2))
                {
                    delatPos.y = 0;
                }
                if (delatPos.x == delatPos.y && delatPos.x == 0) return;//都不用移动就不更新坐标
                tempVector3.x += delatPos.x;
                tempVector3.y += delatPos.y;
                Debug.Log("move"+tempVector3.ToSafeString()+ nowScale.ToSafeString()+ nowSize.ToSafeString());
            }
            itemChild.SetLocalPositionAndRotation(tempVector3, quaternion);
        }
        //更新坐标 应该记录当前显示的位置
    }
    private void onOneTouchEnd(Vector2 nowPos, Vector2 delatPos)
    {
        utilsTools.getUserData<Vector2>(gameObject, "oneTouchBegin", out tempVector, defvalueVector);
        if (tempVector.Equals(defvalueVector))//说明之前已经移除了
        {
            return;
        }
        float sqrMagnitude = (nowPos - tempVector).SqrMagnitude();
        clearOneTouchBegin();
        if (sqrMagnitude > 20f) {//按下和抬起距离太远就不算点击
            Debug.Log("begin end diff big "+ sqrMagnitude);
            return;
        }
        onOneClick(nowPos);
    }
    //获取图片和屏幕交集的区域  //屏幕坐标系
    Rect ImageToSceneJiao()
    {
        //将四个点转成屏幕坐标系
        RectTransform firstRectTransform = transform.GetChild(0).GetComponent<RectTransform>();
        Rect rect = firstRectTransform.rect;
        return rect;
    }
    private Vector3 GetNativePosition(Vector3 screenPos)
    {
        // 将屏幕坐标转换为世界坐标
        screenPos.z = 10000f;
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
        Ray2D ray = new Ray2D(worldPos, Vector2.right);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
        if(hit.collider != null)
        {
            Debug.Log("有碰撞 ....");
        }
        else
        {
            Debug.Log("没有碰撞 ");
        }
        // 获取节点的缩放信息
        Vector3 scale = transform.localScale;

        // 获取节点的位置信息
        Vector3 position = transform.localPosition;

        // 计算节点的逆变换矩阵
        Matrix4x4 inverseTransform = Matrix4x4.TRS(-position, Quaternion.identity, Vector3.one).inverse;
        inverseTransform *= Matrix4x4.Scale(new Vector3(1 / scale.x, 1 / scale.y, 1 / scale.z));
        // 将世界坐标转换为节点内的原生坐标
        Vector3 nativePos = inverseTransform.MultiplyPoint(worldPos);

        return nativePos;
    }
    private void onOneClick(Vector2 nowPos)
    {
        Vector3 temp = new Vector3(nowPos.x,nowPos.y);
        mainGameView mainView = GetComponent<mainGameView>();
        int width;
        int height;
        if (mainView.getSize(out width, out height) == false) return;
        var lineTransform = transform.Find("low").GetComponent<RectTransform>();
        Vector2 vector = utilsTools.ScreenToUILocalPos(lineTransform, nowPos);
        if (lineTransform.rect.Contains(vector))
        {
            Vector2 scaleVector = new Vector2(width / lineTransform.rect.width, height / lineTransform.rect.height);
            Vector2 pos1 = vector * scaleVector;
            short x = Convert.ToInt16(pos1.x + width / 2);
            short y = Convert.ToInt16(pos1.y + height / 2);
            utilsTools.sendEventObjectParams("gameClickPos", x,y);
        }
        else
        {
            print("2");
        }
        //nowPos = GetNativePosition(temp);
        //Debug.Log("当前点击位置到图片对应"+temp.ToSafeString());
    }
    // Update is called once per frame
    void Update()
    {
        setCheckInput();
        checkInput();
    }
}
