using DocumentFormat.OpenXml.Office2010.ExcelAc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using OpenXmlPowerTools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
using TEAMModelOS.SDK.Helper.Common.JsonHelper;
using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
using TEAMModelOS.SDK.Helper.Security.ShaHash;
using TEAMModelOS.SDK.Module.AzureBlob.Container;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Helper.Common.StringHelper;

namespace TEAMModelOS.Controllers.Analysis
{
    [Route("api/[controller]")]
    [ApiController]
    public class ChangeController : Controller
    {
        private readonly SnowflakeId _snowflakeId;
        private readonly IWebHostEnvironment _hostingEnvironment;
        public readonly AzureCosmosFactory _azureCosmos;
        public readonly AzureStorageFactory _azureStorage;
        private const string CacheCosmosPrefix = "Analysis:";
        public ChangeController(IWebHostEnvironment hostingEnvironment, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, SnowflakeId snowflakeId)
        {
            _snowflakeId = snowflakeId;
            _hostingEnvironment = hostingEnvironment;
            _azureCosmos = azureCosmos;
            _azureStorage = azureStorage;
        }



        /* [HttpGet("SaveObjectAdas")]
         public async Task<BaseResponse> SaveObjectAdasAsync(string identity)

         {
             // 获取系统路径
             string contentRootPath = _hostingEnvironment.ContentRootPath;
             identity = "IES/19910";
             //string query = "$.info";
             //int countClasses = 0; 
             //string queryClass = "$member.1.item_answer[*]";
             string query = "$.exercises[*]";
             //string queryInfo = "$.info";
             string queryPoint = "$.testpaper.items[*]";
             string queryInfo = "$.testpaper.info";
             string querySchoolInfo = "$.exercises[*].info";
             string data = FileTool.getJson(contentRootPath, identity);
             data = FileTool.UnicodeToString(data);
             JsonElement parsedJson = JsonExtensions.ToObject<JsonElement>(data);
             JsonPathContext context = new JsonPathContext
             { ValueSystem = new JsonApiValueSystem() };
             //解析试卷作答详情
             List<dynamic> papers = context.SelectNodes(parsedJson,
             query).Select(node => node.Value).ToList();
             //解析试卷基本信息
             List<dynamic> info = context.SelectNodes(parsedJson,
             queryInfo).Select(node => node.Value).ToList();
             //解析题库信息
             List<dynamic> Itempoint = context.SelectNodes(parsedJson,
             queryPoint).Select(node => node.Value).ToList();
             //解析学校信息
             List<dynamic> SchoolInfo = context.SelectNodes(parsedJson,
            querySchoolInfo).Select(node => node.Value).ToList();

             int m = 0;
             //人数总和
             int Count = 0;
             //起始坐标
             int Strat = 0;
             // 初始化学生人数
             int Stus = 0;
             ExamResult simple = new ExamResult();
             ExamAnswer examAnswer = new ExamAnswer();

             List<Student> students = new List<Student>();
             List<Classroom> classrooms = new List<Classroom>();
             //List<ExamAnswer> examAnswers = new List<ExamAnswer>();
             List<List<List<int>>> ClassPoint = new List<List<List<int>>>();
             List<List<double>> StuPoint = new List<List<double>>();
             List<string> StuIds = new List<string>();
             List<List<string>> stuAnswers = new List<List<string>>();
             List<Dictionary<string, int[]>> Classes = new List<Dictionary<string, int[]>>();
             Dictionary<object, object> ListInfo = new Dictionary<object, object>();
             List<double> points = new List<double>();
             //配分数组
             Paper paper = new Paper();
             List<ItemInfo> items = new List<ItemInfo>();
             int k = 0;

             //考试基本信息
             SchoolInfo[0].TryGetProperty("ex_no", out JsonElement exam_no);
             SchoolInfo[0].TryGetProperty("ex_time", out JsonElement ex_time);
             SchoolInfo[0].TryGetProperty("ex_endtime", out JsonElement ex_endtime);
             SchoolInfo[0].TryGetProperty("school_name", out JsonElement school_name);
             SchoolInfo[0].TryGetProperty("school_code", out JsonElement school_code);
             SchoolInfo[0].TryGetProperty("ex_name", out JsonElement ex_name);
             SchoolInfo[0].TryGetProperty("ex_type", out JsonElement ex_type);
             SchoolInfo[0].TryGetProperty("grade_name", out JsonElement grade_name);
             SchoolInfo[0].TryGetProperty("semester", out JsonElement semester);
             SchoolInfo[0].TryGetProperty("period_name", out JsonElement period_name);
             SchoolInfo[0].TryGetProperty("period_code", out JsonElement period_code);
             SchoolInfo[0].TryGetProperty("class_code", out JsonElement class_code);
             SchoolInfo[0].TryGetProperty("grade_code", out JsonElement grade_code);



             //试卷基本信息
             info.ForEach(e =>
             {
                 e.TryGetProperty("name", out JsonElement test_name);
                 e.TryGetProperty("test_date", out JsonElement test_date);
                 e.TryGetProperty("subject", out JsonElement subject);
                 e.TryGetProperty("subject_code", out JsonElement subject_code);
                 //e.TryGetProperty("test_name", out JsonElement test_name);
                 simple.name = test_name.ToString();
                 simple.time = test_date.ToString();
                 paper.name = test_name.ToString();
                 paper.subjectId = subject_code.ToString();
                 paper.subjectName = subject.ToString();
                 paper.id = _snowflakeId.NextId() + "";
             });

             string grade = grade_code.ToString();

             Itempoint.ForEach(p =>
             {
                 p.TryGetProperty("point", out JsonElement point);
                 p.TryGetProperty("options", out JsonElement options);
                 string pt = point.ToString();
                 string OpenTracing = p + "";
                 //JObject jArray = JObject.Parse(OpenTracing);
                 JsonElement jArray = JsonExtensions.ToObject<JsonElement>(OpenTracing);
                 jArray.TryGetProperty("options", out JsonElement op);
                 //string[] aa = op.ToString().Split("\": {");
                 int count = op.ToString().Count(s => s == '_');
                 //count.TryGetInt32(out int length);
                 List<CodeValue> codeValues = new List<CodeValue>();
                 for (int i = 1; i <= count; i++)
                 {
                     string queryOptions = "$." + i + "";
                     List<dynamic> itemOption = context.SelectNodes(op,
                     queryOptions).Select(node => node.Value).ToList();
                     itemOption.ToList<dynamic>().ForEach(i =>
                     {
                         i.TryGetProperty("option_idx", out JsonElement option);
                         i.TryGetProperty("data", out JsonElement data);
                         CodeValue code = new CodeValue
                         {
                             code = option.ToString(),
                             value = data.ToString()
                         };
                         codeValues.Add(code);
                     });
                 }

                 //题序
                 p.TryGetProperty("itemindex", out JsonElement itemindex);
                 //p.TryGetProperty("edu_goal", out JsonElement edu_goal);
                 p.TryGetProperty("answer", out JsonElement answer);
                 p.TryGetProperty("idx_desc", out JsonElement idx_desc);
                 p.TryGetProperty("content", out JsonElement content);
                 p.TryGetProperty("type", out JsonElement type);
                 p.TryGetProperty("edu_goal", out JsonElement field);
                 p.TryGetProperty("explain", out JsonElement explain);
                 string order = itemindex.ToString();
                 string ans = answer.ToString();
                 string knowlege = idx_desc.ToString();
                 int fieldType = int.Parse(field.ToString());

                 ItemInfo item = new ItemInfo
                 {
                     code = "Item-" + school_code.ToString(),
                     subjectId = paper.subjectId,
                     scope = "school",
                     periodId = period_code.ToString(),
                     gradeIds = new List<string> {
                         grade
                     },
                     question = content.ToString(),
                     score = double.Parse(pt),
                     answer = new List<string> {
                         ans
                     },
                     type = StringHelper.getTypeName(type.ToString()),
                     order = int.Parse(order),
                     //level = p.edu_goal,                            
                     option = codeValues,
                     field = fieldType,
                     explain = explain.ToString(),
                     points = new List<string> {
                         knowlege
                     }


                 };
                 items.Add(item);
                 k++;
                 points.Add(double.Parse(pt.Trim()));
             });
             //处理试卷信息
             AzureBlobModel modle = await _azureStorage.UploadFileByContainer("hbcn", items.ToJsonString(), "paper", paper.subjectId + ".json");
             paper.blob = modle.BlobUrl;
             paper.code = "Paper-" + school_code.ToString();
             paper.periodId = period_code.ToString();
             paper.gradeIds = new List<string> { grade };
             paper.scope = "school";
             //paper.subjectCode = "Subject_Math";



             School sc = new School();
             List<ExamClassResult> examClassResults = new List<ExamClassResult>();
             ExamInfo examInfo = new ExamInfo();

             string st = ex_time.ToString();
             string ed = ex_endtime.ToString();
             DateTime.TryParse(st, out DateTime tt);
             DateTime.TryParse(ed, out DateTime etime);
             long time = DateTimeHelper.ToUnixTimestamp(tt);
             long edtime = DateTimeHelper.ToUnixTimestamp(etime);

             sc.schoolCode = school_code.ToString();
             sc.id = school_code.ToString();
             sc.code = "Base";


             sc.name = school_name.ToString();
             sc.period = new List<Period> { new Period {name = period_name.ToString() , id = period_code.ToString(),grades= new List<Grade> {
                     new Grade { name = grade_name.ToString() ,id = grade_code.ToString()} } } };

             //考试基本信息
             //examInfo.id = _snowflakeId.NextId() + "";
             examInfo.code = "Exam-" + school_code.ToString();
             examInfo.name = ex_name.ToString();
             examInfo.type = ex_type.ToString();
             examInfo.id = exam_no.ToString();
             examInfo.startTime = time;
             examInfo.endTime = edtime;
             examInfo.period.id = period_code.ToString();
             examInfo.period.name = period_name.ToString();
             examInfo.grades = new List<Grade> {
                 new Grade {
                     name = grade_name.ToString() ,id = grade_code.ToString()
                 }
             };
             examInfo.subjects.Add(new Subject { id = paper.subjectId, name = paper.subjectName });
 *//*            examInfo.conditions = new Condition
             {
                 period = period_code.ToString(),
                 grade = grade_code.ToString(),
                 semester = semester.ToString(),
                 subject = new List<string> { paper.subjectId }
             };*//*
             SchoolInfo.ForEach(s =>
             {
                 s.TryGetProperty("stucount", out JsonElement stucount);
                 string count = stucount.ToString();
                 examInfo.stuCount += int.Parse(count);
             });
             papers.ForEach(x =>
             {
                 x.TryGetProperty("info", out JsonElement info);
                 //var c = papers[i].member;
                 info.TryGetProperty("stucount", out JsonElement stucount);
                 info.TryGetProperty("course_name", out JsonElement class_name);
                 info.TryGetProperty("course_no", out JsonElement class_code);
                 info.TryGetProperty("school_name", out JsonElement school_name);
                 string stu = stucount.ToString();
                 int k = int.Parse(stu);
                 string key = class_name.ToString();
                 string schoolName = school_name.ToString();
                 Classroom classInfo = new Classroom
                 {
                     //id = _snowflakeId.NextId() + "",
                     name = key,
                     //classroomType = schoolName,
                     //studentCount = k,
                     id = class_code.ToString(),
                     code = "Class-" + sc.id
                 };
                 classrooms.Add(classInfo);
                 Classroom classInfoOfStudent = new Classroom
                 {
                     name = key,
                     //schoolCode = schoolName,
                     //studentCount = k,
                     id = class_code.ToString()
                 };
                 ExamClassResult examClassResult = new ExamClassResult();
                 //examClassResult.pk = typeof(ExamClassResult).Name;
                 examClassResult.code = "ExamClassResult-" + sc.id;
                 examClassResult.school = sc.id;
                 examClassResult.id = _snowflakeId.NextId() + "";
                 examClassResult.examId = examInfo.id;
                 examClassResult.subjectId = paper.subjectId;
                 examClassResult.classCode = classInfo.code;
                 examClassResult.classeId = classInfo.id;
                 examClassResult.progress = "finish";
                 examClassResult.paper.id = paper.id;
                 examClassResult.paper.code = paper.code;
                 examClassResult.paper.name = paper.name;
                 examClassResult.point = points;
                 Dictionary<string, int[]> map = new Dictionary<string, int[]>();
                 int[] Range = new int[2];
                 //处理学生作答数据
                 List<List<string>> classStudentAnswer = new List<List<string>>();
                 List<List<double>> classStuPoint = new List<List<double>>();
                 List<string> classStuIds = new List<string>();
                 x.TryGetProperty("members", out JsonElement members);
                 for (int j = 0; j < k; j++)
                 {
                     Student stus = new Student
                     {
                         type = 2,
                         //schoolCode = schoolName
                     };
                     string men = members[j] + "";
                     JsonElement jArray = JsonExtensions.ToObject<JsonElement>(men);
                     //JObject jArray = JObject.Parse(men);
                     string queryClass = "$.item_answers[*]";
                     string queryStu = "$.info";
                     List<string> ans = new List<string>();
                     List<dynamic> answers = context.SelectNodes(jArray,
                     queryClass).Select(node => node.Value).ToList();
                     //学生ID集合
                     List<dynamic> studentIds = context.SelectNodes(jArray,
                     queryStu).Select(node => node.Value).ToList();

                     List<double> point = new List<double>();
                     if (answers.Count == 0)
                     {
                         StuIds.Add("0");
                         k++;
                     }
                     else
                     {
                         //处理学生信息
                         studentIds.ToList<dynamic>().ForEach(s =>
                         {
                             s.TryGetProperty("student_id", out JsonElement student_id);
                             s.TryGetProperty("name", out JsonElement name);
                             s.TryGetProperty("seatno", out JsonElement seatno);
                             string id = student_id.ToString();
                             //id = System.Guid.NewGuid().ToString();
                             stus.id = id.Trim();
                             stus.name = name.ToString();
                             stus.studentId = id.Trim();
                             string sno = seatno.ToString();
                             if (sno.Equals(""))
                             {
                                 stus.seatNo = 0;
                             }
                             else
                             {
                                 stus.seatNo = int.Parse(sno);
                             }

                             //stus.classroom = classInfoOfStudent;
                             StuIds.Add(id.Trim());
                             classStuIds.Add(id.Trim());
                         });
                         students.Add(stus);
                     }

                     answers.ToList<dynamic>().ForEach(p =>
                     {
                         p.TryGetProperty("real_point", out JsonElement real_point);
                         p.TryGetProperty("ans_content", out JsonElement ans_content);
                         string pt = real_point.ToString();
                         string ansContent = ans_content.ToString();
                         if (ans.Equals(""))
                         {
                             ansContent = "无";
                         }
                         ans.Add(ansContent);
                         point.Add(double.Parse(pt.Trim()));
                     });
                     classStudentAnswer.Add(ans);
                     classStuPoint.Add(point);
                     stuAnswers.Add(ans);
                     StuPoint.Add(point);
                     Stus++;
                 }
                 examClassResult.studentAnswers = classStudentAnswer;
                 examClassResult.studentScores = classStuPoint;
                 examClassResult.studentIds = classStuIds;
                 //每次人数累加得到实际总人数
                 Count += Stus;
                 if (m == 0)
                 {
                     Strat = Stus;
                     Range[0] = 0;
                     Range[1] = Stus - 1;
                 }
                 else
                 {
                     Range[0] = Count - Stus;
                     Range[1] = Count - 1;
                 }

                 map.Add(key, Range);
                 Classes.Add(map);
                 m++;
                 //初始化每个班级人数
                 Stus = 0;
                 examClassResults.Add(examClassResult);
                 //ClassPoint.Add(StuPoint);
             });
             examAnswer.answer = stuAnswers;
             //examAnswer.code = examInfo.examCode;
             //paper.code = examInfo.examCode;
             //simple.code = examInfo.examCode;
             //simple.classes = Classes;
             //simple.ids = StuIds;
             simple.point = points;
             //.result = StuPo;int
             simple.subjectId = paper.subjectId;
             ResponseBuilder builder = ResponseBuilder.custom();
             Dictionary<string, object> keyValues = new Dictionary<string, object> {
                 { "schoolInfo",sc},
                 { "classInfo",classrooms},
                 { "examInfo",examInfo},
                 { "students",students},
                 { "paperInfo",paper},
                 { "examResult",simple},
                 { "examAnswer",examAnswer}
             };
             //AzureBlobModel modle = await _azureStorage.UploadFileByContainer("hbcn", keyValues.ToJsonString(), "exam", sc.schoolCode + examInfo.examCode + paper.subjectCode + ".json");
             //examInfo.blobUrl = modle.BlobUrl;
             //判定是否存储考试基本信息
             Dictionary<string, object> sub = new Dictionary<string, object>
                     {
                         { "id",  examInfo.id}
                     };
             List<ExamInfo> eInfo = await _azureCosmos.FindByDict<ExamInfo>(sub);
             if (eInfo.Count > 0)
             {
                 eInfo.ForEach(e =>
                 {
                     e.subjects.ForEach(s => {
                         if (s.id.Equals(paper.subjectId))
                         {
                             builder.Data("").build();
                         }
                         else {
                             Subject sub = new Subject();
                             sub.id = paper.subjectId;
                             sub.name = paper.subjectName;
                             e.subjects.Add(sub);
                         }                    
                     });
                     *//*if (e.subjects.na.Contains(paper.subjectId))
                     {
                         builder.Data("").build();
                     }
                     else
                     {
                         e.conditions.subject.Add(paper.subjectId);
                         e.blobUrl.Add(modle.BlobUrl);
                     }*//*
                 });
                 //await _azureCosmos.SaveOrUpdateAll(eInfo);
                 await _azureCosmos.SaveOrUpdateAll(examClassResults);
             }
             else
             {
                 examInfo.blobUrl = new List<string> { modle.BlobUrl };
                 await _azureCosmos.SaveOrUpdate(examInfo);
             }


             //Redis处理考试结果数据集合
             if (RedisHelper.Instance != null)
             {
                 await RedisHelper.HSetAsync(CacheCosmosPrefix + "examResult" + simple.subjectId, ShaHashHelper.GetSHA1(examInfo.id), simple);
                 await RedisHelper.HSetAsync(CacheCosmosPrefix + "students", ShaHashHelper.GetSHA1(sc.id), students);
                 await RedisHelper.HSetAsync(CacheCosmosPrefix + "paperInfo" + simple.subjectId, ShaHashHelper.GetSHA1(examInfo.id), paper);
                 await RedisHelper.HSetAsync(CacheCosmosPrefix + "examAnswer" + simple.subjectId, ShaHashHelper.GetSHA1(examInfo.id), examAnswer);
                 await RedisHelper.HSetAsync(CacheCosmosPrefix + "classInfo", ShaHashHelper.GetSHA1(sc.id), classrooms);
                 await RedisHelper.HSetAsync(CacheCosmosPrefix + "schoolInfo", ShaHashHelper.GetSHA1(sc.id), sc);
             }

             //_examInfoService.SaveToCosmos(simple);
             //_cosmosrepository.Save(sc);
             //await _azureCosmos.Save(simple);
             //await _azureCosmos.Save(examAnswer);
             //_cosmosrepository.SaveAll(classrooms);
             //_cosmosrepository.SaveOrUpdateAll(students);
             //_examInfoService.SaveListToCosmos(students);


             return builder.Data(sc).build();
             //return builder.build();
         }*/


