using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using TEAMModelOS.SDK;

using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using System;
using TEAMModelOS.SDK.Helper.Common.JsonHelper;
using System.Linq;
using TEAMModelOS.Models;
using System.Text.Json;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models;
using Microsoft.AspNetCore.Http;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using Azure.Cosmos;
using TEAMModelOS.Services.Common;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("common/syllabus")]
    [ApiController]
    //[Authorize]
    public class SyllabusController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;


        public SyllabusController(AzureCosmosFactory azureCosmos)
        {
            _azureCosmos = azureCosmos;
        }

        /*
        {
          "id": "hbcn108774752059002880",
          "code": "Syllabus-hbcn",
          "scope":"school/private",
          "trees": [
              {
                  "id": "111111-111-44E7-8DD9-A6CB6D0D52F2",
                  "pid": "hbcn108515325535981568",
                  "title": "第一章",
                  "order": 0,
                  "type": tree,
                  "rnodes":[
                      {
                            "type":"item/paper/image/video/pptx.../link"//试题 ，试卷，内容资源，外部链接（只有link,和name）
                            "title":"显示名称",
                            "id":"关联资源的id",
                            "code":"关联资源的code",
                            "link":["https;//www.xxx.com/xxx.json"],
                            "cntr":"blob的容器名"
                      }
                   ],
                  "children": [
                      {
                          "id": "22222-111-447E-8A52-BFCD63E61D33",
                          "pid": "111111-111-44E7-8DD9-A6CB6D0D52F2",
                          "title": "第一节333",
                          "order": 0,
                          "type": 1,
                          "children": [
                              {
                                  "id": "3333-111-447E-8A52-BFCD63E61D33",
                                  "pid": "22222-111-447E-8A52-BFCD63E61D33",
                                  "title": "第一节333",
                                  "order": 0,
                                  "type": 1
                              },
                              {
                                  "id": "4444-111-447E-8A52-BFCD63E61D33",
                                  "pid": "22222-111-447E-8A52-BFCD63E61D33",
                                  "title": "第一节333",
                                  "order": 0,
                                  "type": 1
                              }
                          ]
                      }
                  ]
              },
              {
                  "id": "111111-222-44E7-8DD9-A6CB6D0D52F2",
                  "pid": "hbcn108515325535981568",
                  "title": "第一章",
                  "order": 0,
                  "type": 1,
                  "children": [
                      {
                          "id": "22222-222-447E-8A52-BFCD63E61D33",
                          "pid": "111111-222-44E7-8DD9-A6CB6D0D52F2",
                          "title": "第一节333",
                          "order": 0,
                          "type": 1,
                          "children": [
                              {
                                  "id": "3333-222-447E-8A52-BFCD63E61D33",
                                  "pid": "22222-222-447E-8A52-BFCD63E61D33",
                                  "title": "第一节333",
                                  "order": 0,
                                  "type": 1
                              }
                          ]
                      },
                      {
                          "id": "5555-222-447E-8A52-BFCD63E61D33",
                          "pid": "111111-222-44E7-8DD9-A6CB6D0D52F2",
                          "title": "第一节333",
                          "order": 0,
                          "type": 1,
                          "children": []
                      }
                  ]
              }
          ]
        }

              */

        /// <summary>
        /// 批量保存或更新课纲
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert-tree")]
        public async Task<IActionResult> SaveOrUpdateAsTree(SyllabusTreeNode request)
        {
            List<List<SyllabusTree>> tts = new List<List<SyllabusTree>>();
            foreach (var tree in request.trees) {
                Syllabus syllabus = new Syllabus();
                List<Tnode> nodes = new List<Tnode>();
                SyllabusService.TreeToList(new List<SyllabusTree> { tree }, nodes);
                syllabus.children = nodes;
                syllabus.id = !string.IsNullOrEmpty(tree.id) ? tree.id : Guid.NewGuid().ToString();
                syllabus.code = $"Syllabus-{request.id}";
                syllabus.pk = "Syllabus";
                syllabus.ttl = -1;
                syllabus.volumeId = request.id;
                if (request.scope == "school")
                {
                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync<Syllabus>(syllabus, new Azure.Cosmos.PartitionKey($"Syllabus-{request.id}"));
                }
                else
                {
                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync<Syllabus>(syllabus, new Azure.Cosmos.PartitionKey($"Syllabus-{request.id}"));
                }
                List<SyllabusTree> trees = SyllabusService.ListToTree(nodes);
                tts.Add(trees);
            }

            request.trees = new List<SyllabusTree>() ;
            tts.ForEach(x => request.trees.AddRange(x));
            return Ok(request);
        }

 

        /// <summary>
        /// 查找课纲 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-id")]
        public async Task<IActionResult> Find(JsonElement request)
        {
            var client = _azureCosmos.GetCosmosClient();
            if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
            if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
            SyllabusTreeNode tree = null;
            string vcode = null;
            List<List<SyllabusTree>> tts = new List<List<SyllabusTree>>();
            try {
                if (scope.ToString().Equals("school"))
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Syllabus>(queryText: $"select value(c) from c ",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Syllabus-{code}") }))
                    {
                        vcode = item.volumeId;
                        List<SyllabusTree> trees = SyllabusService.ListToTree(item.children);
                        tts.Add(trees);
                    }
                    tree = new SyllabusTreeNode() { id = vcode,  scope = "school", trees= new List<SyllabusTree>() };
                    tts.ForEach(x => tree.trees.AddRange(x));
                }
                else
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Syllabus>(queryText: $"select value(c) from c ",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Syllabus-{code}") }))
                    {
                        vcode = item.volumeId;
                        List<SyllabusTree> trees = SyllabusService.ListToTree(item.children);
                        tts.Add(trees);
                    }
                    tree = new SyllabusTreeNode() { id = vcode, scope = "school", trees = new List<SyllabusTree>() };
                    tts.ForEach(x => tree.trees.AddRange(x)); 
                }
                return Ok(new { tree });
            } catch (Exception ex) {
                return Ok(new { tree});
            }
        }

        /// <summary>
        /// 删除课纲
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            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 });
            }
        }


     

        private async Task<List<Tnode>> FindByPid(Tnode data, List<Tnode> nodes, List<Tnode> nodedata)
        {
            foreach (Tnode syllabus in nodedata)
            {
                if (syllabus.pid == data.id)
                {
                    nodes.Add(syllabus);
                    await FindByPid(syllabus, nodes, nodedata);
                }
            }
            return nodes;
        }

        
        //private async Task<List<Syllabus>> SaveOrUpdateToNodes(List<Tnode> syllabusNodes)
        //{
        //    List<Syllabus> syllabuses;

        //   var  data = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Syllabus>(  syllabusNodes[0].code ,new Azure.Cosmos.PartitionKey(""));
        //    if (data.IsEmpty())
        //    {
        //        var syllabus = new Syllabus { id = syllabusNodes[0].code, code = syllabusNodes[0].code, children = new List<SyllabusNode>() };
        //        await _azureCosmos.SaveOrUpdate(syllabus);
        //        data = new List<Syllabus>() { syllabus };
        //    }
        //    List<SyllabusNode> syllabusNodes1 = new List<SyllabusNode>();
        //    if (data.IsNotEmpty())
        //    {
        //        syllabusNodes1.AddRange(data[0].children);
        //        //replace
        //        for (int i = 0; i < data[0].children.Count; i++)
        //        {
        //            for (int j = 0; j < syllabusNodes.Count; j++)
        //            {
        //                if (data[0].children[i].id == syllabusNodes[j].id && data[0].children[i].code == syllabusNodes[j].code)
        //                {
        //                    syllabusNodes1.Remove(data[0].children[i]);
        //                    syllabusNodes1.Add(syllabusNodes[j]);
        //                    syllabusNodes.Remove(syllabusNodes[j]);
        //                }
        //            }
        //        }
        //        data[0].children = syllabusNodes1;

        //        //新增
        //        data[0].children.AddRange(syllabusNodes);

        //        if (data[0].children.IsNotEmpty())
        //        {
        //            var len = data[0].children.Count;
        //            for (int i = 0; i < len; i++)
        //            {
        //                if (data[0].children[i].items.IsNotEmpty())
        //                {
        //                    data[0].children[i].item = true;
        //                }
        //                if (data[0].children[i].resources.IsNotEmpty())
        //                {
        //                    data[0].children[i].resource = true;
        //                }
        //            }
        //        }
        //        syllabuses = await _azureCosmos.SaveOrUpdateAll<Syllabus>(data);

        //    }
        //    else
        //    {
        //        throw new BizException("保存失败", ResponseCode.FAILED);

        //    }

        //    return syllabuses;
        //}
    }
}