using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Azure;
using Azure.Cosmos;
using Azure.Storage.Sas;
using HTEXLib.COMM.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using TEAMModelOS.Filter;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.Common;
namespace TEAMModelOS.Controllers
{
    [Route("school/notice")]
    [ApiController]
    public class NoticeController :ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly AzureStorageFactory _azureStorage;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        public NoticeController(
           AzureCosmosFactory azureCosmos,
           AzureStorageFactory azureStorage,
           DingDing dingDing,
           IOptionsSnapshot<Option> option
           )
        {
            _azureCosmos = azureCosmos;
            _azureStorage = azureStorage;
            _dingDing = dingDing;
            _option = option?.Value;
        }

        /// <summary>
        /// 新增 或 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert")]
        [AuthToken(Roles = "teacher,admin")]
        public async Task<IActionResult> Upsert(Notice request)
        {
            try
            {
                var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
                //新增
                var client = _azureCosmos.GetCosmosClient();
                request.code =$"Notice-{request.code}";
                request.pk = "Notice";
                request.ttl = -1;
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                request.createTime = now;
                request.creatorId = userid;
                //如果设置的时间是小于当前时间则立即发布
                if (request.startTime <= 0)
                {
                    request.startTime = now;
                }
                if (request.endTime <= request.startTime) {
                    return BadRequest("结束时间必须大于开始时间");
                }
                if (string.IsNullOrEmpty(request.id))
                {
                    request.id = Guid.NewGuid().ToString();
                  
                    request = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                }
                else
                {
                    var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
                 
                    if (response.Status == 200)
                    {
                       
                        request = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
                    }
                    else
                    {
                        request = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                    }
                }
                return Ok(new { vote = request });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/Notice/upsert()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest(e.StackTrace);
            }
        }/// <summary>
         /// 查询投票活动,用于列表，编辑，查看
         /// </summary>
         /// <data>
         ///Vote-学校/教师编码  活动分区        !"code":"hbcn"/1606285227 
         ///时间筛选范围开始时间 默认30天之前   ?"stime":1608274766154  
         ///时间筛选范围结束时间 默认当前时间   ?"etime":1608274766666 
         ///每页大小     ?"count":10/null/Undefined  
         ///分页Token    ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
         /// 当前状态    ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束  
         /// </data>
         /// <param name="request"></param>
         /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find")]
        [AuthToken(Roles = "teacher,admin")]
        public async Task<IActionResult> Find(JsonElement requert)
        {
            try
            {
                var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
                //必须有学校或者教师编码
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                requert.TryGetProperty("admin", out JsonElement admin);
                string stimestampsql = "";
                string etimestampsql = "";
                if (!$"{admin}" .Equals("1")) {
                    var stimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    if (requert.TryGetProperty("stime", out JsonElement stime))
                    {
                        if (long.TryParse($"{stime}", out long data))
                        {
                            stimestamp = data;
                        }
                    }
                    stimestampsql = $" and c.startTime <= {stimestamp} ";
                    //默认当前时间
                    var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    if (requert.TryGetProperty("etime", out JsonElement etime))
                    {
                        if (long.TryParse($"{etime}", out long data))
                        {
                            etimestamp = data;
                        }
                    }
                    etimestampsql = $" and c.endTime >= {etimestamp} ";
                   
                }
                var publishsql = "";
                if (requert.TryGetProperty("publish", out JsonElement publish))
                {

                    if (!publish.ValueKind.Equals(JsonValueKind.Undefined) && !publish.ValueKind.Equals(JsonValueKind.Null) && publish.ValueKind.Equals(JsonValueKind.Number))
                    {
                        publishsql = $" and c.publish={publish} ";
                    }
                }
                var typesql = "";
                if (requert.TryGetProperty("type", out JsonElement type))
                {

                    if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String))
                    {
                        typesql = $" and c.type='{type}' ";
                    }
                }
                List<Notice> notices = new List<Notice>();
                var client = _azureCosmos.GetCosmosClient();
                var query = $"select value(c) from c where  c.ttl=-1 {etimestampsql} {stimestampsql} {publishsql }  {typesql} ";
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Notice>(queryText: query,
                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Notice-{code}") }))
                {
                    notices.Add(item);
                }
                return Ok(new { notices });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/Notice/find()\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest(ex.StackTrace);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("delete")]
       // [AuthToken(Roles = "admin",Permissions = "teacher-upd")]
        public async Task<IActionResult> Delete(JsonElement request) {
            try
            {
               // var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Notice-{code}"));
                return Ok(new { status = 200 });
            }
            catch (Exception e)
            {
                return BadRequest(e.StackTrace);
            }
        }
    }
}
