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.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos;

namespace TEAMModelOS.Controllers
{
    [Route("school/room")]
    [ApiController]
    public class RoomController : ControllerBase
    {
        public readonly AzureCosmosFactory _azureCosmos;
        private readonly Option _option;
        private readonly DingDing _dingDing;
        public RoomController(AzureCosmosFactory azureCosmos, DingDing dingDing,
            IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
        }
        /// <summary>
        /// {
        ///     "id":"教室id,新增时为空","code":"学校编码hbcn","name":"教室名称"，"no":"编号","x":坐标x,"y":坐标y,
        ///     "sn":"序列号","openType":"1  教室属性，普通 /专设的教室","style":"TBL IRS 类型区分","area":"教学区，第一教学楼...."
        /// }
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert")]
        public async ValueTask<IActionResult> Upsert(Room request) {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                request.pk = "Room";
                request.code = request.pk + "-" + request.code;
                request.ttl = -1;
                if (string.IsNullOrEmpty(request.id))
                {
                    request.id = Guid.NewGuid().ToString();
                    request = await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                }
                else {
                    var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
                    if (response.Status == 200)
                    {
                        using var json = await JsonDocument.ParseAsync(response.ContentStream);
                        var info = json.ToObject<Room>();
                        request = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
                    }
                    else
                    {
                        request = await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                    }
                }
                return Ok(new { room= request });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/vote/save()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        /// <summary>
        /// {"code":"hbcn学校编码"} 
        /// </summary>
        /// <param name="requert"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find")]
        public async Task<IActionResult> Find(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("code", out JsonElement code)) { return BadRequest(); }
                var client = _azureCosmos.GetCosmosClient();
                List<Room> rooms = new List<Room>() ;
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Room>(queryText: $"select value(c) from c ",
                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Room-{code}") })) {
                    rooms.Add(item);
                }
                return Ok(new { rooms= rooms });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/room/find()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        /// <summary>
        /// {"id":"教室id","code":"hbcn学校编码"} 
        /// </summary>
        /// <param name="requert"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-id")]
        public async Task<IActionResult> FindById(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();
                Room room = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<Room>(id.GetString(), new PartitionKey($"Room-{code}"));
                if (room != null)
                {

                    return Ok(new { room });
                }
                else
                {
                    return BadRequest("id,code不存在！");
                }
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/room/find-id()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        /// <summary>
        /// {"id":"教室id","code":"hbcn学校编码"} 
        /// </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", "School").DeleteItemAsync<Room>(id.GetString(), new PartitionKey($"Room-{code}"));
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/room/find-id()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
    }
}
