using System;
using System.Collections;
using System.Collections.Generic;
using Imagine.WebAR;
using TriLibCore;
using UnityEngine;
using UnityEngine.UI;
using static TaskConfig.windowItemGameObject;

public class TaskManager : MonoBehaviour
{
    public GameObject HtmlBG;
    public UserInfo myInfo;
    public ARCamera ar;
    public List<TaskConfig> tconfigs;
    public TaskConfig ntconfig;

    public RawImage bg;
    public RawImage imgbg;
    public RawImage centerbg;
    public RawImage centerbg2;
    public RawImage topbg;
    public GameObject prebg;
    public GameObject Closebt;
    public GameObject Closebt2;
    public Text dialogueText;

    public GameObject Main;
    public GameObject Sence;
    public GameObject daoju;

    public GameObject video;
    public GameObject allimg;
    public GameObject allimg2;

    public GameObject ar_1img;
    public GameObject ar_2img;
    public GameObject ar_1glb;
    public GameObject ar_2glb;
   
    public RawImage bigbg;

    public GameObject GamePIntu;

    public List<GameObject> daojulist;

    public ImageTracker itracker;
    public WorldTracker wtracker;

    public GameObject tuodongbg;

    public GameObject shibie;

    public GameObject Inputgo;
    public GameObject duihuakuang;
    TaskItem nowTaskItem;

    public GameObject xiansuo;
    public int nowTaskIndex;
    public int nowTaskCt;
    public GameObject main_click;

    public GameObject inputbt;
    private void Awake()
    {
        StartCoroutine(InitGame());
    }

    public void saveindex(bool isFinish)
    {
        if (PlayerPrefs.GetInt("isend")!=1)
        {
            PlayerPrefs.SetInt("nowTaskCt", nowTaskCt);
            PlayerPrefs.SetInt("nowTaskIndex", nowTaskIndex);
            if (isFinish)
            {
                PlayerPrefs.SetInt("isend", 1);
            }

        }
    }

    private IEnumerator InitGame()
    {
        Main.SetActive(false);
        Sence.SetActive(false);

   //     yield return new WaitForSeconds(1f);
      //  ar.PauseCamera();
     //   yield return new WaitForSeconds(2f);
        
        yield return StartCoroutine(InitUser());

        if (PlayerPrefs.GetInt("isend") != 1)
        {
            
            myInfo.taskIndex = PlayerPrefs.GetInt("nowTaskIndex");
            myInfo.taskCt = PlayerPrefs.GetInt("nowTaskCt");


            nowTaskIndex = myInfo.taskIndex;
            nowTaskCt = myInfo.taskCt;
            ntconfig = tconfigs[nowTaskCt];
            nowTaskItem = ntconfig.TaskList[nowTaskIndex];
            yield return StartCoroutine(checktaskSence(nowTaskItem));
        }

        else
        {

            Main.SetActive(true);
            Sence.SetActive(false);
        }
    }
    bool isclickxumu;
    public void gotoxumu()
    {
        if (PlayerPrefs.GetInt("isend") == 1)
        {
            isclickxumu = true;
            nowTaskCt = 0;
            nowTaskIndex = -1;
            ntconfig = tconfigs[nowTaskCt];

            nextTask();
            Main.SetActive(false);
            Sence.SetActive(true);
        }

    }

    public void gotodadian()
    {
        isclickxumu = false;
        nowTaskCt = 1;
        nowTaskIndex = 8;
        ntconfig = tconfigs[nowTaskCt];
        nextTask();
        Main.SetActive(false);
        Sence.SetActive(true);
    }
    GameObject hc;

    public List<GameObject> items;

