using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TEAMModelOS.Service.Models.Core;
using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Module.AzureCosmosDB.Interfaces;
using System.Text.Json;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.Extension.SnowFlake;
using TEAMModelOS.SDK.Helper.Security.TmdCrypt;

namespace TEAMModelOS.Controllers.Syllabus
{
    [Route("api/[controller]")]
    [ApiController]
    // [Authorize]
    public class StudentController : BaseController
    {
        private readonly IAzureCosmosDBRepository azureCosmosDBRepository;
        public StudentController(IAzureCosmosDBRepository _azureCosmosDBRepository)
        {
            azureCosmosDBRepository = _azureCosmosDBRepository;
        }

        [HttpPost("SaveStudent")]
        public async Task<BaseJosnRPCResponse> SaveStudentInfo(JosnRPCRequest<Student> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            //设置密码 isSet 是否加密 如果加密则不会再次加密
            if (!request.@params.password.isSet)
            {
                request.@params.password.value = TmdCrypt.Encrypt(request.@params.password.value);
                request.@params.password.isSet = true;
            }
            Student data = await azureCosmosDBRepository.Save<Student>(request.@params);
            return builder.Data(data).build();
        }


        [HttpPost("FindStudent")]
        public async Task<BaseJosnRPCResponse> FindStudent(JosnRPCRequest<Dictionary<string, object>> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            if (request.@params.TryGetValue("schoolCode", out object _))
            {
                List<Student> data = await azureCosmosDBRepository.FindByDict<Student>(request.@params,false);
                return builder.Data(data).build();
            }
            else
            {
                return builder.Error("schoolCode  is null !").build();
            }
        }
        [HttpPost("SaveAllStudent")]
        public async Task<BaseJosnRPCResponse> SaveAllStudentInfo(JosnRPCRequest<List<StudentDto>> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            Dictionary<string, List<StudentDto>> dictInfo = new Dictionary<string, List<StudentDto>>();
            foreach (IGrouping<string, StudentDto> group in request.@params.GroupBy(c => c.classroomCode))
            {
                dictInfo.Add(group.Key, group.ToList());
            }
            List<Student> students = new List<Student>();
            foreach (string key in dictInfo.Keys)
            {
                List<Classroom> classrooms = await azureCosmosDBRepository.FindByParams<Classroom>(new Dictionary<string, object> { { "classroomCode", key } });
                if (classrooms.IsNotEmpty())
                {
                    long createDate = DateTimeOffset.UtcNow.Ticks;
                    dictInfo.TryGetValue(key, out List<StudentDto> sts);
                    List<long>  ids= IdWorker.getIdsByCount(sts.Count);
                    sts.ForEach(x => {
                        Student student = new Student
                        {
                            schoolCode = classrooms[0].schoolCode,
                            id = x.schoolCode + x.studentId,
                            TEAMModelId = x.schoolCode + "#" + x.studentId,
                            virtualId = x.schoolCode + "#" + x.studentId,
                            createDate = createDate
                        };
                        //设置密码 isSet 是否加密 如果加密则不会再次加密
                        if (!x.password.isSet) {
                            student.password.value = TmdCrypt.Encrypt(x.password.value);
                            student.password.isSet = true;
                        }
                        Classroom classroom = new Classroom
                        {
                            classroomCode = x.classroomCode,
                            gradeCode = classrooms[0].gradeCode,
                            periodCode = classrooms[0].periodCode,
                            schoolCode = classrooms[0].schoolCode,
                        };
                        student.classroom = classroom;
                        students.Add(student);
                    });
                    await azureCosmosDBRepository.SaveAll(students);
                }
            }
            return builder.Data(students).build();
        }

        [HttpPost("UpdateStudent")]
        public async Task<BaseJosnRPCResponse> UpdateStudent(JosnRPCRequest<StudentDto> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            //设置密码 isSet 是否加密 如果加密则不会再次加密
            if (!request.@params.password.isSet)
            {
                request.@params.password.value = TmdCrypt.Encrypt(request.@params.password.value);
                request.@params.password.isSet = true;
            }
            Student data = await azureCosmosDBRepository.Update<Student>(request.@params);
            return builder.Data(data).build();
        }
        [HttpPost("UpdateAllStudent")]
        public async Task<BaseJosnRPCResponse> DeleteALlStudentInfo(JosnRPCRequest<Dictionary<string, Dictionary<string, object>>> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            bool find = request.@params.TryGetValue("find", out Dictionary<string, object> findObj);
            bool update = request.@params.TryGetValue("update", out Dictionary<string, object> updateObj);
            List<Student> data = null;
            if (find && update)
            {
                data = await azureCosmosDBRepository.UpdateAll<Student>(findObj, updateObj);
            }
            return builder.Data(data).build();
        }
        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("DeleteStudent")]
        public async Task<BaseJosnRPCResponse> DeleteStudentInfo(JosnRPCRequest<Student> request)
        {
            JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
            string data = await azureCosmosDBRepository.DeleteAsync<Student>(request.@params.id, request.@params.schoolCode);
            return builder.Data(data).build();
        }
    }
}
