using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using TencentCloud.Ecm.V20190719.Models;
using YunhuiKit;

namespace molilian.api.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class TkController : ControllerBase
    {

        protected IHttpContextAccessor _accessor;
        public TkController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        /// <summary>
        /// oppo调用
        /// </summary>
        /// <param name="s">正文</param>
        /// <param name="c">渠道。tb/jd</param>
        /// <param name="a">分配的客户端账号</param>
        /// <param name="t">11位时间戳</param>
        /// <param name="sign">签名</param>
        /// <param name="ip">客户的IP</param>
        /// <param name="oaid">客户的唯一ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> unionParse([FromBody] JsonElement form, [FromQuery] string a = "", [FromQuery] int t = 0, [FromQuery] string sign = "")
        {
            //正文
            var content = form.Read("s", string.Empty);
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var type = form.Read("type", string.Empty);
            var clickId = form.Read("clickId", string.Empty);
            var commerceType = form.Read<int>("commerceType", 0);
            var riskStrategy = form.Read("riskStrategy", string.Empty);
            var launchScene = form.Read<int>("launchScene", -1);
            var special_text = form.Read<int>("special_text", -1);
            var query_text = form.Read("query_text", string.Empty);
            var pic = form.Read("pic", string.Empty);


            //验证签名
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(sign))
            {
                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            DateTime time1 = t.Convert2Datetime();
            if (time1 < DateTime.Now.AddMinutes(-10))
            {
                return new APIResult(new { success = false, message = "验证错误2" }, APIResultCodeEnum.Unauthorized);
            }

            var account = await ApiAccountCore.GetOneAsync(a);
            if (account == null)
            {
                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }
            string app_sign = $"{account.api_secret}@{t}".MD5();
            if (sign != app_sign)
            {
                return new APIResult(new { success = false, message = "验证错误4" }, APIResultCodeEnum.Unauthorized);
            }
            var request = new UnionParseRequest
            {
                Content = content,
                Channel = channel,
                CommerceType = commerceType,
                Ip = ip,
                Oaid = oaid,
                RiskStrategy = riskStrategy,
                LaunchScene = launchScene,
                AccountId = 0,
                SpecialText = special_text,
                QueryText = query_text,
                ClickId = clickId,
                Type = type,
                Pic = pic,
            };
            return await UnionParseCore.UnionParseAsync(request);
        }

        [HttpPost]
        public async Task<ActionResult> unsafeParse([FromBody] JsonElement form)
        {
            var content = form.Read("s", string.Empty);
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var clickId = form.Read("clickId", string.Empty);
            var type = form.Read("type", string.Empty);
            int accountid = form.Read("aid", 0);
            var commerceType = form.Read<int>("commerceType", 0);
            var riskStrategy = form.Read("riskStrategy", string.Empty);
            var launchScene = form.Read<int>("launchScene", -1);
            var special_text = form.Read<int>("special_text", -1);
            var query_text = form.Read("query_text", string.Empty);
            var pic = form.Read("pic", string.Empty);

#if DEBUG
            //ip = "127.0.0.1";
            //oaid = "test-oaid";
#endif
            var request = new UnionParseRequest
            {
                Content = content,
                Channel = channel,
                CommerceType = commerceType,
                Ip = ip,
                Oaid = oaid,
                RiskStrategy = riskStrategy,
                LaunchScene = launchScene,
                AccountId = accountid,
                SpecialText = special_text,
                QueryText = query_text,
                ClickId = clickId,
                Type = type,
                Pic = pic,
            };
            return await UnionParseCore.UnionParseAsync(request);
        }


        [HttpPost]
        public async Task<ActionResult> unsafeBatchParse([FromBody] JsonElement form)
        {
            var content = form.PathReadArray("s[]", string.Empty);
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var clickId = form.Read("clickId", string.Empty);
            var type = form.Read("type", string.Empty);
            int accountid = form.Read("aid", 0);
            int count = form.Read("count", 0);
            var commerceType = form.Read<int>("commerceType", 0);
            //入参参数。brw-浏览器，qapp-快应用
            var riskStrategy = form.Read("riskStrategy", string.Empty);
            var launchScene = form.Read<int>("launchScene", -1);
            var special_text = form.Read<int>("special_text", -1);
            var query_text = form.Read("query_text", string.Empty);
            var pic = form.Read("pic", string.Empty);

#if DEBUG
            //ip = "127.0.0.1";
            //oaid = "test-oaid";
#endif
            for (int i = 0; i < count; i++)
            {
                var request = new UnionParseRequest
                {
                    Content = content[i],
                    Channel = channel,
                    CommerceType = commerceType,
                    Ip = ip,
                    Oaid = oaid,
                    RiskStrategy = riskStrategy,
                    LaunchScene = launchScene,
                    AccountId = accountid,
                    SpecialText = special_text,
                    QueryText = query_text,
                    ClickId = clickId,
                    Type = type,
                    Pic = pic,
                };
                _ = await UnionParseCore.UnionParseAsync(request);
            }
            return new APIResult(new { msg = "ok" });
        }



        [HttpPost]
        public async Task<ActionResult> unionCoupon([FromBody] JsonElement form, [FromQuery] string a = "", [FromQuery] int t = 0, [FromQuery] string sign = "")
        {
            //正文
            var content = form.Read("s", string.Empty);
            var dplink = form.Read("dp", string.Empty);
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var clickId = form.Read("clickId", string.Empty);
            var style = form.Read("style", string.Empty);

            //验证签名
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(sign))
            {
                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            DateTime time1 = t.Convert2Datetime();
            if (time1 < DateTime.Now.AddMinutes(-10))
            {
                return new APIResult(new { success = false, message = "验证错误2" }, APIResultCodeEnum.Unauthorized);
            }

            var account = await ApiAccountCore.GetOneAsync(a);
            if (account == null)
            {
                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }
            string app_sign = $"{account.api_secret}@{t}".MD5();
            if (sign != app_sign)
            {
                return new APIResult(new { success = false, message = "验证错误4" }, APIResultCodeEnum.Unauthorized);
            }
            return await UnionCouponCore.UnionCouponAsync(content, dplink, channel, style, ip, oaid, clickId);
        }


        [HttpPost]
        public async Task<ActionResult> unsafeCoupon([FromBody] JsonElement form)
        {
            var content = form.Read("s", string.Empty);
            var dplink = form.Read("dp", string.Empty);
            var channel = form.Read("c", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var style = form.Read("style", string.Empty);
            var clickId = form.Read("clickId", string.Empty);
#if DEBUG
            ip = "127.0.0.1";
            oaid = "test-oaid";
#endif
            return await UnionCouponCore.UnionCouponAsync(content, dplink, channel, style, ip, oaid, clickId);
        }


        [HttpGet]
        public async Task<ActionResult> jd_parse(string s, string s2 = "", string ip = "", string oaid = "")
        {
            UnionParseRequest request = new()
            {
                Content = s,
                Ip = ip,
                Oaid = oaid,
                RiskStrategy = string.Empty,
                LaunchScene = 0,
            };

            var result = JdUnionPlus.GetFormattedObject(request);
            string body = "";
            string content = s.UrlDecode();
            string content2 = s2.UrlDecode();
            try
            {

                if (AlimamaPlus.ShouldIgnoreRequest(request, out string reason))
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = reason;
                    result.rawContent = content;
                    result.rawContent2 = content2;
                    _ = TkLogCore.LogAsync(result);
                    return new APIResult(result);
                }

                var api = DataokeCore.GetOne();
                if (api == null)
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "没有匹配账号";
                    result.rawContent = content;
                    result.rawContent2 = content2;
                    _ = TkLogCore.LogAsync(result);
                    return new APIResult(result);
                }

                var account = await JdPoolCore.GetOneAsync();
                if (account == null)
                {
                    result.success = false;
                    result.message = "放弃转链";
                    result.reason = "没有匹配账号";
                    result.rawContent = content;
                    result.rawContent2 = content2;
                    _ = TkLogCore.LogAsync(result);
                    return new APIResult(result);
                }
                result = DataokeCore.JdParse(result, api, account, content);
            }
            catch (Exception ex)
            {

                _ = new LoggerLibrary("api_error")
                    .Info(s, s2)
                    .Info("【jd】", body)
                    .Info(ex.Message, ex.StackTrace)
                    .SaveAsync();
                NotifyCore.Notify(new NifyMessage
                {
                    message = $"【转链接口异常】\n{content}\n{content2}\n{body}\n\n{ex.Message}\n{ex.StackTrace}",
                    priority = NifyMessagePriority.high,
                    tags = ["red_circle"]
                });
                result.success = false;
                result.message = "放弃转链";
                result.reason = "转链接口异常";
            }
            result.rawContent = content;
            result.rawContent2 = content2;
            _ = TkLogCore.LogAsync(result);
            return new APIResult(new
            {
                result.success,
                result.message,
                result.shortLinkurl,
                result.itemId,
                result.itemName,
                result.deeplink_url,
            });
        }


        [HttpGet]
        public async Task<ActionResult> Reload()
        {
            await EndPointCore.NotifyReload();
            return new APIResult(new
            {
                success = true,
                message = "ok",
            });
        }

        [HttpGet]
        public async Task<ActionResult> dplist([FromQuery] string query = "", [FromQuery] string a = "", [FromQuery] int t = 0, [FromQuery] string sign = "")
        {
            var clientIp = _accessor.HttpContext.GetUserIp();
            //验证签名
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(sign))
            {
                _ = new LoggerLibrary("api", "dplist_error")
                    .Info($"{clientIp}\t{query}")
                    .Info($"{a}\t{sign}\t{t}")
                    .Info("验证错误")
                    .SaveAsync();

                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            DateTime time1 = t.Convert2Datetime();
            if (time1 < DateTime.Now.AddMinutes(-10))
            {
                _ = new LoggerLibrary("api", "dplist_error")
                    .Info($"{clientIp}\t{query}")
                    .Info($"{a}\t{sign}\t{t}")
                    .Info("验证错误2")
                    .SaveAsync();
                return new APIResult(new { success = false, message = "验证错误2" }, APIResultCodeEnum.Unauthorized);
            }

            var account = await ApiAccountCore.GetOneAsync(a);
            if (account == null)
            {
                _ = new LoggerLibrary("api", "dplist_error")
                    .Info($"{clientIp}\t{query}")
                    .Info($"{a}\t{sign}\t{t}")
                    .Info("验证错误3")
                    .SaveAsync();

                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }
            string app_sign = $"{account.api_secret}@{t}".MD5();
            if (sign != app_sign)
            {
                _ = new LoggerLibrary("api", "dplist_error")
                    .Info($"{clientIp}\t{query}")
                    .Info($"{a}\t{sign}\t{t}")
                    .Info("验证错误4")
                    .SaveAsync();

                return new APIResult(new { success = false, message = "验证错误4" }, APIResultCodeEnum.Unauthorized);
            }

            if (string.IsNullOrEmpty(query))
            {
                _ = new LoggerLibrary("api", "dplist_error")
                    .Info($"{clientIp}\t{query}")
                    .Info($"{a}\t{sign}\t{t}")
                    .Info("查询条件不能为空")
                    .SaveAsync();

                return new APIResult(new { success = false, message = "查询条件不能为空" });
            }
            int[] report_account_ids = account.report_account_ids.TryToArray<int>(',');
            int[] report_exclude_account_ids = account.report_exclude_account_ids.TryToArray<int>(',');

            string filter = $"batchId=@query";
            var account_list = await TkPoolCore.ListAsync();
            List<int> account_ids = [];
            if (account_list.Any())
            {
                account_ids = account_list.Where(e => e.enable_fake_click).Select(e => e.id).ToList();

                if (report_account_ids.Length > 0)
                {
                    account_ids = account_ids.Intersect(report_account_ids).ToList();
                }

                if (report_exclude_account_ids.Length > 0)
                {
                    account_ids = account_ids.Except(report_exclude_account_ids).ToList();
                }
                filter += $" AND accountId IN @account_ids";
            }
            string orderBy = "paid_time ASC";

            var data = new DBContext.Table("tk_order_tracking")
                .Where(filter, new { query, account_ids })
                .Order(orderBy)
                .Select<TkOrderTrackingDTO>();

            //fake_click_link_type


            List<object> list = [];
            foreach (var item in data)
            {
                list.Add(new { pid = item.accountId, url = item.deeplinkUrl, item.shortLinkUrl, count = item.click_num, time = item.exp_time });
            }

            var ids = data.Select(e => e.Id).ToArray();

            _ = new LoggerLibrary("api", "dplist")
                 .Info($"{clientIp}\t{query}\tcount:{list.Count}")
                 .Info(string.Join(',', ids))
                 .SaveAsync();

            var update = new DBContext.Table("tk_order_tracking")
                .Add("last_pull_time", DateTime.Now)
                .Add("last_pull_account", account.name)
                .Add("clicked_num:", "clicked_num+1")
                .Where("id IN @ids", new { ids })
                .Update();

            return new APIResult(new
            {
                success = true,
                message = list.Count == 0 ? "none" : "ok",
                count = list.Count,
                data = list,
            });
        }


        [HttpGet]
        public async Task<ActionResult> unsafeParseDpList([FromQuery] string a = "", [FromQuery] string query = "")
        {
            if (string.IsNullOrEmpty(a))
            {
                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            var account = await ApiAccountCore.GetOneAsync(a);
            if (account == null || !account.enable_report)
            {
                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }

            if (string.IsNullOrEmpty(query))
            {
                return new APIResult(new { success = false, message = "查询条件不能为空" });
            }

            int[] report_account_ids = account.report_account_ids.TryToArray<int>(',');
            int[] report_exclude_account_ids = account.report_exclude_account_ids.TryToArray<int>(',');

            string filter = $"batchId=@query";
            var account_list = await TkPoolCore.ListAsync();
            List<int> account_ids = [];
            if (account_list.Any())
            {
                account_ids = account_list.Where(e => e.enable_fake_click).Select(e => e.id).ToList();

                if (report_account_ids.Length > 0)
                {
                    account_ids = account_ids.Intersect(report_account_ids).ToList();
                }

                if (report_exclude_account_ids.Length > 0)
                {
                    account_ids = account_ids.Except(report_exclude_account_ids).ToList();
                }
                filter += $" AND accountId IN @account_ids";
            }

            string orderBy = "paid_time ASC";

            var data = new DBContext.Table("tk_order_tracking")
                .Where(filter, new { query, account_ids })
                .Order(orderBy)
                .Select<TkOrderTrackingDTO>();

            List<object> list = [];
            foreach (var item in data)
            {
                list.Add(new { pid = item.accountId, url = item.deeplinkUrl, item.shortLinkUrl, count = item.click_num, time = item.exp_time });
            }
            var clientIp = _accessor.HttpContext.GetUserIp();
            LoggerLibrary log = new LoggerLibrary("api", "unsafeParseDpList");
            log.Info($"{clientIp}\t{query}\tcount:{list.Count}");

            var ids = data.Select(e => e.Id).ToArray();
            log.Info(string.Join(',', ids));
            _ = log.SaveAsync();

            return new APIResult(new
            {
                success = true,
                message = list.Count == 0 ? "none" : "ok",
                count = list.Count,
                data = list,
            });
        }



        [HttpPost]
        public async Task<ActionResult> dataReport([FromBody] JsonElement form, [FromQuery] string a = "", [FromQuery] int t = 0, [FromQuery] string sign = "")
        {
            bool debug = form.Read("debug", false);
            var clientIp = _accessor.HttpContext.GetUserIp();
            var log = new LoggerLibrary("ApiReportCore", "dataReport");
            log.Info(clientIp);

            //验证签名
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(sign))
            {
                _ = log.Info($"a:{a}\tt:{t}\tsign:{sign}\t", $"message:验证错误")
                    .Info(form.GetRawText())
                    .SaveAsync();
                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            DateTime time1 = t.Convert2Datetime();
            if (time1 < DateTime.Now.AddMinutes(-10))
            {
                _ = log.Info($"a:{a}\tt:{t}\tsign:{sign}\t", $"message:验证错误2")
                    .Info(form.GetRawText())
                    .SaveAsync();
                return new APIResult(new { success = false, message = "验证错误2" }, APIResultCodeEnum.Unauthorized);
            }

            var account = await ApiAccountCore.GetOneAsync(a);
            if (account == null)
            {
                _ = log.Info($"a:{a}\tt:{t}\tsign:{sign}\t", $"message:验证错误3")
                    .Info(form.GetRawText())
                    .SaveAsync();
                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }
            string app_sign = $"{account.api_secret}@{t}".MD5();
            if (sign != app_sign)
            {
                _ = log.Info($"a:{a}\tt:{t}\tsign:{sign}\tapp_sign:{app_sign}", $"message:验证错误4")
                    .Info(form.GetRawText())
                    .SaveAsync();
                return new APIResult(new { success = false, message = "验证错误4" }, APIResultCodeEnum.Unauthorized);
            }

            try
            {
                //0:全分销类型;-1:各分销类型，1:goods 2: live 3:video 4: profile 5: unknown
                int distributiontype = form.Read("distributiontype", 0);

                //0:全平台;-1:各平台;1:淘宝 2:京东 2:多多
                int platform = form.Read("platform", 0);

                var data = await ApiReportCore.ReportDailysAsync(form, clientIp, debug);
                _ = log.Info(form.GetRawText(), data.Convert2Json()).SaveAsync();
                return new APIResult(new { success = true, platform, distributiontype, data });
            }
            catch (Exception ex)
            {
                _ = log.Info(form.GetRawText()).Info(ex.Message, ex.StackTrace).SaveAsync();
                return new APIResult(new { success = false, message = "内部错误" });
            }
        }


        [HttpPost]
        public async Task<ActionResult> unsafeDataReport([FromBody] JsonElement form)
        {
            bool debug = form.Read("debug", false);
            var clientIp = _accessor.HttpContext.GetUserIp();
            var log = new LoggerLibrary("ApiReportCore", "unsafeDataReport");
            log.Info(clientIp);

            try
            {
                //0:全分销类型;-1:各分销类型，1:goods 2: live 3:video 4: profile 5: unknown
                int distributiontype = form.Read("distributiontype", 0);

                //0:全平台;-1:各平台;1:淘宝 2:京东
                int platform = form.Read("platform", 0);

                var data = await ApiReportCore.ReportDailysAsync(form, clientIp, debug);
                _ = log.Info(form.GetRawText(), data.Convert2Json()).SaveAsync();
                return new APIResult(new { success = true, platform, distributiontype, data });
            }
            catch (Exception ex)
            {
                _ = log.Info(form.GetRawText()).Info(ex.Message, ex.StackTrace).SaveAsync();
                return new APIResult(new { success = false, message = "内部错误" });
            }
        }

    }
}