        // TODO 前端没在用
        //[HttpGet("SaveObjectAdas")]
        //public async Task<BaseResponse> SaveObjectAdasAsync(string identity)

        //{
        //    // 获取系统路径
        //    string contentRootPath = _hostingEnvironment.ContentRootPath;
        //    identity = "IES/19910";
        //    //string query = "$.info";
        //    //int countClasses = 0; 
        //    //string queryClass = "$member.1.item_answer[*]";
        //    string query = "$.exercises[*]";
        //    //string queryInfo = "$.info";
        //    string queryPoint = "$.testpaper.items[*]";
        //    string queryInfo = "$.testpaper.info";
        //    string querySchoolInfo = "$.exercises[*].info";
        //    string data = FileTool.getJson(contentRootPath, identity);
        //    data = FileTool.UnicodeToString(data);
        //    JsonElement parsedJson = JsonExtensions.ToObject<JsonElement>(data);
        //    JsonPathContext context = new JsonPathContext
        //    { ValueSystem = new JsonApiValueSystem() };
        //    //解析试卷作答详情
        //    List<dynamic> papers = context.SelectNodes(parsedJson,
        //    query).Select(node => node.Value).ToList();
        //    //解析试卷基本信息
        //    List<dynamic> info = context.SelectNodes(parsedJson,
        //    queryInfo).Select(node => node.Value).ToList();
        //    //解析题库信息
        //    List<dynamic> Itempoint = context.SelectNodes(parsedJson,
        //    queryPoint).Select(node => node.Value).ToList();
        //    //解析学校信息
        //    List<dynamic> SchoolInfo = context.SelectNodes(parsedJson,
        //   querySchoolInfo).Select(node => node.Value).ToList();