    private IEnumerator checktaskSence(TaskItem ti)
    {
        if(hc)
        {
            Destroy(hc);
            hc = null;
        }
        dialogueText.text = ti.info;
        if(iidex==1&& ti.info2!="")
            dialogueText.text = ti.info2;
        
        getTexture(ti.bgName, (tex) => {
            if (tex)
            {
                bg.texture = tex;
                bg.color = new Color(bg.color.r, bg.color.g, bg.color.b, 1);
            }
            else
            {
                bg.color = new Color(bg.color.r, bg.color.g, bg.color.b, 0);
            }
        });

        getTexture(ti.imgName, (tex) => {
            if (tex)
            {
                imgbg.texture = tex;
                imgbg.color = new Color(bg.color.r, bg.color.g, bg.color.b, 1);
            }
            else
            {
                imgbg.color = new Color(bg.color.r, bg.color.g, bg.color.b, 0);
            }
            duihuakuang.SetActive(ti.centerName != "one_end");
        });
        getTexture(ti.centerName, (tex) => {
            if (tex)
            {
                centerbg.GetComponent<RectTransform>().sizeDelta = new Vector2(tex.width, tex.height);
                centerbg.texture = tex;
                centerbg.color = new Color(bg.color.r, bg.color.g, bg.color.b, 1);
                centerbg.gameObject.SetActive(true);
                centerbg.transform.localScale = new Vector3(0.95f, 0.95f, 0.95f);
            }
            else
            {
                centerbg.color = new Color(bg.color.r, bg.color.g, bg.color.b, 0);
            }
        });
        
        GetBD(ti.perbName, (go) => {

            if(go)
            {
                go.SetActive(true);
                go.transform.parent = prebg.transform;
                go.transform.localPosition = Vector3.zero;
                go.transform.localEulerAngles = Vector3.zero;
                go.transform.localScale = Vector3.one;
                hc = go;
            }

        });
        if(ti.type != TaskConfig.TaskType.ARTask)
        {
            bigbg.color = new Color(bigbg.color.r, bigbg.color.g, bigbg.color.b, 1);
            imgbg.color = new Color(imgbg.color.r, imgbg.color.g, imgbg.color.b, 1);

        }

        for (int i = 0; i < items.Count; i++)
        {
            if(ti.daojus.Count>i)
            {
                items[i].SetActive(ti.daojus[i].isshow);
            }else
            {
                items[i].SetActive(false);
            }
        }
        dialogueText.GetComponent<Button>().enabled = ti.isTextNext;

        inputbt.SetActive(false);
        nongwu.SetActive(ti.isnongwu);
        HtmlBG.SetActive(ti.type!=TaskConfig.TaskType.ARTask);
        shibie.SetActive(false);
        switch (ti.type)
        {
            case TaskConfig.TaskType.Dialogue:
                if (isarinit)
                {
                    //wtracker.StopTracker();
                    ar.PauseCamera();
                }
                ar_2img.SetActive(false);
                ar_1img.SetActive(false);
                Main.SetActive(false);
                Sence.SetActive(true);
                allimg.SetActive(ti.isClose);
                Closebt.SetActive(ti.isClosebtShow);
                allimg.GetComponent<Button>().enabled = !ti.isClosebtShow;

                tuodongbg.SetActive(ti.isTuo);
                break;
            case TaskConfig.TaskType.Xiansuo:
                if (isarinit)
                {
                    ar.PauseCamera();
                }
                Main.SetActive(false);
                Sence.SetActive(true);
                xiansuo.SetActive(true);
                break;
            case TaskConfig.TaskType.ARTask:
                if (!isarinit)
                {
                    ar.InitAR();
                    isarinit = true;
                    Invoke("yanchi", 2f);

                }
                else
                {

                    bigbg.color = new Color(bigbg.color.r, bigbg.color.g, bigbg.color.b, 0);
                    imgbg.color = new Color(imgbg.color.r, imgbg.color.g, imgbg.color.b, 0);
                    ar.UnpauseCamera();
                }
                if (ti.isARSao)
                {
                    shibie.SetActive(true);
                    itracker.StartTracker();
                    //wtracker.StartTracker();
                    wtracker.ResetOrigin();

                    switch (ti.arid)
                    {
                        case 1:

                            ar_1glb.SetActive(false);
                            ar_2glb.SetActive(false);
                            ar_1img.SetActive(ti.isARSao);
                            ar_2img.SetActive(false);
                            break;
                        case 2:
                            ar_1glb.SetActive(false);
                            ar_2glb.SetActive(false);
                            ar_2img.SetActive(ti.isARSao);
                            ar_1img.SetActive(false);
                            break;

                    }
                }
                else
                {
                    switch (ti.arid)
                    {
                        case 1:
                            ar_1glb.SetActive(true);
                            ar_2glb.SetActive(false);
                            break;
                        case 2:
                            ar_1glb.SetActive(false);
                            ar_2glb.SetActive(true);
                            break;

                    }
                    itracker.StopTracker();
                   
                }
              //  Main.SetActive(false);
                break;
            case TaskConfig.TaskType.SkipSence:
                if (isarinit)
                {
                    ar.PauseCamera();
                }
                switch (ti.info)
                {
                    case "daoju":
                        daoju.SetActive(true);
                        Invoke("nextTask", 1f);
                        break;
                    case "end":
                        video.SetActive(true);
                        duihuakuang.SetActive(ti.centerName != "one_end");
                        Invoke("videoclose", 3f);
                        break;
                    case "end2":
                        end2.SetActive(true);
                        break;
                    case "main":
                        Main.SetActive(true);
                        Sence.SetActive(false);
                        main_click.SetActive(true);
                        break;
                }
                break;
            case TaskConfig.TaskType.GameTask:
                switch (ti.info)
                {
                    case "pintu":
                        GamePIntu.SetActive(true);
                        break;
                }
                break;
            case TaskConfig.TaskType.InputTask:
                if (isarinit)
                {
                    ar.PauseCamera();
                }
                inputbt.SetActive(true);
                ar_2img.SetActive(false);
                ar_1img.SetActive(false);
                Main.SetActive(false);
                Sence.SetActive(true);
                allimg.SetActive(ti.isClose);
                Closebt.SetActive(ti.isClosebtShow);
                allimg.GetComponent<Button>().enabled = !ti.isClosebtShow;

                tuodongbg.SetActive(ti.isTuo);
                Inputgo.SetActive(true);
                break;
            case TaskConfig.TaskType.ChooseTask:

                if (isarinit)
                {
                    ar.PauseCamera();
                }
                ar_2img.SetActive(false);
                ar_1img.SetActive(false);
                Main.SetActive(false);
                Sence.SetActive(true);
                allimg.SetActive(ti.isClose);
                dialogueText.GetComponent<Button>().enabled =false;
                Closebt.SetActive(ti.isClosebtShow);
                allimg.GetComponent<Button>().enabled = !ti.isClosebtShow;
                choosego.SetActive(true);
                tuodongbg.SetActive(ti.isTuo);
                break;
        }

        yield return null;
    }
    bool isarinit=false;
    public void arFound()
    {
        nextTask();
    }
    public GameObject errortext;
    public void checkinput()
    {
        if(Inputgo.GetComponent<InputField>().text == nowTaskItem.taskcheck)
        {
            Inputgo.SetActive(false);
            nextTask();
        }else
        {
            errortext.SetActive(true);
        }
    }

