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 WebSocketSharp.Net;
namespace molilian.api.Controllers
{


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

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


            string cookie = form.Read<string>("cookie", string.Empty);
            cookie = cookie.Replace("\r", "").Replace("\n", "").Trim();
            if (!cookie.EndsWith(";")) cookie += ";";

            var accountId = JdPoolCore.UpdateCookies(cookie, user_agent);
            bool success = accountId > 0;
            if (success)
            {
                //string desc = ObjectComparer.PrintCompareToString(old, form).Trim();
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"jd_pool:{accountId}:cookie", string.Empty, cookie);
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入的cookie" },
            });
        }

        /// <summary>
        /// 账号列表
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [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);
            string keyword = form.Read("name", string.Empty);
            bool getTotal = form.Read("getTotal", true);
            string _status = form.Read("status", string.Empty);
            int status = _status switch
            {
                "online" => 1,
                "offline" => 0,
                _ => -1,
            };
            var lastTime = form.PathReadArray<string>("lastTime[]");

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

            string filter = " is_hide=0";
            if (!string.IsNullOrEmpty(keyword))
            {
                filter += $" AND (`name` LIKE @keyword OR `description` LIKE @keyword)";
                keyword = $"%{keyword}%";
            }
            DateTime stime = DateTime.MinValue, etime = DateTime.MinValue;
            if (lastTime.Count == 2)
            {
                if (DateTime.TryParse(lastTime[0], out stime) && DateTime.TryParse(lastTime[1], out etime))
                {
                    etime = etime.AddDays(1).AddSeconds(-1);
                    filter += $" AND last_time BETWEEN @stime AND @etime";
                }
            }
            if (status != -1)
            {
                filter += $" AND status=@status";

            }

            filter = filter.StringTrimStart(" AND ");

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

            using var conn = DBContext.GetOpenConnection();
            var result = new DBContext.Table(conn, "jd_pool")
                .Where(filter, new { keyword, status, stime, etime })
                .Page(size, page)
                .Order(orderBy)
                .PageList<JdPoolDTO>(getTotal);

            foreach (var item in result.List)
            {
                item.app_secret = string.Empty;
                item.cookies = 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 = "更新失败，请检查输入的cookie" } });
            }

            int result;
            switch (name)
            {
                case "enable_parse":
                case "enable_coupon":
                case "status":
                    bool bVal = val.Equals("True");
                    result = new DBContext.Table("jd_pool")
                           .Add(name, bVal)
                           .Add("last_time", DateTime.Now)
                           .Where("id=@id", new { id })
                           .Update();
                    break;
                case "time_range":
                    int.TryParse(val, out int iVal);
                    result = new DBContext.Table("jd_pool")
                           .Add(name, iVal)
                           .Add("last_time", DateTime.Now)
                           .Where("id=@id", new { id })
                           .Update();
                    break;
                default:
                    return new APIResult(new { data = new { success = false, msg = "更新失败，未授权操作" } });
            }
            bool success = result > 0;
            if (success)
            {
                OperationLogCore.LogOperation(token.AccessKey, clientIp, $"jd_pool:{id}:{name}", string.Empty, val);
                await EndPointCore.NotifyReload(true);

            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }


    }
}