        //    int m = 0;
        //    //人数总和
        //    int Count = 0;
        //    //起始坐标
        //    int Strat = 0;
        //    // 初始化学生人数
        //    int Stus = 0;
        //    ExamResultDto simple = new ExamResultDto();
        //    ExamAnswer examAnswer = new ExamAnswer();

        //    List<OldStudent> students = new List<OldStudent>();
        //    List<Class> classrooms = new List<Class>();
        //    //List<ExamAnswer> examAnswers = new List<ExamAnswer>();
        //    List<List<List<int>>> ClassPoint = new List<List<List<int>>>();
        //    List<List<double>> StuPoint = new List<List<double>>();
        //    List<string> StuIds = new List<string>();
        //    List<List<string>> stuAnswers = new List<List<string>>();
        //    List<Dictionary<string, int[]>> Classes = new List<Dictionary<string, int[]>>();
        //    Dictionary<object, object> ListInfo = new Dictionary<object, object>();
        //    List<double> points = new List<double>();
        //    //配分数组
        //    PaperDto paper = new PaperDto();
        //    List<ItemInfoDto> items = new List<ItemInfoDto>();
        //    int k = 0;
        //    Itempoint.ForEach(p =>
        //    {
        //        p.TryGetProperty("point", out JsonElement point);
        //        p.TryGetProperty("options", out JsonElement options);
        //        string pt = point.ToString();
        //        string OpenTracing = p + "";
        //        //JObject jArray = JObject.Parse(OpenTracing);
        //        JsonElement jArray = JsonExtensions.ToObject<JsonElement>(OpenTracing);
        //        jArray.TryGetProperty("options", out JsonElement op);
        //        //string[] aa = op.ToString().Split("\": {");
        //        int count = op.ToString().Count(s => s == '_');
        //        //count.TryGetInt32(out int length);
        //        List<CodeValue> codeValues = new List<CodeValue>();
        //        for (int i = 1; i <= count; i++)
        //        {
        //            string queryOptions = "$." + i + "";
        //            List<dynamic> itemOption = context.SelectNodes(op,
        //            queryOptions).Select(node => node.Value).ToList();
        //            itemOption.ToList<dynamic>().ForEach(i =>
        //            {
        //                i.TryGetProperty("option_idx", out JsonElement option);
        //                i.TryGetProperty("data", out JsonElement data);
        //                CodeValue code = new CodeValue
        //                {
        //                    code = option.ToString(),
        //                    value = data.ToString()
        //                };
        //                codeValues.Add(code);
        //            });
        //        }

