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 TEAMModelOS.Services.Common;
using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
using HTEXLib.COMM.Helpers;
using TEAMModelOS.Filter;

namespace TEAMModelOS.Controllers.Research
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("research/ability-task")]
    [ApiController]
    //[Authorize]
    public class AbilityTaskController: ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly Option _option;
        private readonly DingDing _dingDing;
        public AbilityTaskController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
        }

        /// <summary>
        /// 检查资源链接是否被其他结构关联
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("check-link")]
        [AuthToken(Roles = "area")]
        public async Task<IActionResult> CheckLink(JsonElement request)
        {
            if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
            if (!request.TryGetProperty("links", out JsonElement _links)) return BadRequest();
            //if (!request.TryGetProperty("code", out JsonElement _code)) return BadRequest();
            //if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
            if ( _links.ValueKind.Equals(JsonValueKind.Array))
            {
                List<AbilityLinkDto> links = new List<AbilityLinkDto>();
                List<string> list = _links.ToObject<List<string>>();
                var client = _azureCosmos.GetCosmosClient();
                list = list.Select(x => $"'{x}'").ToList();
                string lks = string.Join(",", list);
                StringBuilder queryText = new StringBuilder($"SELECT  c.id as abilityTaskId,c.abilityId,rnodes.link ,children.id as treeid  FROM c join children  in  c.children join rnodes in children.rnodes    where rnodes.link in ({lks}) ");
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AbilityLinkDto>(queryText: queryText.ToString(),
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"AbilityTask-{standard}") }))
                {
                    links.Add(item);
                }
                var count = links.GroupBy(x => x.link).Select(y => new { key = y.Key, count = y.ToList().Count });
                return Ok(new { count, links });
            }
            else
            {
                return BadRequest();
            }
        }
        public class AbilityLinkDto
        {
            /// <summary>
            /// 原来为 abilityTaskId
            /// </summary>
            public string abilityTaskId { get; set; }
            /// <summary>
            /// 原来为 abilityId
            /// </summary>
            public string abilityId { get; set; }
            public string link { get; set; }
            public string treeid { get; set; }
        }

        /*
         [
            {
                "id": "章节id",
                "abilityId": "册别id",
                "scope": "school",
                "trees": [
                    {
                        "id": "b2b15c99-83cc-eca7-5b4b-e58d2a457c8e",
                        "pid": "0baf00db-0768-4b62-a8f7-280f6bcebf71",
                        "title": "第一单元",
                        "type": 1,
                        "children": []
                    }
                ]
            }
        ]
         */
        /// <summary>
        /// 批量保存或更新课纲
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert-tree")]
        [AuthToken(Roles = "area")]
        public async Task<IActionResult> SaveOrUpdateAsTree(List<AbilityTaskTreeNode> request)
        {
            if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
            long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            foreach (AbilityTaskTreeNode abilityTaskTree in request)
            {

                if (!string.IsNullOrEmpty(abilityTaskTree.id))
                {
                    AbilityTask abilityTask = null;
                    try
                    {
                        abilityTask = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<AbilityTask>(abilityTaskTree.id, new Azure.Cosmos.PartitionKey($"AbilityTask-{standard}"));
                    }
                    catch
                    {
                    }
                    if (abilityTask == null)
                    {
                        if (abilityTaskTree.trees.IsNotEmpty())
                        {
                            abilityTaskTree.trees.ForEach(x => x.id = abilityTaskTree.id);
                        }
                        List<Tnode> nodes = new List<Tnode>();
                        AbilityService.TreeToList(abilityTaskTree.trees, nodes, now);
                        abilityTask = new AbilityTask();
                        abilityTask.id = abilityTaskTree.id;
                        abilityTask.children = nodes;
                        abilityTask.code = $"AbilityTask-{standard}";
                        abilityTask.pk = "AbilityTask";
                        abilityTask.ttl = -1;
                        abilityTask.abilityId = abilityTaskTree.abilityId;
                        abilityTask.scope = abilityTaskTree.scope;
                        abilityTask.codeval = $"{standard}";
                        abilityTask.standard = $"{standard}";
                        await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync<AbilityTask>(abilityTask, new Azure.Cosmos.PartitionKey($"AbilityTask-{standard}"));
                    }
                    else
                    {
                        if (abilityTaskTree.trees.IsNotEmpty())
                        {
                            abilityTaskTree.trees.ForEach(x => x.id = abilityTaskTree.id);
                        }
                        List<Tnode> nodes = new List<Tnode>();
                        AbilityService.TreeToList(abilityTaskTree.trees, nodes, now);
                        abilityTask.children = nodes;
                        abilityTaskTree.auth = abilityTask.auth;
                        await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync<AbilityTask>(abilityTask, abilityTask.id, new Azure.Cosmos.PartitionKey($"AbilityTask-{standard}"));
                    }


                }
                else
                {
                    string id = Guid.NewGuid().ToString();
                    abilityTaskTree.id = id;
                    if (abilityTaskTree.trees.IsNotEmpty())
                    {
                        abilityTaskTree.trees.ForEach(x => x.id = abilityTaskTree.id);
                    }
                    List<Tnode> nodes = new List<Tnode>();
                    AbilityService.TreeToList(abilityTaskTree.trees, nodes, now);
                    AbilityTask abilityTask = new AbilityTask
                    {
                        id = id,
                        code = $"AbilityTask-{standard}",
                        pk = "AbilityTask",
                        ttl = -1,
                        abilityId = abilityTaskTree.abilityId,
                        children = nodes,
                        scope = abilityTaskTree.scope,
                        codeval= $"{standard}",standard = $"{standard}"
                    };
                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync<AbilityTask>(abilityTask, new Azure.Cosmos.PartitionKey($"AbilityTask-{standard}"));
                }
            }
            return Ok(request);
        }


        /*
            {"abilityId":"册别id：0baf00db-0768-4b62-a8f7-280f6bcebf71","scope":"school","abilityCode":"册别分区键"}
         */
        /// <summary>
        /// 查找课纲 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-id")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> Find(JsonElement request)
        {
            if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
            var client = _azureCosmos.GetCosmosClient();
            if (!request.TryGetProperty("abilityId", out JsonElement abilityId)) return BadRequest();
           // if (!request.TryGetProperty("abilityCode", out JsonElement abilityCode)) return BadRequest();
            //if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
            Ability ability = null;
            List<AbilityTaskTreeNode> treeNodes = new List<AbilityTaskTreeNode>();
            List<AbilityTaskTreeNode> redt = new List<AbilityTaskTreeNode>();
            try
            {
                int rnodeCount=0;
                ability = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<Ability>($"{abilityId}", new PartitionKey($"Ability-{standard}"));
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c where c.abilityId='{abilityId}'",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"AbilityTask-{standard}") }))
                {
                    var rns = item.children.Select(x => x.rnodes);
                    if (rns != null)
                    {
                        var list = rns.ToList();
                        list.ForEach(x => {
                            if (x.IsNotEmpty())
                            {
                                rnodeCount += 1;
                            }
                        });
                    }
                    List<AbilityTaskTree> trees = AbilityService.ListToTree(item.children);
                    AbilityTaskTreeNode tree = new AbilityTaskTreeNode() { id = item.id, scope = item.scope, trees = trees, abilityId = item.abilityId, auth = item.auth, codeval = ability.school };
                    treeNodes.Add(tree);
                }
                //对课纲树形结构排序
                if (ability.abilityTaskIds.IsNotEmpty())
                {
                    ability.abilityTaskIds.ForEach(x =>
                    {
                        for (int index = 0; index < treeNodes.Count; index++)
                        {
                            if (treeNodes[index].id .Equals(x))
                            {
                                redt.Add(treeNodes[index]);
                                treeNodes.RemoveAt(index);
                            }
                        }
                    });
                    redt.AddRange(treeNodes);
                    return Ok(new { tree = redt });
                }
                else
                {
                    return Ok(new { tree = treeNodes, rnodeCount });
                }

            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},common/syllabus/find-id\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return Ok(new { tree = treeNodes });
            }
        }

        /*
            {"id":"章节id","code":"学校编码/醍摩豆id","scope":"school/private"}
         */

        /// <summary>
        /// 删除章节
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("delete")]
        [AuthToken(Roles = "area")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            try
            {
                if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                var response = await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"AbilityTask-{standard}"));
                return Ok(new { code = response.Status });
            }
            catch
            {
                return Ok(new { code = 404 });
            }
        }
    }
}
