using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Ocsp;
using System.Text.Json;
using System.Runtime.InteropServices;
using TencentCloud.Scf.V20180416.Models;
using Quartz.Impl.AdoJobStore.Common;
using TencentCloud.Gaap.V20180529.Models;
using System.Net;
using TencentCloud.Ie.V20200304.Models;
using TencentCloud.Soe.V20180724.Models;

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

        [HttpGet]
        public ActionResult get()
        {
            var data = new DBContext.Table("tk_config").Get<TkConfigDTO>("id>0", new { });
            return new APIResult(new { data });
        }


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

            string content = "【3瓶】恩威万蓝莓叶黄素酯软糖儿童成人上班族如酸涩肿胀可服用，<z5TYWAblvTw >:// HU7709,打開/";
            try
            {
                var arr = form.tk_whitelist_regular.Split('\n')
                            .Where(line => !string.IsNullOrWhiteSpace(line))
                            .ToList();

                var arr2 = form.tk_blacklist_regular.Split('\n')
                            .Where(line => !string.IsNullOrWhiteSpace(line))
                            .ToList();
                bool is_tao_token = AlimamaPlus.MatchRegexes(content, arr);
                bool is_other = AlimamaPlus.MatchOtherInfo(content, arr2);
            }
            catch (Exception ex)
            {
                return new APIResult(new { msg = $"正则异常${ex.Message}", success = false });
            }
            using var conn = DBContext.GetOpenConnection();
            var old = new DBContext.Table(conn, "tk_config").Get<TkConfigDTO>("id>0", new { });

            int result = await conn.UpdateAsync<TkConfigDTO>(form);

            var endpoint = EndPointCore.GetCouponAdmin();
            if (!string.IsNullOrEmpty(endpoint.db_server))
            {
                using var conn2 = EndPointCore.GetDbConnection(endpoint.db_server);
                _ = await conn2.UpdateAsync<TkConfigDTO>(form);
            }

            string desc = ObjectComparer.PrintCompareToString(old, form).Trim();
            OperationLogCore.LogOperation(token.AccessKey, clientIp, "config", old.Convert2Json(), desc);
            EndPointCore.NotifyReload();
            return new APIResult(new { msg = "更新成功", success = result > 0 });
        }

    }
}