        //        //题序
        //        p.TryGetProperty("itemindex", out JsonElement itemindex);
        //        //p.TryGetProperty("edu_goal", out JsonElement edu_goal);
        //        p.TryGetProperty("answer", out JsonElement answer);
        //        p.TryGetProperty("idx_desc", out JsonElement idx_desc);
        //        p.TryGetProperty("content", out JsonElement content);
        //        p.TryGetProperty("type", out JsonElement type);
        //        p.TryGetProperty("edu_goal", out JsonElement field);
        //        p.TryGetProperty("explain", out JsonElement explain);
        //        string order = itemindex.ToString();
        //        string ans = answer.ToString();
        //        string knowlege = idx_desc.ToString();
        //        ItemInfoDto item = new ItemInfoDto
        //        {
        //            question = content.ToString(),
        //            score = double.Parse(pt),
        //            answer = new List<string> {
        //                ans
        //            },
        //            type = StringHelper.getTypeName(type.ToString()),
        //            order = int.Parse(order),
        //            //level = p.edu_goal,                            
        //            option = codeValues,
        //            field = StringHelper.getEduName(field.ToString()),
        //            explain = explain.ToString(),
        //            points = new List<string> {
        //                knowlege
        //            }


        //        };
        //        items.Add(item);
        //        k++;
        //        points.Add(double.Parse(pt.Trim()));
        //    });
        //    //处理试卷信息
        //    paper.item = items;
        //    //paper.subjectCode = "Subject_Math";
        //    //基本信息
        //    info.ForEach(e =>
        //    {
        //        e.TryGetProperty("name", out JsonElement test_name);
        //        e.TryGetProperty("test_date", out JsonElement test_date);
        //        e.TryGetProperty("subject", out JsonElement subject);
        //        e.TryGetProperty("subject_code", out JsonElement subject_code);
        //        //e.TryGetProperty("test_name", out JsonElement test_name);
        //        simple.name = test_name.ToString();
        //        simple.time = test_date.ToString();
        //        paper.name = test_name.ToString();
        //        paper.subjectCode = subject_code.ToString();
        //    });


