using LitJson; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using UnityEngine; using UnityEngine.Networking; using ZXKFramework; namespace YiLiao.Main { public class BaoGaoController : SingletonDdol { public string baseUrl; public string baoGaoUrl; public ClodeData codeRoot; public TokenData tokenData; public UserRoot userRoot; public UrlData urlData = new UrlData(); UrlPathData mUrlPathData = new UrlPathData();//通过streamingAssetsPath下Json读取的baseUrl /// /// 初始化数据 /// public override void InitInstance() { base.InitInstance(); try { // 读取地址Json string loPath = Application.streamingAssetsPath + "/UrlPathData.json"; string content = File.ReadAllText(loPath); mUrlPathData = JsonMapper.ToObject(content); baseUrl = mUrlPathData.baseUrl; baoGaoUrl = baseUrl + "/client/training/notify"; Debug.Log($"BaoGaoController urlPathData:{content} baseUrl:{baseUrl} baoGaoUrl:{baoGaoUrl} courseId:{mUrlPathData.courseId}"); } catch (Exception e) { Debug.LogError(e); } } public void LoginPost(string account, string password, string yanzhengma, Action callBack) { Login(new LoginData() { account = account, password = password, uuid = codeRoot.data.uuid, code = yanzhengma }, (m, n) => { if (m) { //成功之后显示验证码错误 tokenData = n.ToClass(); if (tokenData.code == 500) { //网络错误 callBack?.Invoke(false, tokenData.msg); } else { //验证码成功就可以进入 callBack?.Invoke(m, n); GetUserInfo((m, n) => { if (m) { userRoot = n.ToClass(); } else { //网络错误 callBack?.Invoke(false, "网络错误"); } }); } } else { //网络错误 callBack?.Invoke(false, "网络错误"); } }); } /// /// 报告上传 /// /// /// public void EndBaoGao(Root root, Action callBack) { #if UNITY_EDITOR #elif UNITY_WEBGL root.uuid = urlData.uuid; root.examId = urlData.examId; root.questionId = urlData.questionId; //root.experimentId = urlData.experimentId; root.courseId = urlData.courseId; #endif string json = JsonMapper.ToJson(root).ToUTF8(); //string json = Resources.Load("Data").text;//测试数据 Debug.Log($"报告数据 {json}"); WWWForm loWWWForm = new WWWForm(); loWWWForm.AddField("jsonStr", json); StartCoroutine(PostWWWForm(baoGaoUrl, loWWWForm, (m, n) => { if (m) { Debug.Log("报告上传成功 " + n.text); callBack?.Invoke(n.text); } })); } public long TimeStampNow { get { // 获取当前时间 DateTime now = DateTime.UtcNow; // 转换为Unix时间戳(毫秒) long timestamp = ((long)(now - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds); return timestamp; } } public Root SetRoot(int _useTimes, int _allScore, List _steps) { Root root = new Root(); root.uuid = userRoot.data.uuid; root.courseId = mUrlPathData.courseId;//课程编号 root.score = _allScore;//总分 root.endTime = TimeStampNow; root.timeUsed = _useTimes * 1000;//用时 root.startTime = root.endTime - root.timeUsed; root.secret = "实验说明"; root.require = "实训要求"; root.content = "实训内容"; root.structure = "实训结构"; root.ReportSummary = "实验报告总结"; root.examId = "0"; root.questionId = "0"; root.experimentId = 0; root.status = 1; root.appid = "1"; root.secret = "1"; //root.steps = _steps; if (_steps.Count != 0) { for (int i = 0; i < _steps.Count; i++) { //步骤对比数据 ScoreStatistics step = new ScoreStatistics(); step.name = _steps[i].name; step.score_roportion = int.Parse(_steps[i].score.ToString("0")); //step.type = _steps[i].type; root.scoreStatistics?.Add(step); //步骤显示 root.content += $" ----> 步骤:{step.name} 得分:{step.score_roportion}"; //步骤详细数据 Step loStep = _steps[i]; //loStep.questions.Clear(); root.steps.Add(loStep); } } return root; } //https://virtual-emulation.zhihuishu.com/webgl/2000086607/JBZXWangLuo/index.html?experId=2795148&courseId=10808092&experimentId=1410&taskId=7240&backurl=https://wenda.zhihuishu.com/stu/courseInfo/VirtualDetailsMain?courseId=10808092&assignmentId=7240 int IntSafe(string data) { try { return Int32.Parse(data.Trim()); } catch (Exception e) { Debug.LogError(data + " " + e); } return 0; } long GetShiJianChuo(DateTime dateTime) { return ((dateTime.Ticks - 621355968000000000) / 1000); } /// /// 获取验证码 /// public void GetCode(Action action) { string url = baseUrl + "client/login/captchaImage"; StartCoroutine(Get(url, (m, n) => { if (m) { codeRoot = n.ToClass(); action?.Invoke(m, codeRoot.data.img); } })); } /// /// 登录 /// /// 用户名 /// 密码 /// /// 验证码 /// public void Login(LoginData loginData, Action action) { string loUrl = baseUrl + "client/login/loginByPwd"; string jsonData = UnityTools.GetJson(loginData); StartCoroutine(Post(loUrl, jsonData, action)); } /// /// 获取用户信息 /// /// public void GetUserInfo(Action action) { string loUrl = baseUrl + "client/user/getUserInfo"; StartCoroutine(PostUserInfo(loUrl, action)); } /// /// 获取用户信息 /// /// /// /// public IEnumerator PostUserInfo(string url, Action callBack) { Debug.Log("Post url : " + url); UnityWebRequest www = new UnityWebRequest(url, "POST"); string token = "Bearer " + tokenData.data; Debug.Log("token : " + token); // 设置响应类型为JSON www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); www.SetRequestHeader("Content-Type", "application/json"); www.SetRequestHeader("Authorization", token); // 发送请求 yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log("Post fail: " + www.error); callBack?.Invoke(false, www.error); } else { string result = www.downloadHandler.text; Debug.Log("Post success: " + result); callBack?.Invoke(true, result); } } public IEnumerator PostWWWForm(string url, WWWForm form, Action callBack, string Header = null, string HeaderValue = null, int timeOut = 3) { //请求链接,并将form对象发送到远程服务器 using (UnityWebRequest webRequest = UnityWebRequest.Post(url, form)) { if (!string.IsNullOrEmpty(Header) && !string.IsNullOrEmpty(HeaderValue)) { webRequest.SetRequestHeader(Header, HeaderValue); } webRequest.timeout = timeOut * 1000; yield return webRequest.SendWebRequest(); if (webRequest.result != UnityWebRequest.Result.Success) { Debug.Log(webRequest.error); callBack?.Invoke(false, webRequest.downloadHandler); } else { callBack?.Invoke(true, webRequest.downloadHandler); } }; } public IEnumerator Post(string url, string json, Action callBack) { Debug.Log("Post url : " + url); UnityWebRequest www = new UnityWebRequest(url, "POST"); // 设置请求体为JSON数据 Debug.Log("Post data : " + json); byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json); www.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend); www.uploadHandler.contentType = "application/json"; // 设置响应类型为JSON www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); www.SetRequestHeader("Content-Type", "application/json"); //www.SetRequestHeader("Authorization", "Bearer 51e8ead1-52fa-4139-8c51-a2044b83f98a"); // 发送请求 yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log("Post fail: " + www.error); callBack?.Invoke(false, www.error); } else { string result = www.downloadHandler.text; Debug.Log("Post success: " + result); callBack?.Invoke(true, result); } } private IEnumerator Get(string url, Action action) { using (UnityWebRequest request = UnityWebRequest.Get(url)) { Debug.Log($"Get Utl : {url} "); yield return request.SendWebRequest(); string result; if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError) { result = request.error; Debug.Log($"Get fail : {result} "); action?.Invoke(false, result); } else { result = request.downloadHandler.text; Debug.Log($"Get success : {result} "); action?.Invoke(true, result); } } } } /// /// 地址数据 /// public class UrlPathData { public string baseUrl { get; set; } public string courseId { get; set; } } /// /// URL数据 /// public class UrlData { public string uuid { get; set; } public string examId { get; set; } public string questionId { get; set; } public string experimentId { get; set; } public string courseId { get; set; } } public static class Tools { public static string ToUTF8(this string self) { Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})"); self = reg.Replace(self, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); }); return self; } public static T ToClass(this string self) where T : class { return LitJson.JsonMapper.ToObject(self); } /// /// 字符转图片 /// /// /// public static Sprite StringToSprite(this string base64) { // 将Base64字符串转换为字节数组 byte[] imageBytes = Convert.FromBase64String(base64); // 创建一个新的Texture2D对象并加载字节数组数据 Texture2D texture = new Texture2D(1, 1); texture.LoadImage(imageBytes); // 将Texture2D对象应用到Image组件上 return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); } } public class TokenData { public int code { get; set; } /// /// 登录成功 /// public string msg { get; set; } public string data { get; set; } } /// /// 验证码数据 /// public class ClodeData { public int code { get; set; } /// /// 操作成功 /// public string msg { get; set; } public ClodeDataMsg data { get; set; } } public class ClodeDataMsg { /// /// /// public string img { get; set; } /// /// /// //public bool captchaEnabled { get; set; } /// /// /// public string uuid { get; set; } } /// /// 登录数据 /// public class LoginData { public string account = "";//账号 public string password = ""; public string uuid = ""; public string code = ""; } public class UserSchool { public int id { get; set; } /// /// 北京师范大学2 /// public string name { get; set; } public string logo { get; set; } public string profile { get; set; } /// /// 公办大学 /// public string nature { get; set; } /// /// 双一流 /// public string features { get; set; } } public class UserClassItem { public int id { get; set; } public int classId { get; set; } /// /// 建筑2024年1届1班 /// public string className { get; set; } public int userId { get; set; } } public class UserData { /// /// /// public int id { get; set; } /// /// /// public int schoolId { get; set; } /// /// /// public int role { get; set; } /// /// /// public string account { get; set; } /// /// /// public string phone { get; set; } /// /// 赵敏 /// public string userName { get; set; } /// /// /// public string userNo { get; set; } /// /// /// public string position { get; set; } /// /// /// public string profile { get; set; } /// /// /// public int majorId { get; set; } /// /// /// public int majorId2 { get; set; } /// /// /// public int gender { get; set; } /// /// /// public string avatar { get; set; } /// /// /// public string email { get; set; } /// /// /// public int status { get; set; } /// /// /// public UserSchool school { get; set; } /// /// /// //public List class { get; set; } /// /// /// public string uuid { get; set; } /// /// 建筑类 /// public string majorName { get; set; } /// /// 桥梁仿真 /// public string major2Name { get; set; } } public class UserRoot { /// /// /// public int code { get; set; } /// /// 操作成功 /// public string msg { get; set; } /// /// /// public UserData data { get; set; } } public class Inputs { } public class ReportContentsItem { /// /// 内容 /// public string name { get; set; } /// /// /// public List images { get; set; } /// /// /// public string imageType { get; set; } /// /// /// public string type { get; set; } /// /// /// public Inputs inputs { get; set; } /// /// 我是内容 /// public string script { get; set; } /// /// /// public List datas { get; set; } } public class ReportModelsItem { /// /// 实验1 /// public string name { get; set; } /// /// /// public List reportContents { get; set; } } public class ScoreStatistics { public string name { get; set; } public int score_roportion { get; set; } } public class Root { public string uuid { get; set; } public string examId { get; set; } public string questionId { get; set; } public int experimentId { get; set; } public string courseId { get; set; } public long startTime { get; set; } public long endTime { get; set; } public long timeUsed { get; set; } public List scoreStatistics { get; set; } = new List(); public List steps { get; set; } = new List(); public List reportModels { get; set; } public int status { get; set; } public int score { get; set; } public string appid { get; set; } public string secret { get; set; } /// /// 实验报告总结 /// public string ReportSummary { get; set; } /// /// 实训要求 /// public string require { get; set; } /// /// 实训内容 /// public string content { get; set; } /// /// 实训结构 /// public string structure { get; set; } } }