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

namespace TEAMModelOS.Controllers.Research
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("research/ability")]
    [ApiController]
    public class AbilityController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        public AbilityController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value; ;
        }
       
        /*
           {"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> FindId(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("schoolCode", out JsonElement schoolCode)) return BadRequest();
           // if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
            Ability ability = null;
            try
            {
                ability = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<Ability>($"{abilityId}", new PartitionKey($"Ability-{standard}"));
                return Ok(new { ability = ability });
            }
            catch (Exception ex)
            {
                return Ok(new { ability = ability });
            }
        }
         
       

        /*
           {
               "id": "册别id",
               "code": "学校编码/教师编码",
               "scope": "school/private"
           }
        */
        /// <summary>
        /// 删除技能点
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [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();
                // if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                string sql = $"select value(c) from c where c.abilityId='{id}'";
                List<AbilityTask> syllabus = new List<AbilityTask>();
                var response = await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Ability-{standard}"));
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AbilityTask>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{standard}") }))
                {
                    syllabus.Add(item);
                }
                if (syllabus.IsNotEmpty())
                {
                    var sresponse = await client.GetContainer("TEAMModelOS", "School").DeleteItemsStreamAsync(syllabus.Select(x => x.id).ToList(), $"AbilityTask-{standard}");
                }
                return Ok(new { code = response.Status });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController:Delete\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                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")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> Find(JsonElement request)
        {
            try
            {
                if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
                List<Ability> abilities = new List<Ability>();
                request.TryGetProperty("dimension", out JsonElement _dimension);
                
                StringBuilder sql = new StringBuilder("select value(c) from c ");
                if (!string.IsNullOrEmpty($"{_dimension}")) {
                    sql.Append($" where c.dimension='{_dimension}' ");
                }
                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                         .GetItemQueryIterator<Ability>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{standard}") }))
                {
                    abilities.Add(item);
                }
                return Ok(new { abilities });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController:find\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }


        /*
         
        {
            "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")]
        [AuthToken(Roles = "area")]
        public async Task<IActionResult> Upsert(Ability request)
        {
            if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
            request.pk = "Ability";
            request.ttl = -1;
            request.code = $"Ability-{standard}";
            // 检查册别条件相同的是否存在
            ///表示更新
            if (!string.IsNullOrEmpty(request.id))
            {
                try
                {
                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Ability>(request, request.id, new Azure.Cosmos.PartitionKey($"Ability-{standard}"));

                }
                catch (Exception ex)
                {
                    return BadRequest(new { error = ResponseCode.FAILED });
                }
            }
            //表示新增,则需要检查是否重复
            else
            {
                try
                {
                    request.comid = Guid.NewGuid().ToString();
                    StringBuilder sql = new StringBuilder("select value(c) from c where c.status = 1 ");
                    if ( !string.IsNullOrEmpty(request.dimension))
                    {
                        sql.Append($" and c.dimension = '{request.dimension}' and c.name = '{request.name}' ");
                        List<Ability> volumes = new List<Ability>();
                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                        .GetItemQueryIterator<Ability>(queryText: sql.ToString(), requestOptions: new Azure.Cosmos.QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Ability-{standard}") }))
                        {
                            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();
                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(request, new PartitionKey($"Ability-{standard}"));
                }
                catch (Exception ex)
                {
                    await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController:Upsert\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                }
            }
            return Ok(request);
        }
    }
}