        //    School sc = new School();
        //    ExamInfoDto examInfo = new ExamInfoDto();
        //    SchoolInfo[0].TryGetProperty("ex_no", out JsonElement exam_no);
        //    SchoolInfo[0].TryGetProperty("ex_time", out JsonElement ex_time);
        //    SchoolInfo[0].TryGetProperty("ex_endtime", out JsonElement ex_endtime);
        //    SchoolInfo[0].TryGetProperty("school_name", out JsonElement school_name);
        //    SchoolInfo[0].TryGetProperty("school_code", out JsonElement school_code);
        //    SchoolInfo[0].TryGetProperty("ex_name", out JsonElement ex_name);
        //    SchoolInfo[0].TryGetProperty("ex_type", out JsonElement ex_type);
        //    SchoolInfo[0].TryGetProperty("grade_name", out JsonElement grade_name);
        //    SchoolInfo[0].TryGetProperty("semester", out JsonElement semester);
        //    SchoolInfo[0].TryGetProperty("period_name", out JsonElement period_name);
        //    SchoolInfo[0].TryGetProperty("period_code", out JsonElement period_code);
        //    SchoolInfo[0].TryGetProperty("class_code", out JsonElement class_code);
        //    SchoolInfo[0].TryGetProperty("grade_code", out JsonElement grade_code);
        //    string st = ex_time.ToString();
        //    string ed = ex_endtime.ToString();
        //    DateTime.TryParse(st, out DateTime tt);
        //    DateTime.TryParse(ed, out DateTime etime);
        //    long time = DateTimeHelper.ToUnixTimestamp(tt);
        //    long edtime = DateTimeHelper.ToUnixTimestamp(etime);

