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;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.Filter;
using HTEXLib.COMM.Helpers;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("school/debate")]
    [ApiController]
    public class DebateController: ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        public DebateController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value; ;
        }
        /// <summary>
        /// 查询所有话题
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-id")]
        public async Task<IActionResult> FindId(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("debateId", out JsonElement _debateId)) { return BadRequest(); }
                if (!request.TryGetProperty("debateCode", out JsonElement _debateCode)) { return BadRequest(); }
                List<dynamic> debates = new List<dynamic>();
                Debate debate = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>($"{_debateId}", new PartitionKey($"{_debateCode}"));
                return Ok(new { debate = debate , replyCount = debate.replies!=null  ?debate.replies.Count:0});
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，DebateController,school/debate/FindId\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }
        /// <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("debateId", out JsonElement _debateId)) { return BadRequest(); }
                if (!request.TryGetProperty("debateCode", out JsonElement _debateCode)) { return BadRequest(); }
                List<dynamic> debates = new List<dynamic>();
                await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").DeleteItemAsync<Debate>($"{_debateId}", new PartitionKey($"{_debateCode}"));
                return Ok(new { status=200});
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，DebateController,school/debate/delete\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }

        /// <summary>
        /// 查询所有话题
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find")]
        public async Task<IActionResult> Find(JsonElement request) {
            try
            {
                List<dynamic> debates = new List<dynamic>();
                request.TryGetProperty("source", out JsonElement _source);
                request.TryGetProperty("tmdid", out JsonElement _tmdid);
                request.TryGetProperty("comid", out JsonElement _comid);
                if (request.TryGetProperty("code", out JsonElement code))
                {
                    StringBuilder stringBuilder = new StringBuilder($"select c.id,c.code,c.tmdid,c.tmdname,c.title,c.comment,c.time,c.comid,c.likeCount,c.school,c.likes,c.wordCount,c.timeoutReply,c.expire,c.source,c.pk, ARRAY_LENGTH( c.replies ) as replyCount from c where c.pk='Debate' ");
                    if (!string.IsNullOrEmpty($"{_source}")) {
                        stringBuilder.Append($" and c.source='{_source}'");
                    }
                    if (!string.IsNullOrEmpty($"{_tmdid}"))
                    {
                        stringBuilder.Append($" and c.tmdid='{_tmdid}'");
                    }
                    if (!string.IsNullOrEmpty($"{_comid}"))
                    {
                        stringBuilder.Append($" and c.comid='{_comid}'");
                    }
                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                            .GetItemQueryIterator<dynamic>(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Debate-{code}") }))
                    {
                        debates.Add(item);
                    }
                }
                return Ok(debates);
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/debate/find\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }
        /*
        {
           "opt":"add"
            "debateId": "1fcdb1d6-de51-40d5-bfa0-193c3929e50c",
            "debateCode":"Debate-hbcn",
            "reply":{
                "id":null,
                "pid":"话题的id  1fcdb1d6-de51-40d5-bfa0-193c3929e50c",
                "tmdid":"回复者的id",
                "tmdname":"回复者的昵称",
                "comment":"回复内容",
                "atTmdid":"被回复的id",
                "atTmdname":"被回复的name"
            }
        }
        {
           "opt":"del"
            "debateId": "1fcdb1d6-de51-40d5-bfa0-193c3929e50c",
            "debateCode":"Debate-hbcn",
            "reply":{
                "id":"uuid"
            }
        }

         */

        /// <summary>
        /// 回复话题
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("reply")]
        [AuthToken(Roles = "admin,teacher")]
        public async Task<IActionResult> reply(JsonElement request) {
            var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
            if (!request.TryGetProperty("opt", out JsonElement _opt)) { return BadRequest(); }
            if (!request.TryGetProperty("debateId", out JsonElement _debateId)) { return BadRequest(); }
            if (!request.TryGetProperty("debateCode", out JsonElement _debateCode)) { return BadRequest(); }
            if (!request.TryGetProperty("reply", out JsonElement _reply)) { return BadRequest(); }
            DebateReply reply = null;
            if (!string.IsNullOrEmpty($"{_debateId}") && !string.IsNullOrEmpty($"{_debateCode}") && !string.IsNullOrEmpty($"{_opt}"))
            {
                switch ($"{_opt}")
                {
                    case "add":
                        try
                        {
                            Debate debate = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>($"{_debateId}", new PartitionKey($"{_debateCode}"));
                            reply = _reply.ToObject<DebateReply>();
                            reply.pid = string.IsNullOrEmpty(reply.pid) ? $"{_debateId}" : reply.pid;
                            reply.id = string.IsNullOrEmpty(reply.id) ? Guid.NewGuid().ToString() : reply.id;
                            reply.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                            debate.replies.Add(reply);
                            await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Debate>(debate, $"{_debateId}", new PartitionKey($"{_debateCode}"));
                            return Ok(new { reply , replyCount = debate.replies.Count });
                        }
                        catch (CosmosException ex)
                        {
                            return BadRequest();
                        }
                    case "del":
                        try
                        {
                            Debate debate = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>($"{_debateId}", new PartitionKey($"{_debateCode}"));
                            reply = _reply.ToObject<DebateReply>();
                            var findall = debate.replies.FindAll(x => reply.id .Equals(x.id));
                            if (findall.IsNotEmpty())
                            {   
                                foreach (var find in findall)
                                {
                                    if (find.tmdid .Equals(userid)||debate.tmdid .Equals(userid))
                                    {
                                        debate.replies.Remove(find);
                                    }
                                    else {
                                        //不能删除别人的
                                        return Ok(new { status = 2, replyCount = debate.replies.Count });
                                    }
                                }
                                await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Debate>(debate, $"{_debateId}", new PartitionKey($"{_debateCode}"));
                                //删除成功
                                return Ok(new { status = 0 , replyCount = debate.replies.Count });
                            }
                            else {
                                return Ok(new { status = 0, replyCount = debate.replies.Count });
                            }
                        }
                        catch (CosmosException ex)
                        {   //删除失败，话题不存在
                            return Ok(new {  status=1});
                        }
                    default:
                        return BadRequest("opt only is del or add");
                }
            }
            else { return BadRequest(); }
        }


        /*
        {
            "comid":"uuid",
            "source":"normal",
            "debate":
            {
                "id":"uuid",
                "code":"hbcn",
                "tmdid":"153445tmdid",
                "tmdname":"醍摩豆。昵称",
                "title":"本次教研活动有哪些建议？",
                "comment":"请大家踊跃讨论！",
                "time":0,
                "school":"hbcn",
                "wordCount":500,//字数限制
                "timeoutReply":false,
                "expire":11255522
            }
        } 
         */
        /// <summary>
        /// 创建话题
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert")]
        public async Task<IActionResult> upsert(JsonElement request) {
            /// 评论/话题的统一id,用于被关联
            request.TryGetProperty("comid", out JsonElement _comid);
            /// 创建来源
            if (!request.TryGetProperty("source", out JsonElement _source)) { return BadRequest("source param is null!"); }
            request.TryGetProperty("debate", out JsonElement _debate);
            string comid = $"{_comid}";
            ///如果位空则表示来源并非 技能点话题或者作品成果话题 或者以及其他已经定义的业务类型关联的comid，为保证数据完整性，则需要重新生成。
            if (string.IsNullOrEmpty(comid)) {
                comid = Guid.NewGuid().ToString();
            }
            Debate debate= _debate.ToObject<Debate>();
            debate.comid = comid;
            debate.source = $"{_source}";
            if ($"{_source}".Equals("normal") || $"{_source}".Equals("ability")) {
                debate.openType = 1;
            }
            else { debate.openType = 0; }
            debate.pk = "Debate";
            if (string.IsNullOrEmpty(debate.code))
            {
                return BadRequest("debate.code param is null!");
            }
            else {
                debate.code = debate.code.StartsWith("Debate-") ? debate.code : $"Debate-{debate.code}";
            }
            if (string.IsNullOrEmpty(debate.id)) {
                debate.id = Guid.NewGuid().ToString();
                debate.time= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(debate, new PartitionKey(debate.code));
            }
            else {
                try
                {
                    Debate _DBdebate = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>(debate.id, new PartitionKey(debate.code));
                    ///保证记录回复记录和点赞记录正常
                    debate.replies = _DBdebate.replies;
                    debate.likeCount = _DBdebate.likeCount;
                    debate.likes = _DBdebate.likes;
                    debate.replies = _DBdebate.replies;
                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(debate, debate.id, new PartitionKey(debate.code));
                }
                catch (CosmosException ex) {
                    if (ex.Status == 404) {
                        await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(debate,  new PartitionKey(debate.code));
                    }
                }
            }
            return Ok(new { debate= debate,now= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
        }
    }
}
