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

        [HttpPost]
        public ActionResult account_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 username like @keyword OR company like @keyword OR mobile 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("aliyun_pool")
               .Where(filter, new { keyword })
               .Page(size, page)
               .Order(orderBy)
               .PageList<AliyunPoolDTO>(getTotal);

            foreach (var item in result.List)
            {
                item.ecs_list = AliyunPoolCore.EcsList(item);
                item.accessKeyId = string.Empty;
                item.accessKeySecret = string.Empty;
            }
            return new APIResult(new { data = result });
        }



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

            int id = form.Read<int>("id", 0);
            string name = form.Read<string>("name", string.Empty);
            string val = form.Read<string>("val", string.Empty);

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

            int result = 0;
            switch (name)
            {
                case "status":
                    bool bVal = val.Equals("True");
                    result = new DBContext.Table("aliyun_pool")
                           .Add(name, bVal)
                           .Add("last_time", DateTime.Now)
                           .Where("id=@id", new { id })
                           .Update();
                    break;
                case "balance":
                    var item = new DBContext.Table("aliyun_pool").Get<dynamic>("id=@id", new { id });
                    if (string.IsNullOrEmpty(item.accessKeyId)) result = 0;
                    decimal amout = 0;
                    try
                    {
                        AliyunCore core = new AliyunCore(item.id);
                        var response = core.QueryAccountBalance();
                        var balance = response.Body.Data.AvailableAmount;
                        if (decimal.TryParse(balance, out amout))
                        {
                            result = 1;
                            AliyunPoolCore.UpdateDrawBalance(item.name, amout);
                            if (item.balance != amout && amout <= item.balance_alert_threshold)
                            {
                                string message = $"【{item.company}】阿里云当前余额：{amout} 元";
                                _ = NotifyCore.QYWeixinPushNotifyAsync("余额预警", message);
                                NotifyCore.Notify(new NifyMessage
                                {
                                    message = message,
                                    priority = NifyMessagePriority.high,
                                    tags = ["red_circle"]
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _ = new LoggerLibrary("aliyun", "balance_error")
                          .Info($"Account:{item.id}\tbalance:{amout}")
                          .Info(ex.Message, ex.StackTrace)
                          .SaveAsync();
                    }
                    break;
                default:
                    return new APIResult(new { data = new { success = false, msg = "更新失败，未授权操作" } });
            }


            bool success = result > 0;
            if (success)
            {
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"aliyun_pool:{id}:{name}", string.Empty, val);
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }


        [HttpPost]
        public async Task<ActionResult> ecs_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 log_date = form.PathReadArray<string>("query_date[]");
            var accountName = form.Read("accountName", string.Empty);
            int channel = form.Read("channel", -1);

            if (!string.IsNullOrEmpty(accountName))
            {
                filter += $" AND accountName=@accountName";
            }
            else
            {
                filter += $" AND accountName!='all'";
            }
            DateTime stime = DateTime.MinValue, etime = DateTime.MinValue;
            if (log_date.Count == 2)
            {
                if (DateTime.TryParse(log_date[0], out stime) && DateTime.TryParse(log_date[1], out etime))
                {
                    etime = etime.AddDays(1).AddSeconds(-1);
                    if (etime > DateTime.Now) etime = DateTime.Now;
                    filter += $" AND log_date BETWEEN @stime AND @etime";
                }
            }
            if (channel != -1)
            {
                filter += $" AND channel=@channel";
            }
            filter = filter.StringTrimStart(" AND ");

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

            using var conn = CenterHub.GetOpenConnection();
            var result = new DBContext.Table(conn, "aliyun_ecs")
                .Where(filter, new { channel, accountName, stime, etime })
                .Page(size, page)
                .Order(orderBy)
                .PageList<AliyunEcsDTO>(getTotal);


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



    }
}