        //    sc.schoolCode = school_code.ToString();
        //    sc.name = school_name.ToString();
        //    sc.period = new List<Period> { new Period {name = period_name.ToString() , id = period_code.ToString(),grades= new List<Grade> {
        //            new Grade { name = grade_name.ToString() ,id = grade_code.ToString()} } } };

        //    //考试基本信息
        //    examInfo.id = _snowflakeId.NextId() + "";
        //    examInfo.code = school_code.ToString();
        //    examInfo.name = ex_name.ToString();
        //    examInfo.type = ex_type.ToString();
        //    examInfo.examCode = exam_no.ToString();
        //    examInfo.startTime = time;
        //    examInfo.endTime = edtime;
        //    examInfo.conditions = new Condition
        //    {
        //        period = period_code.ToString(),
        //        grade = grade_code.ToString(),
        //        semester = semester.ToString(),
        //        subject = new List<string> { paper.subjectCode }
        //    };
        //    SchoolInfo.ForEach(s =>
        //    {
        //        s.TryGetProperty("stucount", out JsonElement stucount);
        //        string count = stucount.ToString();
        //        examInfo.stuCount += int.Parse(count);
        //    });
        //    papers.ForEach(x =>
        //    {
        //        x.TryGetProperty("info", out JsonElement info);
        //        //var c = papers[i].member;
        //        info.TryGetProperty("stucount", out JsonElement stucount);
        //        info.TryGetProperty("course_name", out JsonElement class_name);
        //        info.TryGetProperty("course_no", out JsonElement class_code);
        //        info.TryGetProperty("school_name", out JsonElement school_name);
        //        string stu = stucount.ToString();
        //        int k = int.Parse(stu);
        //        string key = class_name.ToString();
        //        string schoolName = school_name.ToString();
        //        Class classInfo = new Class
        //        {
        //            //id = _snowflakeId.NextId() + "",
        //            name = key,
        //            //classroomType = schoolName,
        //            //studentCount = k,
        //            id = class_code.ToString()
        //        };
        //        classrooms.Add(classInfo);
        //        Class classInfoOfStudent = new Class
        //        {
        //            name = key,
        //            //schoolCode = schoolName,
        //            //studentCount = k,
        //            id = class_code.ToString()
        //        };
        //        Dictionary<string, int[]> map = new Dictionary<string, int[]>();
        //        int[] Range = new int[2];
        //        //处理学生作答数据

