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.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.Common;

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();
                if (scope.ToString().Equals("school"))
                {
                    var response = await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Volume-{code}"));
                    return Ok(new { code = response.Status });
                }
                else
                {
                    var response = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Volume-{code}"));
                    return Ok(new { code = response.Status });
                }
            }
            catch (Exception e)
            {
                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) {
          //  List<Syllabus> syllabuses = new List<Syllabus>();
            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()== "private")
                {
                    //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{code}") }))
                    //{
                    //    using var json = await JsonDocument.ParseAsync(item.ContentStream);
                    //    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                    //    {
                    //        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                    //        {
                    //            syllabuses.Add(obj.ToObject<Syllabus>());
                    //        }
                    //    }
                    //}
                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("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);
                        //using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        //if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        //{
                        //    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                        //    {
                        //        volumes.Add(obj.ToObject<Volume>());
                        //    }
                        //}
                    }
                }
                else if(scope.GetString() == "school") {
                    //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{code}") }))
                    //{
                    //    using var json = await JsonDocument.ParseAsync(item.ContentStream);
                    //    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                    //    {
                    //        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                    //        {
                    //            syllabuses.Add(obj.ToObject<Syllabus>());
                    //        }
                    //    }
                    //}
                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("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);

                        //using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        //if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        //{
                        //    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                        //    {
                        //        volumes.Add(obj.ToObject<Volume>());
                        //    }
                        //}
                    }
                }
             }
            else { return BadRequest(); };
            return Ok(new { volumes  });
        }

        /*
         
        {
            "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"))
                    {
                        Volume volume = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Volume>(request.id, new PartitionKey(request.code));
                        //保留授权
                        request.auth = volume.auth;
                        await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Volume>(request, request.id, new Azure.Cosmos.PartitionKey(request.code));
                    }
                    else if (request.scope.Equals("private")) {
                        Volume volume = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Volume>(request.id, new PartitionKey(request.code));
                        //保留授权
                        request.auth = volume.auth;
                        await _azureCosmos.GetCosmosClient().GetContainer("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("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("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("TEAMModelOS", "Teacher").CreateItemAsync(request, new PartitionKey(request.code));
                    }
                    else {
                        await _azureCosmos.GetCosmosClient().GetContainer("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("TEAMModelOS", "Teacher").UpsertItemAsync(share, new PartitionKey($"{share.code}"));
            //    }
            //}
            return Ok(request);
        }
    }
}
