using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using static molilian.core.ChartDataCore;
using TencentCloud.Soe.V20180724.Models;
using TencentCloud.Mrs.V20200910.Models;
using System.Xml.Linq;
using System.Security.Cryptography;
using TencentCloud.Bi.V20220105.Models;
namespace molilian.api.Controllers
{
    [ApiController]
    [MyAuthorize("admin")]
    [Route("api/[controller]/[action]")]
    public class ApiAccountController : ControllerBase
    {
        readonly IAuthorizationProvider provider = new AdminProvider();
        protected IHttpContextAccessor _accessor;
        public ApiAccountController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        [HttpPost]
        public 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 (name like @keyword OR description like @keyword OR api_key like @keyword)";
                keyword = $"%{keyword}%";
            }
            filter = filter.StringTrimStart(" AND ");

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

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

            return new APIResult(new { data = result });
        }



        [HttpPost]
        public async Task<ActionResult> update([FromBody] ApiAccountDTO 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, "api_account").Get<ApiAccountDTO>("id=@id", new { data.id });
            if (item == null) return new APIResult(new { data = new { success = false, msg = "更新失败，记录不存在" } });

            data.last_time = DateTime.Now;
            var result = ApiAccountCore.Update(data, conn);
            bool success = result > 0;
            if (success)
            {

                string desc = ObjectComparer.PrintCompareToString(item, data).Trim();
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"api_account:{data.name}", item.Convert2Json(), desc);
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }

        [HttpPost]
        public async Task<ActionResult> create([FromBody] ApiAccountDTO 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 = ApiAccountCore.Create(data, conn);
            bool success = result > 0;
            if (success)
            {
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"api_account:{data.name}", string.Empty, data.Convert2Json());
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }


    }
}