using Azure;
using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using HTEXLib.COMM.Helpers;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("common/volume")]
    [ApiController]
    public class VolumeController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly DingDing _dingDing;
        private readonly Option _option;

        public VolumeController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value; ;
        }
        /*
        {
            "id": "册别id",
            "code": "学校编码/教师编码",
            "scope": "school/private"
        }
         */
        /// <summary>
        /// 删除册别
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                string sql =$"select value(c) from c where c.volumeId='{id}'";
                List<Syllabus> syllabus = new List<Syllabus>();
                if (scope.ToString().Equals("school"))
                {
                    var response = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Volume-{code}"));
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Syllabus>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{code}") })) {
                        syllabus.Add(item);
                    }
                    if (syllabus.IsNotEmpty())
                    {
                        foreach (var s in syllabus) {
                            if (s.auth.IsNotEmpty()) {
                                foreach (var a in s.auth) {
                                    try {
                                        Share share = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Share>(s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
                                        share.agree = -1;
                                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Share>(share,s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
                                    } catch (Exception ex) {
                                        ///仅用于处理查不到该数据的问题
                                    }
                                }
                            }
                        }
                        var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsStreamAsync(syllabus.Select(x => x.id).ToList(), $"Syllabus-{code}");
                    }
                    return Ok(new { code = response.Status });
                }
                else
                {
                    var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Volume-{code}"));
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Syllabus>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{code}") }))
                    {
                        syllabus.Add(item);
                    }
                    if (syllabus.IsNotEmpty())
                    {
                        foreach (var s in syllabus)
                        {
                            if (s.auth.IsNotEmpty())
                            {
                                foreach (var a in s.auth)
                                {
                                    try
                                    {
                                        Share share = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Share>(s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
                                        share.agree = -1;
                                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Share>(share, s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
                                    }
                                    catch (Exception ex)
                                    {
                                        ///仅用于处理查不到该数据的问题
                                    }
                                }
                            }
                        }
                        var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(syllabus.Select(x => x.id).ToList(), $"Syllabus-{code}");
                    }
                    return Ok(new { code = response.Status });
                }
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，VolumeController:Delete\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }
        /*
        {
            "periodId": "学段id",
            "subjectId": "科目id",//
            "status": 1,//状态
            "code": "学校编码或者tmdid",
            "scope": "school/private"  如果是私人课纲 则学段科目id可以为空
        }
         */
        /// <summary>
        /// 查找册别
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find")]

        public async Task<IActionResult> Find(JsonElement request) {
            try {
                List<Volume> volumes = new List<Volume>();
                request.TryGetProperty("periodId", out JsonElement periodCode);
                request.TryGetProperty("subjectId", out JsonElement subjectCode);
                request.TryGetProperty("status", out JsonElement status);
                if (request.TryGetProperty("code", out JsonElement code))
                {
                    request.TryGetProperty("scope", out JsonElement scope);
                    //私有课纲
                    if (scope.GetString() .Equals("private"))
                    {
                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Volume>(queryText: $"select value(c) from c where c.status = {status}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{code}") }))
                        {
                            volumes.Add(item);
                        }
                    }
                    else if (scope.GetString() .Equals("school"))
                    {
                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Volume>(queryText: $"select value(c) from c where c.status = {status} and c.periodId = '{periodCode}' and c.subjectId = '{subjectCode}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{code}") }))
                        {
                            volumes.Add(item);
                        }
                    }
                }
                else { return BadRequest(); };
                return Ok(new { volumes });
            } catch (Exception ex) {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，VolumeController:find\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }

        /*
         
        {
            "id": "册别id",
            "code": "学校编码或教师id",
            "periodId": "学段id",
            "subjectId": "学科id",
            "gradeId": "年级id",
            "semesterId": "学期id",
            "status": 1,
            "name": "册别名",
            "creatorId": "创建者id",
            "school": "学校编码",
            "scope": "school|private"
        }
         */

        /// <summary>
        /// 新增册别
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert")]
        public async Task<IActionResult> Upsert(Volume request) {

            //var client = _azureCosmos.GetCosmosClient();
            //if (request.editors != null && request.editors.Count > 5)
            //{
            //    return BadRequest("共编人数大于5人！");
            //    // throw new BizException("共编人数大于5人！");
            //}
            request.pk = "Volume";
            request.ttl = -1;
            request.code = "Volume-" + request.code;
            // 检查册别条件相同的是否存在
            
            string code = "Volume-";
            if (request.scope.Equals("private"))
            {
                code = $"Volume-{request.creatorId}";
            }
            else if (request.scope.Equals("school"))
            {
                code = $"Volume-{request.school}";
            }
           
            request.code = code;
            ///表示更新
            if (!string.IsNullOrEmpty(request.id))
            {
                try {
                    if (request.scope.Equals("school"))
                    {
                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Volume>(request, request.id, new Azure.Cosmos.PartitionKey(request.code));
                    }
                    else if (request.scope.Equals("private")) {
                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Volume>(request, request.id, new Azure.Cosmos.PartitionKey(request.code));
                    }
                      
                }
                catch (Exception  ex) {
                    return BadRequest(new { error = ResponseCode.FAILED });
                }
            }
            //表示新增，则需要检查是否重复
            else {
                try
                {
                    StringBuilder sql = new StringBuilder("select value(c) from c where c.status = 1 ");
                    //私人课纲 只检查是否重名
                    if (request.scope.Equals("private"))
                    {
                        sql.Append($" and c.name = '{request.name}' ");
                        List<Volume> volumes = new List<Volume>();
                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher")
                        .GetItemQueryIterator<Volume>(queryText: sql.ToString(), requestOptions: new Azure.Cosmos.QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey(request.code) }))
                        {
                            volumes.Add(item);
                        }
                        if (volumes.Count > 0)
                        {
                            return Ok(new { error = ResponseCode.DATA_EXIST });
                        }
                    }
                    //学校课纲检查 学段 科目 年级 学期
                    else if (request.scope.Equals("school")
                        && !string.IsNullOrEmpty(request.periodId)
                        && !string.IsNullOrEmpty(request.subjectId)
                        && request.gradeId>=0
                        && !string.IsNullOrEmpty(request.semesterId))
                    {
                        sql.Append($" and c.periodId = '{request.periodId}' and  c.subjectId = '{request.subjectId}'" +
                            $" and c.gradeId = {request.gradeId} and c.semesterId = '{request.semesterId}' and c.name = '{request.name}' ");
                        List<Volume> volumes = new List<Volume>();
                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
                        .GetItemQueryIterator<Volume>(queryText: sql.ToString(), requestOptions: new Azure.Cosmos.QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey(request.code) })) {
                            volumes.Add(item);
                        }
                        if (volumes.Count>0)
                        {
                            return Ok(new { error = ResponseCode.DATA_EXIST });
                        }
                    }
                    else {
                        return BadRequest(new { error = ResponseCode.PARAMS_ERROR });
                    }
                    
                    request.id = System.Guid.NewGuid().ToString();
                    if (request.scope.Equals("private"))
                    {
                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync(request, new PartitionKey(request.code));
                    }
                    else {
                        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(request, new PartitionKey(request.code));
                    }
                }
                catch (Exception ex)
                {
                    await _dingDing.SendBotMsg($"OS，{_option.Location}，VolumeController:Upsert\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                }
            }
            ///处理更新 分享及共编的数据
            //if (request.auth.IsNotEmpty()) {
            //    long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            //    foreach (var au in request.auth) {
            //      var share=  new Share
            //        {
            //            id = request.id,
            //            code = $"Share-{au.tmdid}",
            //            pk = "Share",
            //            ttl = -1,
            //            scode=request.code,
            //            issuer=request.creatorId,
            //            createTime= now,
            //            school=request.school,
            //            scope=request.scope
            //        };
            //        await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(share, new PartitionKey($"{share.code}"));
            //    }
            //}
            return Ok(request);
        }
    }
}