    public void yanchi()
    {

        bigbg.color = new Color(bigbg.color.r, bigbg.color.g, bigbg.color.b, 0);
        imgbg.color = new Color(imgbg.color.r, imgbg.color.g, imgbg.color.b, 0);
    }
    public GameObject showBT;
    public void videoclose()
    {
        showBT.SetActive(true);
       // showBT.GetComponent<>(true);
        //nextTask();
    }
    public void nextTask()
    {
        if(nowTaskItem.type == TaskConfig.TaskType.InputTask)
        {
            Inputgo.GetComponent<InputField>().text = "";
        }

        if(!allimg.activeSelf||(allimg.activeSelf&& nowTaskItem.isClose)|| nowTaskItem.type== TaskConfig.TaskType.ChooseTask)
        {
            if (nowTaskIndex + 1 >= ntconfig.TaskList.Count)
            {
                if(nowTaskCt+1>=tconfigs.Count)
                {

                    nowTaskCt = 1;
                    ntconfig = tconfigs[nowTaskCt];
                    nowTaskIndex = 8;
                    Main.SetActive(true);
                    Sence.SetActive(false);

                    saveindex(true);
                }
                else
                {
                    if(!isclickxumu)
                    {
                        nowTaskCt++;
                        ntconfig = tconfigs[nowTaskCt];
                        nowTaskIndex = 0;
                        nowTaskItem = ntconfig.TaskList[nowTaskIndex];
                        StartCoroutine(checktaskSence(nowTaskItem));
                        saveindex(false);

                    }
                    else
                    {
                        Main.SetActive(true);
                        Sence.SetActive(false);
                    }

                }
            }
            else
            {
                nowTaskIndex++;
                nowTaskItem = ntconfig.TaskList[nowTaskIndex];
                StartCoroutine(checktaskSence(nowTaskItem));
            }
        }


    }

