using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using NSUListView;
using System;
using System.Linq;
using UnityEngine.SceneManagement;

public class HomePageLibrary : MonoBehaviour,IEventHandler
{
    public GameObject headVeiws = null;
    public GameObject lableVeiws = null;
    public GameObject imageViews = null;
    private CheckInput checkInput = null;
    public List<GameObject> ignoreList = new List<GameObject>();
    private Vector2 winPrvePos = new Vector2(0, 0);
    public float offsetYMax = 0;
    public float offsetYMin = 0;
    public float nowOffsetY = 0;
    private List<NetLableItem> labels = null;
    public int selectId = -1;
    //0 没有移动 1 初始横向 2 初始纵向 3 纵向但禁止
    int moveDir = 0;
    Dictionary<string, EventChildItemBack> childEventHandlers = new Dictionary<string, EventChildItemBack>();
    void onEvent(string name, EventChildItemBack func)
    {
        utilsTools.onEvent(this, name);
        childEventHandlers.Add(name, func);
    }
    private void setCheckInput()
    {
        if (checkInput == null)
        {
            checkInput = utilsTools.IsPhone ? checkInputByPhone : checkInputByComputer;
        }
    }
    void checkInputByPhone()
    {
        if (Input.touchCount == 1)
        {
            var oneTouch = Input.GetTouch(0);
            TouchPhase touchPhase = oneTouch.phase;
            if (touchPhase == TouchPhase.Began)
            {
                Debug.Log("one Click begin");
                if (checkMouseInIgnoreList(Input.mousePosition) == false)
                {
                    onOneTouchBegin(oneTouch.position);
                }
            }
            else if (touchPhase == TouchPhase.Moved)
            {
                if (utilsTools.ContainsKey(gameObject, "oneTouchBegin") == false) return;
                onOneTouchMove(oneTouch.position, oneTouch.deltaPosition);
            }
            else if (touchPhase == TouchPhase.Ended)
            {
                if (utilsTools.ContainsKey(gameObject, "oneTouchBegin") == false) return;
                onOneTouchEnd(oneTouch.position, oneTouch.deltaPosition);
            }else if(touchPhase == TouchPhase.Canceled)
            {
                clearOneTouchBegin();
                moveDir = 0;
            }
        }
    }
    void checkInputByComputer()
    {
        if (Input.GetMouseButtonDown(0))
        {
            print("*********** ------");
            if (utilsTools.ContainsKey(gameObject, "oneTouchBegin") == false)
            {
                if (checkMouseInIgnoreList(Input.mousePosition))
                {
                    winPrvePos.x = -9000000;
                    return;
                }
                winPrvePos = Input.mousePosition;
                onOneTouchBegin(Input.mousePosition);
                return;
            }
        }else if(Input.GetMouseButton(0) && winPrvePos.x > -8000000)
        {
            Vector2 diff = new Vector2(Input.mousePosition.x - winPrvePos.x, Input.mousePosition.y - winPrvePos.y);
            onOneTouchMove(Input.mousePosition, diff);
        }
        else if(Input.GetMouseButtonUp(0) && winPrvePos.x > -8000000)
        {
            Vector2 diff = new Vector2(Input.mousePosition.x - winPrvePos.x, Input.mousePosition.y - winPrvePos.y);
            winPrvePos = Input.mousePosition;
            onOneTouchEnd(Input.mousePosition, diff);
        }
    }
    private void onOneTouchBegin(Vector2 vector2)
    {
        var rectTransform = imageViews.GetComponent<RectTransform>();
        var temp = utilsTools.ScreenToUILocalPos(rectTransform, vector2);
        temp = temp - new Vector2(rectTransform.rect.width/2, rectTransform.rect.height/2) + new Vector2(rectTransform.transform.localPosition.x, rectTransform.transform.localPosition.y);
        
        if (rectTransform.rect.Contains(temp) == false)
        {
            return;
        }
        utilsTools.setUserData(gameObject, "oneTouchBegin", vector2);
    }
    void clearOneTouchBegin()
    {
        Debug.Log("one Click clear");
        utilsTools.delUserDataByKey(gameObject, "oneTouchBegin");
    }
    private void onOneTouchMove(Vector2 nowPos, Vector2 delatPos)
    {
        Debug.Log("Move " + moveDir.ToString());
        if(moveDir == 0)
        {
            if(Mathf.Abs(delatPos.x) > Mathf.Abs(delatPos.y))
            {
                moveDir = 1;
            }
            else
            {
                moveDir = 2;
            }
        }
        if(moveDir == 2)
        {
            offsetYMovePos(delatPos.y);            
        }
        
    }
    public void offsetYMovePos(float dtOffset)
    {
        if(offsetYMax > offsetYMin)
        {
            float tempOffsetY = nowOffsetY + dtOffset;
            if(tempOffsetY > offsetYMax)
            {
                tempOffsetY = offsetYMax - nowOffsetY;
                moveDir = 3;
            }
            else if(tempOffsetY < offsetYMin)
            {
                tempOffsetY = nowOffsetY - offsetYMin;
                moveDir = 3;
            }
            else
            {
                tempOffsetY = dtOffset;
            }
            nowOffsetY = tempOffsetY + nowOffsetY;
            GameObject[] gameObjects = { headVeiws,lableVeiws,imageViews };
            Vector3 pos;
            Quaternion quaternion;
            foreach (var item in gameObjects)
            {
                item.transform.GetLocalPositionAndRotation(out pos, out quaternion);
                pos.y -= tempOffsetY;
                item.transform.SetLocalPositionAndRotation(pos, quaternion);
            }
        }
    }
    private void onOneTouchEnd(Vector2 nowPos, Vector2 delatPos)
    {
        if (moveDir == 2)
        {
            offsetYMovePos(delatPos.y);
        }else if(moveDir == 1) { 
            Vector2 beginPos = new Vector2(nowPos.x,nowPos.y);
            utilsTools.getUserData<Vector2>(gameObject, "", out beginPos, nowPos);
            float diff = (beginPos.x - nowPos.x);
            if(Mathf.Abs(diff) > imageViews.GetComponent<RectTransform>().rect.width / 2)
            {
                //准备切页面
                utilsTools.sendEventObjectParams("SwitchLableNext", diff, true);
            }
            else
            {
                //回复原始的X位置
                utilsTools.sendEventObjectParams("SwitchLableNext", diff, false);
            }
        }
        moveDir = 0;
        clearOneTouchBegin();
    }
    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;
    }
    public void updateLabelScrollView()
    {
        gridView grid = transform.Find("mideleArea/lables").GetComponent<gridView>();
        grid.setData(labels.Count, (GameObject gobj, int idx, ListViewBackTypeEnum backType) => {
            if(backType == ListViewBackTypeEnum.create || backType == ListViewBackTypeEnum.update)
            {
                var item = gobj.GetComponent<prfb_hor_item>();
                item.setData(labels[idx], labels[idx].id.Equals(selectId));
            }
        }, false);
        
        GameObject gameObjectContext = grid.GetComponent<ScrollRect>().content.gameObject;
        gameObjectContext.GetComponent<GridLayoutGroup>().SetLayoutHorizontal();
    }
    private bool onLabelsInit(string data)
    {
        NetLabelTypeData netLabelTypeData = JsonUtility.FromJson<NetLabelTypeData>(data);
        if(netLabelTypeData == null) return false;
        if (netLabelTypeData.status.Equals(200))
        {
            labels = netLabelTypeData.result.data;
            selectId = labels[0].id;
            updateLabelScrollView();
            utilsTools.sendEventObjectParams("showImagePageData", -1,  false, "imageListL");
            utilsTools.sendEventObjectParams("showImagePageData", 1, false, "imageListR");
            utilsTools.sendEventObjectParams("showImagePageData", 0, true, "imageListM");//少量加载
            return true;
        }
        return false;
    }
    private void getLabels()
    {
        utilsTools.httpGET(this, "http://8.218.187.222:19897/app/v1/game/ts/getTags?type=18&page=1&zygt=hzwz&tgtk=1", true,
            (string id, string url, bool isSuccess, System.Object data) => {
                if (isSuccess)
                {
                    if (onLabelsInit(data as string) == false) return 1;
                    return 0;
                }
                else
                {
                    return 1;
                }
            });
    }
    // Start is called before the first frame update
    void Start()
    {
        setCheckInput();
        onEvent("switchHomeLabels", onClickSwitchHomeLabelsEvent);
        onEvent("SwitchLableNext", onSwitchLableNextEvent);
        onEvent("showImagePageData", onShowImagePageDataEvent);
        onEvent("clickImageViewHandler", onClickImageViewHandlerEvent);
        
        getLabels();
    }
    // Update is called once per frame
    void Update()
    {
        setCheckInput();
        TaskManages.getInstance().updateTask(this);
        //checkInput();
    }
    public void onTestOper(Vector2 vector2)
    {
        if(vector2.y == 0.0f)
        {
        }
        else if(vector2.y == 1.0f)
        {
        }
    }

    public void onEventHandler(string eventName, List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        if (childEventHandlers.ContainsKey(eventName)) childEventHandlers[eventName](uobjects, objects);
    }
    public void onSwitchLableNextEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        float diff = (float)objects[0];
        bool switchFlg = (bool)objects[1];
        if (switchFlg)//
        {
            int idx = 0;
            for (int i = 0; i < labels.Count; i++)
            {
                if (labels[i].id.Equals(selectId))
                {
                    idx = i;
                    break;
                }
            }
            if (diff > 0.0f)
            {
                idx = idx + 1;
            }
            else
            {
                idx = idx - 1;
            }
            if(idx >= 0 && idx < labels.Count)
            {
                onClickSwitchHomeLabelsEvent(null,new List<System.Object> { labels[idx].id });
                return;
            }
        }
        
    }
    public void onClickSwitchHomeLabelsEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        gridView grid = transform.Find("mideleArea/lables").GetComponent<gridView>();
        int clickId = (int)objects[0];
        float x = 0;
        int idx = 0;
        for (int i = 0; i < labels.Count; i++)
        {
            if (labels[i].id.Equals(clickId))
            {
                var obj = grid.getObjectById(i).GetComponent<prfb_hor_item>();
                obj.setData(labels[i], true);
                x = obj.transform.localPosition.x;
                idx = i;
            }
            else if (labels[i].id.Equals(selectId))
            {
                grid.getObjectById(i).GetComponent<prfb_hor_item>().setData(labels[i], false);
            }
        }

        selectId = clickId;
        utilsTools.sendEventObjectParams("showImagePageData", idx - 1, false, "imageListL");
        utilsTools.sendEventObjectParams("showImagePageData", idx, true, "imageListM");//少量加载
        utilsTools.sendEventObjectParams("showImagePageData", idx+1, false, "imageListR");
        
        //scrollViewSkipToPosAction(x);
    }
    //imageListM
    public void onShowImagePageDataEvent(List<UnityEngine.Object> uobjects, List<System.Object> objects)
    {
        int idx = (int)objects[0];
        bool isShow = (bool)objects[1];
        string name = (string)objects[2];
        //USimpleListView homeImageGrid = transform.Find("imageListBase/" + name).GetComponent<USimpleListView>();
        homeImageGridView homeImageGrid = transform.Find("imageListBase/" + name).GetComponent<homeImageGridView>();
        if (idx < 0 || idx >= labels.Count)
        {
            homeImageGrid.gameObject.SetActive(false);
            return;
        }
        homeImageGrid.gameObject.SetActive(true);
        var tm = TaskManages.getInstance(); ;
        TaskItemBack taskItemBack = (System.Object[] param1) =>
        {
            homeImageGrid.swapLoadData(labels[idx].tagId, (bool)param1[2]);
        };
        if (isShow)
        {
            tm.insertTask(this, taskItemBack, name, idx, isShow);
        }
        else
        {
            //tm.addTask(this, taskItemBack, name, idx,isShow);
        }
    }
    
    public void onShowImagePageDataEvent1(List<UnityEngine.Object> uobjects, List<object> objects)
    {
        int idx = (int)objects[0];
        bool isShow = (bool)objects[1];
        string name = (string)objects[2];
        homeImageGridView homeImageGrid = transform.Find("imageListBase/"+name).GetComponent<homeImageGridView>();
        
        if(idx < 0 || idx >= labels.Count)
        {
            homeImageGrid.gameObject.SetActive(false);
            return;
        }
        homeImageGrid.gameObject.SetActive(true);
        var tm = TaskManages.getInstance(); ;
        TaskItemBack taskItemBack = (System.Object[] param1) =>
        {
            string name1 = (string)param1[0];
            int idx1 = (int)param1[1];
            homeImageGridView homeImageGrid1 = transform.Find("imageListBase/" + name).GetComponent<homeImageGridView>();
            homeImageGrid.swapLoadData(labels[idx].tagId,(bool)param1[2]);
        };
        if (isShow)
        {
            tm.insertTask(this,taskItemBack, name, idx,isShow);
        }
        else
        {
            //tm.addTask(this, taskItemBack, name, idx,isShow);
        }
    }
    //clickImageViewHandler
    public void onClickImageViewHandlerEvent(List<UnityEngine.Object> uobjects, List<object> objects)
    {
        string id = (string)objects[0];
        utilsTools.setGDataByKey("nowUseGameId", id);
        SceneManager.LoadScene("Scenes/gameScene");
    }
    public void scrollViewSkipToPosAction(float x)
    {
        
        gridView grid = transform.Find("mideleArea/lables").GetComponent<gridView>();
        utilsTools.addTimer_Update(grid.gameObject, "offset", (string name) =>
        {
            ScrollRect scrollRect = grid.GetComponent<ScrollRect>();
            Rect rectObj = grid.GetComponent<RectTransform>().rect;
            Rect rect = scrollRect.content.GetComponent<RectTransform>().rect;
            Vector2 vector2 = scrollRect.normalizedPosition;
            vector2.x = x / (rect.width - rectObj.width/2);
            scrollRect.normalizedPosition = vector2;
            return false;
        });
    }
    public void OnDestroy()
    {
        IRunEventManages.unOn(this, null);
        ActionManages.clearAllAction();
    }
}
