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.Json;
using System.Threading.Tasks;
using TEAMModelOS.Filter;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using TEAMModelOS.Services.Common;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("teacher/favorite")]
    [ApiController]
    public class FavoriteController: ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly DingDing _dingDing;
        private readonly Option _option;

        public FavoriteController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value; 
        }
        /// <summary>
        /// 保存或更新 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert")]
        [AuthToken(Roles = "Teacher")]
        public async Task<IActionResult> Upsert(Favorite request)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                request.pk = "Favorite";
                request.code = request.pk + "-" + request.code;
                request.ttl = -1;
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                request.createTime = now;
                if (string.IsNullOrEmpty(request.id))
                {

                    request.id = Guid.NewGuid().ToString();
                    request = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                }
                else
                {
                    var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
                    if (response.Status == 200)
                    {
                        using var json = await JsonDocument.ParseAsync(response.ContentStream);
                        var info = json.ToObject<Favorite>();
                        request = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
                    }
                    else
                    {
                        request = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                    }
                }
                return Ok(new { room = request });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，teacher/favorite/upsert\n{e.Message}{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        /// <summary>
        /// {"code":"教师编码"} 
        /// </summary>
        /// <param name="requert"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [AuthToken(Roles = "Teacher")]
        [HttpPost("find")]
        public async Task<IActionResult> Find(JsonElement request)
        {
            try
            {
                List<Favorite> favorites = new List<Favorite>();
                if (!request.TryGetProperty("code", out JsonElement code)) { return BadRequest(); }
                var client = _azureCosmos.GetCosmosClient();
              
                await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Favorite>(queryText: $"select value(c) from c ",
                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Favorite-{code}") }))
                {
                    favorites.Add(item);
                }
                return Ok(new { favorites = favorites });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，teacher/favorite/find()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        /// <summary>
        /// {"id":"我的最爱id","code":"教师编码"} 
        /// </summary>
        /// <param name="requert"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement requert)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                //id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                //
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var room = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<Favorite>(id.GetString(), new PartitionKey($"Favorite-{code}"));
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，teacher/favorite/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
    }
}
