using System.Collections;
using System.Collections.Generic;
using Unity.EditorCoroutines.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using WS;

public class UploadStepsEditor : EditorWindow
{
    [MenuItem("Tools/上传步骤")]
    public static void ShowVoice()
    {
        UploadStepsEditor window = EditorWindow.GetWindow<UploadStepsEditor>("上传步骤");
        window.Show();
    }

    private UploadStepsConfig Setting;
    private List<WSTask> Tasks;

    ///<summary>是否上传中</summary>
    private bool IsUpload;
    ///<summary>当前已经完成数量</summary>
    private int UploadCurrent;

    private EditorCoroutine UploadCoroutine;

    private void OnEnable()
    {
        string path = $"{Application.dataPath}/Resources/Config/Process/AllProcess.txt";
        List<Module> config = ConfigHelper.FileLoadConfig<List<Module>>(path);
        Tasks = new List<WSTask>();
        for (int i = 0; i < config.Count; i++)
        {
            Tasks.AddRange(config[i].WSTasks);
        }
        Setting = AssetDatabase.LoadAssetAtPath<UploadStepsConfig>("Assets/Editor/Framework/Other/UploadStepsConfig.asset");
    }

    private void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("URL:", GUILayout.Width(50));
        string url = Setting.URL;
        Setting.URL = EditorGUILayout.TextField(Setting.URL);
        if (url != Setting.URL)
        {
            EditorUtility.SetDirty(Setting);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Token:", GUILayout.Width(50));
        string token = Setting.Token;
        Setting.Token = EditorGUILayout.TextField(Setting.Token);
        if (token != Setting.Token)
        {
            EditorUtility.SetDirty(Setting);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("课程Id:", GUILayout.Width(50));
        int courseId = Setting.CourseId;
        Setting.CourseId = EditorGUILayout.IntField(Setting.CourseId);
        if (courseId != Setting.CourseId)
        {
            EditorUtility.SetDirty(Setting);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        if (IsUpload)
        {
            GUILayout.Label($"进度:{UploadCurrent}/{Tasks.Count}");
        }
        else
        {
            GUILayout.Label("");
        }
        if (GUILayout.Button("上传", GUILayout.Width(100)))
        {
            if (IsUpload)
            {
                Debug.LogError("正在上传中!");
                return;
            }
            if (!string.IsNullOrEmpty(Setting.URL) || !string.IsNullOrEmpty(Setting.Token) || Setting.CourseId > 0)
            {
                IsUpload = true;
                UploadWeb();
                //UploadCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(UploadWeb());
            }
            else
                Debug.LogError("参数不能为空!");
        }
        EditorGUILayout.EndHorizontal();

    }

    private void UploadWeb()
    {
        for (int i = 0; i < Tasks.Count; i++)
        {
            UploadCurrent++;
            UploadData uploadData = new UploadData
            {
                stepName = Tasks[i].Name,
                stepSn = Tasks[i].Id.ToString(),
                branchId = Setting.CourseId,
                stepScore = Tasks[i].Score.ToString(),
            };
            string json = LitJson.JsonMapper.ToJson(uploadData);
            byte[] postBytes = System.Text.Encoding.Default.GetBytes(json);
            UnityWebRequest webrequest = UnityWebRequest.Post(Setting.URL, UnityWebRequest.kHttpVerbPOST);
            webrequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
            webrequest.SetRequestHeader("Content-Type", "application/json");
            webrequest.SetRequestHeader("Authorization", Setting.Token);
            webrequest.SendWebRequest();
            //if (string.IsNullOrEmpty(webrequest.error))
            //{
            //    Debug.Log($"上传成功! {Tasks[i].Name}");
            //}
            //else
            //{
            //    Debug.LogError($"上传失败! {webrequest.error}");
            //    break;
            //}
        }
        IsUpload = false;
        UploadCurrent = 0;
        UploadCoroutine = null;
    }

    private class UploadData
    {
        public string Id;
        ///<summary>名称</summary>
        public string stepName;
        ///<summary>编号</summary>
        public string stepSn;
        ///<summary>课程Id</summary>
        public int branchId;
        ///<summary>分数</summary>
        public string stepScore;
    }
}