using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip.Compression;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VectorGraphics;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
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 = 60f;
    public List<GameObject> ignoreList = new List<GameObject>();
    private Vector2 winPrvePos = new Vector2(-90000, -90000);
    public List<Sprite> DebugSprites = new List<Sprite>();
    public GameObject resetBtn = null;
    private Vector3 initScale = new Vector3();
    public Vector2 oleMovePos = new Vector3();
    public Vector2 scaleConstPos = new Vector2();
    public Vector2 NowPos
    {
        get { return nowPos; }
    }
    public Vector2 NowScale
    {
        get
        {
            return nowScale;
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        Vector3 tempVector3;
        Quaternion quaternion;
        maxScale = 8f;
        minScale = 0.25f;
        Debug.Log("**************");
        Debug.Log(Vector2.Distance(new Vector2(-100, -100), new Vector2(20, 60)));
        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);
            }
        }
        if(resetBtn != null)
        {
            resetBtn.SetActive(false);
        }
    }
    public void setCheckInput()
    {
        if (checkInput == null)
        {
            initScale = transform.GetChild(0).GetComponent<RectTransform>().localScale;
            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;
                if (OldTouchCurrDis < -999)
                {
                    Vector2 touchPos1 = utilsTools.DisplaySize / 2 + touch1.position;
                    Vector2 touchPos2 = utilsTools.DisplaySize / 2 + touch2.position;
                    Vector2 zhongxin = (touchPos1 - touchPos2) / 2 + utilsTools.DisplaySize / 2;
                    mainGameView mainView = GetComponent<mainGameView>();
                    var lineTransform = transform.Find("low").GetComponent<RectTransform>();
                    Vector2 vector = utilsTools.ScreenToUILocalPos(lineTransform, zhongxin);
                    if (lineTransform.rect.Contains(vector) == false)
                    {
                        if (lineTransform.rect.xMin > vector.x)
                        {
                            vector.x = lineTransform.rect.xMin;
                        }
                        else if (lineTransform.rect.xMax < vector.x)
                        {
                            vector.x = lineTransform.rect.xMax;
                        }
                        if (lineTransform.rect.yMin > vector.y)
                        {
                            vector.y = lineTransform.rect.yMin;
                        }
                        else if (lineTransform.rect.yMax < vector.y)
                        {
                            vector.y = lineTransform.rect.yMax;
                        }
                    }
                    scaleConstPos = new Vector2(vector.x / (lineTransform.rect.width * lineTransform.localPosition.x), vector.y / (lineTransform.rect.height * lineTransform.localPosition.y));
                    OldTouchCurrDis = Vector2.Distance(touch1.position,touch2.position);
                    return;
                }
                
                //Vector2 center = new Vector2(touch1.position.x-touch2.position.x,touch1.position.y-touch2.position.y);
                onDoubleTouchHandler(Vector2.Distance(touch1.position, touch2.position));
            }
            else {
                skipDoubleScale = false;
                OldTouchCurrDis = -1000;
            }
            
            
        } 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)
    {

        var nowOffset = (nowTouchDistance - OldTouchCurrDis) * utilsTools.getGDataByKey<float>("doubleTouchScale", 0.002f);
        //var nowOffset = nowTouchDistance * utilsTools.getGDataByKey<float>("doubleTouchScale",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;
            }
        }
        int dt001 = utilsTools.getTotalMillisecond();
        nowScale = new Vector2(nowScale.x + nowOffset,nowScale.y + nowOffset) ;
        OldTouchCurrDis = nowTouchDistance;
        Vector2 offsetPos = Vector2.zero;
        int dt002 = 0;
        int dt003 = 0;
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            if(i == 0)
            {
                RectTransform rectTrans1 = itemChild.GetComponent<RectTransform>();
                Vector2 scaleDiff = nowScale - new Vector2(itemChild.localScale.x, itemChild.localScale.y);
                Vector2 scaleDiffSize = new Vector2(scaleDiff.x * rectTrans1.rect.width, scaleDiff.y * rectTrans1.rect.height);
                if (!(itemChild.localPosition.x == 0 || itemChild.localPosition.y == 0))
                {
                    offsetPos = scaleConstPos * scaleDiffSize;
                }
                else
                {
                    offsetPos = scaleDiffSize;
                }
                
                offsetPos = scaleDiffSize / 4;///2 左下角 锁定 不偏移 中心锁定 

                
            }
            itemChild.localScale = nowScale;
            Vector3 nowPos = new Vector3(itemChild.localPosition.x + offsetPos.x, itemChild.localPosition.y + offsetPos.y);
            itemChild.localPosition = nowPos;
            if (i == 0 && resetBtn)
            {
                RectTransform rectTrans = itemChild.GetComponent<RectTransform>();
                dt002 = utilsTools.getTotalMillisecond();
                bool leftIsOut = checkPtIsOutScene(rectTrans,new Vector2(rectTrans.rect.xMin, 0));
                bool rightIsOut = checkPtIsOutScene(rectTrans,new Vector2(rectTrans.rect.xMax, 0));
                bool topIsOut = checkPtIsOutScene(rectTrans,new Vector2(0, rectTrans.rect.yMax));
                bool downIsOut = checkPtIsOutScene(rectTrans, new Vector2(0, rectTrans.rect.yMin));
                dt003 = utilsTools.getTotalMillisecond();
                if ((leftIsOut && rightIsOut) || (topIsOut && downIsOut))
                {
                    resetBtn.SetActive(true);
                }
                else
                {
                    resetBtn.SetActive(false);
                }
                
            }
        }
        int dt004 = utilsTools.getTotalMillisecond();
        updateScaleView();
        int dt005 = utilsTools.getTotalMillisecond();
        String msg = String.Format("5 - 4 = {0},3 - 2 = {1},5 -1 = {2}", dt005 - dt004, dt003 - dt002, dt005 - dt001);
        Debug.Log(msg);
    }
    bool checkPtIsOutScene(RectTransform rectTrans,Vector2 pos)
    {
        Vector3 vector3 = rectTrans.TransformPoint(new Vector3(pos.x, pos.y));
        Vector3 vector31 = Camera.main.WorldToScreenPoint(vector3);
        if(vector31.x >Screen.width || vector31.x < 0 || vector31.y > Screen.height || vector31.y < 0)
        {
            return true;
        }
        return false;
    }
    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);
        var itemChild = transform.GetChild(0);
        tempVector3 = itemChild.localPosition;
        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;//都不用移动就不更新坐标

        if (delatPos.x == 0f || delatPos.y == 0f)
        {
            return;
        }
        float scaleBet = utilsTools.getGDataByKey<float>("moveScale", 1.0f);
        delatPos = delatPos * scaleBet;
        tempVector3.x += delatPos.x;
        tempVector3.y += delatPos.y;
        updateSizeMove(tempVector3);
        //更新坐标 应该记录当前显示的位置
    }
    private void updateSizeMove(Vector3 tempVector3)
    {
        
        Quaternion quaternion = new Quaternion();
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            itemChild.localPosition = tempVector3;
            //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);
    }
    private void onOneClick(Vector2 nowPos)
    {
        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);
        }
    }
    // Update is called once per frame
    void Update()
    {
        
        if (checkInput != null)
        {
            if (utilsTools.getGDataByKey<bool>("enableZoomMove", false))
            {
                checkInput();
            }
        }
        
    }
    private void updateScaleView()
    {
        GetComponent<mainGameView>().updateScaleView();
    }
    public void onResetSizeCenterHandler()
    {
        resetBtn.SetActive(false);
        nowScale = new Vector2(initScale.x,initScale.y);
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            itemChild.localScale = initScale;
            itemChild.localPosition = new Vector3(0, 0);
        }
        updateScaleView();
    }
    public void onAutoFillHander()
    {
        onResetSizeCenterHandler();
        GetComponent<mainGameView>().onAutoFillHandler();
    }
    public void onTipShowPosMaxScale(gameAreaItem areaItem,float width,float height)
    {
        nowScale = new Vector2(maxScale,maxScale);
        Vector3 pos = new Vector3();
        float ptx = areaItem.px / width * 1.0f;//百分比
        float pty = areaItem.py / height * 1.0f;
        
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            itemChild.localScale = nowScale;
        }
        Debug.Log(areaItem.ToString());
        RectTransform idAreaRectTransform = transform.Find("areaIdBase/" + areaItem.tempExKey).GetComponent<RectTransform>();
        pos = idAreaRectTransform.localPosition * -1 * nowScale / initScale;
        
        for (int i = 0; i < transform.childCount; i++)
        {
            var itemChild = transform.GetChild(i);
            itemChild.localPosition = pos;
        }
        if (resetBtn != null)
        {
            resetBtn.SetActive(true);
        }
        updateScaleView();
    }
}
