using LitJson;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public class DownLoadItem : MonoBehaviour
{
    public delegate void DownLoadCallBack(bool b);
    public delegate void DownLoadPressOn(float f);

    //下载回调
    public DownLoadCallBack callback;
    //下载进度回调
    public DownLoadPressOn onProgress;

    //下载ID
    public string id;

    /// <summary>
    ///  下载地址
    /// </summary>
    public string downLoadPath;
    /// <summary>
    /// 是否下载成功
    /// </summary>
    public bool isDownLoad;
    /// <summary>
    /// 下载成功后的文件
    /// </summary>
    public byte[] downLoadData;

    public object downLoadObject;

    public ModelType type;
    /// <summary>
    /// 进度条
    /// </summary>
    public float progress;
    /// <summary>
    /// 下载后状态
    /// </summary>
    public string downLoadState;

    //下载后是否有处理
    public bool isAction;
    public long updateTime;

    private UnityWebRequest webRequest;

    public void Init(string downLoadPath,string id,ModelType type,long updateTime)
    {
        this.downLoadPath = downLoadPath;
        this.id = id;
        this.type = type;
        this.updateTime = updateTime;
        LoadManager.Instance.downloadQueueList.Enqueue(this);
    }

    public System.Collections.IEnumerator DownloadFile()
    {
        string url = HttpAction.Instance.baseurl + HttpAction.file_download;
        if (UserInfo.Instance.is20)
        {
            url = HttpAction.Instance.baseurl20 + HttpAction.file_download;
        }
        Debug.Log(" 当前下载>>>>     " + url + "   " + downLoadPath);
        using (webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
        {
            SendMaterials sendImage = new SendMaterials();
            sendImage.url = downLoadPath;
            string jsonString = JsonConvert.SerializeObject(sendImage);
            Debug.Log("body   :" + jsonString);
            Debug.Log("Token   :" + UserInfo.Instance.Token);
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
            //DownloadHandlerTexture texture = new DownloadHandlerTexture(true);
            //webRequest.downloadHandler = texture;
             webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            //switch (type)
            //{
            //    case ModelType.Image:
            //        webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerTexture(true);
            //        break;
            //    case ModelType.Video:
            //        webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerAudioClip("", AudioType.ACC);
            //        break;
            //    case ModelType.ABModel:
            //        webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerFile(Application.persistentDataPath + downLoadPath);
            //        break;
            //    case ModelType.Text:

            //    default:
            //        webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            //        break;
            //}

            webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
            webRequest.SetRequestHeader("Content-Type", "application/json");

            yield return webRequest.SendWebRequest();

            while (!webRequest.isDone)
            {
                // 此处可以显示下载进度条等UI操作
                progress = webRequest.downloadProgress;
                onProgress?.Invoke(progress);
                // Debug.Log("Download Progress: " + progress);
                yield return new WaitForFixedUpdate();
            }

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError("Download Failed: " + webRequest.error);
                // 下载失败 
                downLoadState = webRequest.error;
                isDownLoad = false;
            }
            else
            {
                Debug.Log(webRequest.isDone + "    " + webRequest.downloadHandler.data.Length);
               // Debug.LogError("Download Failed: " + webRequest.error);
              
                downLoadData = webRequest.downloadHandler.data;
                isDownLoad = true;
                downLoadState = "下载成功";
            }
            //if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
            //{
            //    //Debug.LogError("Download Failed: " + webRequest.error);

            //    downLoadData = webRequest.downloadHandler.data;
            //    isDownLoad = true;
            //}
            //else
            //{
            //    //switch (type)
            //    //{
            //    //    case ModelType.Image:
            //    //        break;
            //    //    case ModelType.Video:
            //    //        break;
            //    //    case ModelType.ABModel:
            //    //        var ab =  DownloadHandlerAssetBundle.GetContent(webRequest);
            //    //        downLoadObject = ab;
            //    //        AssetBundleRequest abRequest = ab.LoadAssetAsync(ab.GetAllAssetNames()[0]);
            //    //        yield return abRequest;
            //    //       GameObject obj =  abRequest.asset as GameObject;
            //    //        Debug.Log(" AssetBundleRequest>>>>  " + obj.name);
            //    //        break;
            //    //    case ModelType.Text:
            //    //        break;
            //    //    default:
            //    //        break;
            //    //}
            //    // 下载失败 


            //}
            callback?.Invoke(isDownLoad);
        }





        //string url = HttpAction.baseurl + HttpAction.file_download;
        //SendMaterials sendImage = new SendMaterials();
        //sendImage.url = downLoadPath;
        //if (UserInfo.Instance.is20)
        //{
        //    url = HttpAction.baseurl20 + HttpAction.file_download;
        //}
        //string jsonString = JsonMapper.ToJson(sendImage);
        //if (UserInfo.Instance.is20) 
        //    Debug.Log(string.Format("url:{0} postData:{1}", url, jsonString));


        //using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        //{
        //    byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
        //    webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        //    DownloadHandlerTexture texture = new DownloadHandlerTexture(true);
        //    webRequest.downloadHandler = texture;
        //    // Debug.Log(value.mObj.localSavePath);
        //    // webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerFile(value.mObj.localSavePath);
        //    //  Debug.Log(value.mObj.localSavePath);
        //    webRequest.SetRequestHeader("authorization", UserInfo.Instance.Token);
        //    webRequest.SetRequestHeader("Content-Type", "application/json");

        //    yield return webRequest.SendWebRequest();

        //    if (webRequest.isHttpError || webRequest.isNetworkError)
        //    {
        //        Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);


        //    }
        //    else
        //    {
        //        if (callback != null)
        //        {

        //            try
        //            {

        //            }
        //            catch (Exception e)
        //            {

        //            }

        //            try
        //            {
        //                Texture2D texture2 = texture.texture;
        //                Sprite createSprite = Sprite.Create(texture2, new Rect(0, 0, texture2.width, texture2.height), Vector2.zero);
        //                Debug.Log(webRequest.downloadHandler.data.Length + "    " + texture2.width);


        //                Texture2D texture3 = texture.texture;
        //            }
        //            catch (Exception e)
        //            {
        //                // ErrorLogPanel.Instance.Show(" 图片生成出现错误 " + jsonString);

        //            }
        //            ////转为字节数组  

        //            // File.WriteAllBytes(value.mObj.localSavePath, webRequest.downloadHandler.data);

        //        }
        //    }
        //}
           
      

    }

    public void DownloadFileMsg()
    {
        Debug.Log("查询需要下载的updateTime"+updateTime);
        MsgHandler.AddListener(downLoadPath, HandleMsg);
        DownLoadMaterial data = new DownLoadMaterial();
        data.downLoadPath = downLoadPath;
        data.localLoadPath = Application.persistentDataPath + "/Material/" + Path.GetFileName(downLoadPath);
        if(type == ModelType.vuforial)
            data.localLoadPath = Application.persistentDataPath + "/StreamingAssets/Vuforia/GHZVuforia." + downLoadPath.Split('.')[1];
  
        data.type = ((int)type).ToString();

        

        Debug.LogError("DownloadFileMsg");
        DownloadResManager.Instance.DownLoad(data);
    }

    private void HandleMsg(Msg msg)
    {
        if (msg.Value != null)
        {
            downLoadData = (byte[])msg.Value;
            isDownLoad = true;
            downLoadState = "下载成功";

        }
        else
        {
            isDownLoad = true;
            downLoadState = "下载失败";
        }
        callback?.Invoke(isDownLoad);
        MsgHandler.RemoveListener(Application.persistentDataPath + "" + downLoadPath, HandleMsg);

    }

    Dictionary<string, string> requestHeader = new Dictionary<string, string>();  //  header
    public void initHead()
    {
        requestHeader.Clear();
        if (UserInfo.Instance.Token != "" && UserInfo.Instance.Token != null)
        {
            //  requestHeader.Add("x-token", UserInfo.Instance.Token);
            Debug.Log("ADD  Token");
            requestHeader.Add("authorization", UserInfo.Instance.Token);
        }
        requestHeader.Add("Content-Type", "application/json");
    }


    private void OnDestroy()
    {
        // 断开下载连接
        if (webRequest != null && !webRequest.isDone)
        {
            webRequest.Abort();
        }
    }

}