        //        x.TryGetProperty("members", out JsonElement members);
        //        for (int j = 0; j < k; j++)
        //        {
        //            OldStudent stus = new OldStudent
        //            {
        //                type = 2,
        //                //schoolCode = schoolName
        //            };
        //            string men = members[j] + "";
        //            JsonElement jArray = JsonExtensions.ToObject<JsonElement>(men);
        //            //JObject jArray = JObject.Parse(men);
        //            string queryClass = "$.item_answers[*]";
        //            string queryStu = "$.info";
        //            List<string> ans = new List<string>();
        //            List<dynamic> answers = context.SelectNodes(jArray,
        //            queryClass).Select(node => node.Value).ToList();
        //            //学生ID集合
        //            List<dynamic> studentIds = context.SelectNodes(jArray,
        //            queryStu).Select(node => node.Value).ToList();
        //            List<double> point = new List<double>();
        //            if (answers.Count == 0)
        //            {
        //                StuIds.Add("0");
        //                k++;
        //            }
        //            else
        //            {
        //                //处理学生信息
        //                studentIds.ToList<dynamic>().ForEach(s =>
        //                {
        //                    s.TryGetProperty("student_id", out JsonElement student_id);
        //                    s.TryGetProperty("name", out JsonElement name);
        //                    s.TryGetProperty("seatno", out JsonElement seatno);
        //                    string id = student_id.ToString();
        //                    //id = System.Guid.NewGuid().ToString();
        //                    stus.id = id.Trim();
        //                    stus.name = name.ToString();
        //                    stus.studentId = id.Trim();
        //                    string sno = seatno.ToString();
        //                    if (sno.Equals(""))
        //                    {
        //                        stus.seatNo = 0;
        //                    }
        //                    else
        //                    {
        //                        stus.seatNo = int.Parse(sno);
        //                    }

        //                    //stus.classroom = classInfoOfStudent;
        //                    StuIds.Add(id.Trim());
        //                });
        //                students.Add(stus);
        //            }

        //            answers.ToList<dynamic>().ForEach(p =>
        //            {
        //                p.TryGetProperty("real_point", out JsonElement real_point);
        //                p.TryGetProperty("ans_content", out JsonElement ans_content);
        //                string pt = real_point.ToString();
        //                string ansContent = ans_content.ToString();
        //                if (ans.Equals(""))
        //                {
        //                    ansContent = "无";
        //                }
        //                ans.Add(ansContent);
        //                point.Add(double.Parse(pt.Trim()));
        //            });
        //            stuAnswers.Add(ans);
        //            StuPoint.Add(point);
        //            Stus++;
        //        }
        //        //每次人数累加得到实际总人数
        //        Count += Stus;
        //        if (m == 0)
        //        {
        //            Strat = Stus;
        //            Range[0] = 0;
        //            Range[1] = Stus - 1;
        //        }
        //        else
        //        {
        //            Range[0] = Count - Stus;
        //            Range[1] = Count - 1;
        //        }

        //        map.Add(key, Range);
        //        Classes.Add(map);
        //        m++;
        //        //初始化每个班级人数
        //        Stus = 0;

        //        //ClassPoint.Add(StuPoint);
        //    });
        //    examAnswer.answer = stuAnswers;
        //    examAnswer.code = examInfo.examCode;
        //    paper.code = examInfo.examCode;
        //    simple.code = examInfo.examCode;
        //    simple.classes = Classes;
        //    simple.ids = StuIds;
        //    simple.point = points;
        //    simple.result = StuPoint;
        //    simple.subjectCode = paper.subjectCode;
        //    ResponseBuilder builder = ResponseBuilder.custom();
        //    Dictionary<string, object> keyValues = new Dictionary<string, object> {
        //        { "schoolInfo",sc},
        //        { "classInfo",classrooms},
        //        { "examInfo",examInfo},
        //        { "students",students},
        //        { "paperInfo",paper},
        //        { "examResult",simple},
        //        { "examAnswer",examAnswer}
        //    };
        //    AzureBlobModel modle = await _azureStorage.UploadFileByContainer("hbcn", keyValues.ToJsonString(), "exam", sc.schoolCode + examInfo.examCode + paper.subjectCode + ".json");
        //    //examInfo.blobUrl = modle.BlobUrl;
        //    //判定是否存储考试基本信息
        //    Dictionary<string, object> sub = new Dictionary<string, object>
        //            {
        //                { "examCode",  examInfo.examCode}
        //            };
        //    List<ExamInfoDto> eInfo = await _azureCosmos.FindByDict<ExamInfoDto>(sub);
        //    if (eInfo.Count > 0)
        //    {
        //        eInfo.ForEach(e =>
        //        {
        //            if (e.conditions.subject.Contains(paper.subjectCode))
        //            {
        //                builder.Data("").build();
        //            }
        //            else
        //            {
        //                e.conditions.subject.Add(paper.subjectCode);
        //                e.blobUrl.Add(modle.BlobUrl);
        //            }
        //        });
        //        await _azureCosmos.SaveOrUpdateAll(eInfo);
        //    }
        //    else
        //    {
        //        examInfo.blobUrl = new List<string> { modle.BlobUrl };
        //        await _azureCosmos.SaveOrUpdate(examInfo);
        //    }


        //    //Redis处理考试结果数据集合
        //    if (RedisHelper.Instance != null)
        //    {
        //        await RedisHelper.HSetAsync(CacheCosmosPrefix + "examResult" + simple.subjectCode, ShaHashHelper.GetSHA1(examInfo.examCode), simple);
        //        await RedisHelper.HSetAsync(CacheCosmosPrefix + "students", ShaHashHelper.GetSHA1(sc.schoolCode), students);
        //        await RedisHelper.HSetAsync(CacheCosmosPrefix + "paperInfo" + simple.subjectCode, ShaHashHelper.GetSHA1(examInfo.examCode), paper);
        //        await RedisHelper.HSetAsync(CacheCosmosPrefix + "examAnswer" + simple.subjectCode, ShaHashHelper.GetSHA1(examInfo.examCode), examAnswer);
        //        await RedisHelper.HSetAsync(CacheCosmosPrefix + "classInfo", ShaHashHelper.GetSHA1(sc.schoolCode), classrooms);
        //        await RedisHelper.HSetAsync(CacheCosmosPrefix + "schoolInfo", ShaHashHelper.GetSHA1(sc.schoolCode), sc);
        //    }