    public static void getTexture(string m_url, Action<Texture2D> callback)
    {
        if (m_url == "" || m_url == null)
        {
            callback.Invoke(null);
        }
        else
        {
            string filePath = System.IO.Path.Combine(Application.streamingAssetsPath + "/ui", m_url);
            SetWebGLText.Instance.GetTexture(filePath + ".png", (Texture2D t2d) => {

                callback.Invoke(t2d);
            });

        }
    }

    public static void GetBD(string m_url, Action<GameObject> callback)
    {
        if (m_url == "" || m_url == null)
        {
            callback.Invoke(null);
        }
        else
        {
            SetWebGLText.Instance.GetBD(m_url, (GameObject t2d) => {

                callback.Invoke(t2d);
            });

        }
    }

    public void checkisNextTask()
    {
        
        //nextTask();


    }

    public void showdaoju(string urlname)
    {
        allimg2.SetActive(true);
        Closebt2.SetActive(true);
        allimg2.GetComponent<Button>().enabled = false;

        getTexture(urlname, (tex) => {
            if (tex)
            {
                centerbg2.GetComponent<RectTransform>().sizeDelta = new Vector2(tex.width, tex.height);
                centerbg2.texture = tex;
                centerbg2.color = new Color(bg.color.r, bg.color.g, bg.color.b, 1);
                centerbg2.transform.localScale = new Vector3(0.95f, 0.95f, 0.95f);
                centerbg2.gameObject.SetActive(true);
            }
            else
            {
                centerbg2.color = new Color(bg.color.r, bg.color.g, bg.color.b, 0);
            }
        });
    }


    public static void loadUrl(string ModelURL, Action<AssetLoaderContext> OnLoad, Action<AssetLoaderContext> OnMaterialsLoad, Action<AssetLoaderContext, float> OnProgress, Action<IContextualizedError> OnError, GameObject go = null)
    {
        var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
        var webRequest = AssetDownloader.CreateWebRequest(ModelURL);
        AssetDownloader.LoadModelFromUri(webRequest, OnLoad, OnMaterialsLoad, OnProgress, OnError, go, assetLoaderOptions);

    }

    public static void loadFile(string ModelPath, Action<AssetLoaderContext> OnLoad, Action<AssetLoaderContext> OnMaterialsLoad, Action<AssetLoaderContext, float> OnProgress, Action<IContextualizedError> OnError, GameObject go = null)
    {
        var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
        AssetLoader.LoadModelFromFile(ModelPath, OnLoad, OnMaterialsLoad, OnProgress, OnError, go, assetLoaderOptions);
    }

    private IEnumerator InitUser()
    {
        myInfo = new UserInfo();
        yield return null;

    }

   public int iidex;
    public void chooseitem(int index)
    {
        iidex = index;
        nextTask();
    }

    public GameObject choosego;
    public GameObject end2;
    public GameObject nongwu;
}