using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using System.Net;
using static QRCoder.PayloadGenerator;
using MySqlX.XDevAPI;
using OfficeOpenXml.FormulaParsing.LexicalAnalysis;
using StackExchange.Redis;
using YunhuiKit;
namespace molilian.api.Controllers
{


    [ApiController]
    [MyAuthorize("admin")]
    [Route("api/[controller]/[action]")]
    public class OverrideRulesController : ControllerBase
    {
        readonly IAuthorizationProvider provider = new AdminProvider();
        protected IHttpContextAccessor _accessor;
        public OverrideRulesController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }



        [HttpPost]
        public async Task<ActionResult> list([FromBody] JsonElement form)
        {
            var token = provider.Get(_accessor.HttpContext);

            int page = form.Read("current", 1);
            int size = form.Read("pageSize", 10);
            bool getTotal = form.Read("getTotal", true);

            string sort = form.Read<string>("sort");
            string order = form.Read<string>("order");

            string filter = string.Empty;

            var keyword = form.Read("keyword", string.Empty);

            if (!string.IsNullOrEmpty(keyword))
            {
                filter += $" AND (original_text like @keyword OR original_text like @keyword)";
                keyword = $"%{keyword}%";
            }
            filter = filter.StringTrimStart(" AND ");

            string orderBy = "sort DESC, id DESC";
            if (!string.IsNullOrEmpty(order))
            {
                order = "descending".Equals(order) ? "DESC" : "ASC";
                orderBy = sort switch
                {
                    _ => $"{sort} {order}",
                };
            }

            var result = new DBContext.Table("tk_override_rules")
               .Where(filter, new { keyword })
               .Page(size, page)
               .Order(orderBy)
               .PageList<OverrideRuleDTO>(getTotal);

            foreach (var item in result.List)
            {
                string hourlyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMddHH}";
                string dailyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMdd}";

                item.current_daily_calls = await RedisKit.GetAsync<int>(hourlyKey);
                item.current_hourly_calls = await RedisKit.GetAsync<int>(hourlyKey);
            }
            return new APIResult(new { data = result });
        }



        [HttpPost]
        public async Task<ActionResult> update([FromBody] OverrideRuleDTO data)
        {
            var clientIp = _accessor.HttpContext.GetUserIp();
            var token = provider.Get(_accessor.HttpContext);

            using var conn = DBContext.GetOpenConnection();
            if (data.id == 0) return new APIResult(new { data = new { success = false, msg = "更新失败，请检查输入参数" } });

            var item = new DBContext.Table(conn, "tk_override_rules").Get<OverrideRuleDTO>("id=@id", new { data.id });
            if (item == null) return new APIResult(new { data = new { success = false, msg = "更新失败，记录不存在" } });

            data.last_time = DateTime.Now;
            var result = OverrideRuleCore.Update(data, conn);
            bool success = result > 0;
            if (success)
            {
                string desc = ObjectComparer.PrintCompareToString(item, data).Trim();
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"tk_override_rules:{data.id}", item.Convert2Json(), desc);
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }

        [HttpPost]
        public async Task<ActionResult> create([FromBody] OverrideRuleDTO data)
        {
            var clientIp = _accessor.HttpContext.GetUserIp();
            var token = provider.Get(_accessor.HttpContext);

            data.create_time = DateTime.Now;
            data.last_time = DateTime.Now;

            using var conn = DBContext.GetOpenConnection();
            var result = OverrideRuleCore.Create(data, conn);
            bool success = result > 0;
            if (success)
            {
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"tk_override_rules:{result}", string.Empty, data.Convert2Json());
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }


    }
}