        //    //_examInfoService.SaveToCosmos(simple);
        //    //_cosmosrepository.Save(sc);
        //    //_cosmosrepository.Save(simple);
        //    //_cosmosrepository.Save(examAnswer);
        //    //_cosmosrepository.SaveAll(classrooms);
        //    //_cosmosrepository.SaveOrUpdateAll(students);
        //    //_examInfoService.SaveListToCosmos(students);


        //    return builder.Data(sc).build();
        //    //return builder.build();
        //}




        // TODO 前端没在用，导入在用，重做
        //[HttpGet("SaveExamToBlob")]
        //public async Task<BaseResponse> SendExam(JosnRequest<Dictionary<string, object>> request)
        //{
        //    ResponseBuilder builder = ResponseBuilder.custom();
        //    OldStudent student = null;
        //    List<OldStudent> AnalysisStudents = new List<OldStudent>();
        //    ExamInfoDto examInfo = null;
        //    ExamResult result = null;
        //    if (request.@params.TryGetValue("id", out object id) && request.@params.TryGetValue("pk", out object pk))
        //    {
        //        examInfo = await _azureCosmos.FindByIdPk<ExamInfoDto>(id.ToString(), pk.ToString());
        //        //获取发布对象
        //        if (request.@params.TryGetValue("schoolCode", out object schoolCode))
        //        {
        //            List<string> targetCode = examInfo.target;
        //            List<ClassStudent> classroomStudents = await _azureCosmos.FindByDict<ClassStudent>(new Dictionary<string, object> { { "id", targetCode } });
        //            List<OldStudent> students = await _azureCosmos.FindByDict<OldStudent>(
        //                new Dictionary<string, object>() { { "classroomCode", targetCode }, { "code", schoolCode } },
        //                new List<string> { "id", "name", "code", "seatNo", "studentId", "classroomCode" });
        //            List<dynamic> stus = new List<dynamic>();
        //            List<ClassStudent> newClassStudents = new List<ClassStudent>();
        //            ///新增的学生
        //            if (students.IsNotEmpty())
        //            {
        //                students.ForEach(x =>
        //                {
        //                    if (!classroomStudents.Select(m => m.code).Contains(x.studentId))
        //                    {
        //                        newClassStudents.Add(new ClassStudent() { id = x.classroomCode, code = x.studentId });
        //                    }
        //                    var stu = new { x.id, x.name, x.code, x.seatNo, x.studentId, x.classroomCode };
        //                    stus.Add(stu);
        //                });
        //            }
        //            ///反射已存在的id信息
        //            if (classroomStudents.IsNotEmpty())
        //            {
        //                ///处理冗余的id查询
        //                List<string> ids = new List<string>();
        //                classroomStudents.ForEach(x =>
        //                {
        //                    if (!students.Select(m => m.studentId).Contains(x.code))
        //                    {
        //                        ids.Add(x.code);
        //                    }
        //                });
        //                var sts = await _azureCosmos.FindByDict<OldStudent>(new Dictionary<string, object>() { { "studentId", ids.ToArray() } });
        //                if (sts.IsNotEmpty())
        //                {
        //                    sts.ForEach(x =>
        //                    {
        //                        var stu = new { x.id, x.name, x.code, x.seatNo, x.studentId, x.classroomCode };
        //                        stus.Add(stu);
        //                    });
        //                }

        //            }
        //            //保存新增学生
        //            if (newClassStudents.IsNotEmpty())
        //            {
        //                classroomStudents.AddRange(await _azureCosmos.SaveOrUpdateAll(newClassStudents));
        //            }

        //            //处理学生信息以便学情使用
        //            int n = 1;
        //            stus.ForEach(s =>
        //            {
        //                student = new OldStudent
        //                {
        //                    id = s[0],
        //                    name = s[1],
        //                    studentId = s[4],
        //                    seatNo = n,
        //                    classroomCode = s[5]

        //                };
        //                n++;
        //                AnalysisStudents.Add(student);
        //            });
        //            //依次处理班级信息
        //            targetCode.ForEach(c =>
        //            {
        //                int count = 0;
        //                AnalysisStudents.ForEach(s =>
        //                {
        //                    if (c.Equals(s.classroomCode))
        //                    {
        //                        count++;
        //                    }
        //                    //处理学生作答以及学生得分记录
        //                });

        //            });
        //            result = new ExamResult
        //            {
        //                code = examInfo.id,
        //                name = examInfo.name,

        //            };

        //            //return builder.Data(classroomStudents).Extend(new Dictionary<string, object> { { "students", stus }, { "count", stus.Count } }).build();
        //        }
        //        else
        //        {
        //            return builder.build();
        //        }
        //    }
        //    else
        //    {
        //        return builder.build();
        //    }
        //    return builder.Data("").build();
        //}
    }
}
