using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using TEAMModelOS.Services.Common;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using Azure;

namespace TEAMModelOS.Controllers.Common
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("sheet-config")]
    [ApiController]
    public class SheetConfigController : ControllerBase
    {
        private readonly AzureRedisFactory _azureRedis;
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly AzureServiceBusFactory _serviceBus;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureStorageFactory _azureStorage;
        public SheetConfigController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option,
            AzureRedisFactory azureRedis, AzureStorageFactory azureStorage)
        {
            _azureCosmos = azureCosmos;
            _serviceBus = serviceBus;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value;
            _azureRedis = azureRedis;
            _azureStorage = azureStorage;
        }
        /// <summary>
        ///查询答题卡
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find")]
        public async Task<IActionResult> Find(JsonElement request) {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                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();
                if ($"{scope}" .Equals("school"))
                {
                    SheetConfig config = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SheetConfig>($"{id}", new PartitionKey($"SheetConfig-{code}"));
                    return Ok(new { config = config, status = 200 });
                }
                else
                {
                    SheetConfig config = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<SheetConfig>($"{id}", new PartitionKey($"SheetConfig-{code}"));
                    return Ok(new { config = config,status=200 });
                }
            }
            catch (CosmosException e)
            {
                return Ok(new { status = e.Response.Status });
            }
            catch (Exception ex) {

                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/SheetConfig/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest(ex.StackTrace);
            }
        }

        /**
        @条件1 当examId有值，则paperId 和 owner必定有值，sheet代表一个评测下的某一个试卷的答题卡数据，且答题卡的scope对应为评测的scope,且school和creatorId 与评测保持一致，且sheet.id从前端传递来的无效，
            因为id需要根据当前评测examId的试卷绑定的答题卡覆写或者新建
            如果检测到examId下对应的试卷绑定答题卡sheet为空则新生成一个答题卡id，并自动绑定。
        @条件2 当examId没有值，且paperId有值，sheet代表一个试卷库的某一个试卷的答题卡数据，且答题卡的scope对应为试卷库paperId的scope,且school和creatorId 与评测保持一致，且sheet.id从前端传递来的无效，
            因为id需要根据试卷绑定的答题卡覆写或者新建
            如果检测到paperId的试卷绑定的答题卡sheett为空则新生成一个答题卡id，并自动绑定。如果检测aperId的试卷已经绑定答题卡，则只需要更新实时的答题卡数据。
        @条件3 当examId和paperId都没有值，sheet代表与评测，试卷库无关的答题卡数据，且答题卡的scope ，school和creatorId 根据当前创建者需要保存数据的规则有关。
            且sheet.id，如果有值则是更新答题卡内容数据。
            如果sheet.id，没有值则是新建保存答题卡数据。
        @条件4 其他情况的参数传递不予以考虑，直接返回400参数错误。
         **/
        /// <summary>
        /// 新增 或 修改答题卡
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert")]
        public async Task<IActionResult> Upsert(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("sheet", out JsonElement _sheet)) { return BadRequest(); }
                request.TryGetProperty("examId", out JsonElement _examId);
                request.TryGetProperty("paperId", out JsonElement _paperId);
                request.TryGetProperty("owner", out JsonElement _owner);
                var client = _azureCosmos.GetCosmosClient();
                SheetConfig sheet = _sheet.ToObject<SheetConfig>();
                if (sheet == null) { 
                    return BadRequest("sheet params is null!");
                }
                if (!sheet.code.StartsWith("SheetConfig-")) {
                    sheet.code = $"SheetConfig-{sheet.code}";
                }
               
                sheet.pk = $"SheetConfig";
                sheet.ttl = -1;
                string tbname = sheet.scope.Equals("school", StringComparison.OrdinalIgnoreCase)? "School": "Teacher";
                // @条件1 代表需要更新评测的某一个试卷的答题卡
                if (!_paperId.ValueKind.Equals(JsonValueKind.Null) && !_examId.ValueKind.Equals(JsonValueKind.Null) && !string.IsNullOrEmpty($"{ _examId}") && !string.IsNullOrEmpty($"{ _paperId}"))
                {
                    sheet.from = "exam";
                    string code = "";
                    if (!string.IsNullOrEmpty($"{_owner}") && $"{_owner}".Equals("school", StringComparison.OrdinalIgnoreCase)) {
                        code = $"Exam-{sheet.school}";
                        sheet.scope = "school";
                    }
                    else {
                        code = $"Exam-{sheet.creatorId}"; 
                        sheet.scope = "private";
                    }
                    try
                    {
                        ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>($"{_examId}", new PartitionKey($"{code}"));
                        var ps = exam.papers.Where(p => p.id == $"{_paperId}").FirstOrDefault();
                        if (ps != null)
                        {
                            if (string.IsNullOrEmpty(ps.sheet) || !Guid.TryParse(ps.sheet, out Guid guid))
                            {
                                sheet.id = Guid.NewGuid().ToString();
                                ps.sheet = sheet.id;
                            }
                            else {
                                sheet.id = ps.sheet;
                            }
                            if (string.IsNullOrEmpty(sheet.no)) { 
                                sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname, sheet.from); 
                            }
                            ps.sheetNo = sheet.no;
                            exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(exam, $"{_examId}", new PartitionKey($"{code}"));
                        }
                        else
                        {
                            return BadRequest($"paperId:{_paperId} is not exist!");
                        }
                    }
                    catch (Exception ex)
                    {
                        return BadRequest($"{ex.Message},examId:{_examId} is not exist!");
                    }
                }
                //  @条件2  代表需要更新或保存试卷库的某一个试卷的答题卡
                else if ((string.IsNullOrEmpty($"{ _examId}") || !_examId.ValueKind.Equals(JsonValueKind.Null))
                    && !_paperId.ValueKind.Equals(JsonValueKind.Null) && !string.IsNullOrEmpty($"{ _paperId}"))
                {
                    sheet.from = "paper";
                    string code = sheet.scope.Equals("school", StringComparison.OrdinalIgnoreCase) ? $"Paper-{sheet.school}": $"Paper-{sheet.creatorId}";
                    try
                    {
                        Paper paper = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<Paper>($"{_paperId}", new PartitionKey($"{code}"));
                        if (string.IsNullOrEmpty(paper.sheet)||!Guid.TryParse(paper.sheet,out Guid guid))
                        {
                           
                            sheet.id = Guid.NewGuid().ToString();
                            paper.sheet = sheet.id;
                           
                        }
                        else
                        {
                            sheet.id = paper.sheet;
                        }
                        if (string.IsNullOrEmpty(sheet.no)) {
                            sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname, sheet.from);
                            paper.sheetNo = sheet.no;
                        }
                        paper.sheetNo = sheet.no;
                        paper = await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<Paper>(paper, $"{_paperId}", new PartitionKey($"{code}"));

                    }
                    catch (Exception ex)
                    {
                        return BadRequest($"{ex.Message},paperId:{_paperId} is not exist!");
                    }
                }
                //@条件3 代表需要直接产生一个答题卡
                else if (string.IsNullOrEmpty($"{ _examId}") && string.IsNullOrEmpty($"{ _paperId}"))
                {
                    sheet.from = "sheet";
                    if (string.IsNullOrEmpty(sheet.id)) {
                        sheet.id = Guid.NewGuid().ToString();
                    }
                    if (string.IsNullOrEmpty(sheet.no)) {
                        sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname, sheet.from);
                    }
                }
                else {
                    //@条件4
                    return BadRequest("params is error!");
                }
                if (string.IsNullOrEmpty(sheet.no))
                {
                    sheet.no = await SheetService.genSheetNo(client, _dingDing, _option, sheet.code, tbname,sheet.from);

                }
                sheet = await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(sheet, new PartitionKey($"{sheet.code}"));
                return Ok(new { config = sheet, status=200 });
            }
            catch (CosmosException ex)
            {
                return Ok(new { status = ex.Status });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/SheetConfig/upsert()\n{e.Message}{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest(e.Message);
            }
        }

        
        /// <summary>
        ///删除答题卡
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                List<string> idslist = ids.ToObject<List<string>>();
                if ($"{scope}" .Equals("school"))
                {
                    await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsStreamAsync(idslist, $"SheetConfig-{code}");
                }
                else
                {
                    await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(idslist, $"SheetConfig-{code}");
                }
                return Ok(new { status = 404 });
            }
            catch (CosmosException ex) {
                return Ok(new { status = ex.Status });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/SheetConfig/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest(e.StackTrace);
            }
        }
    }
}
