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;
using static Microsoft.Extensions.Logging.EventSource.LoggingEventSource;
using molilian.core.PushDataReport;
using System.Threading;
using OfficeOpenXml.DataValidation.Exceptions;
namespace molilian.api.Controllers
{
    [ApiController]
    [MyAuthorize("admin")]
    [Route("api/[controller]/[action]")]
    public class DataReportController : ControllerBase
    {
        readonly IAuthorizationProvider provider = new AdminProvider();
        protected IHttpContextAccessor _accessor;
        public DataReportController(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;

            // 临时锁定所有口令推送数据
            //string filter = "type<>1";

            int type = form.Read("type", 0);
            if (type > 0) filter += $" AND type = @type";


            int status = form.Read("status", -1);
            if (status != -1) filter += $" AND status = @status";

            int is_settlement = form.Read("is_settlement", -1);
            if (is_settlement != -1) filter += $" AND is_settlement = @is_settlement";


            int platform = form.Read("platform", 0);
            if (platform > 0) filter += $" AND platform = @platform";

            var report_date = form.Read<DateTime>("report_date", DateTime.MinValue);
            if (report_date != DateTime.MinValue) filter += $" AND report_date = @report_date";


            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("push_data_report")
               .Where(filter, new { type, report_date, is_settlement, status, platform })
               .Page(size, page)
               .Order(orderBy)
               .PageList<dynamic>(getTotal);

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



        [HttpPost]
        public async Task<ActionResult> push([FromBody] JsonElement form)
        {
            int id = form.Read<int>("id");

            using var conn = DBContext.GetOpenConnection();
            var item = new DBContext.Table(conn, "push_data_report").Get<PushDataReportDTO>("id=@id", new { id });
            if (item == null) return new APIResult(new { data = new { success = false, msg = "PUSH失败，记录不存在" } });

            // 临时锁定所有口令推送数据
            //if (item.type == 1) return new APIResult(new { data = new { success = false, msg = "PUSH失败，类型错误" } });

            PushDataReportPush plus = new PushDataReportPush();

            item.request_id = Guid.NewGuid().ToString();
            var response = await plus.PushReportData(item);

            bool success = response.code == 200;
            if (!success)
            {
                item.request_id = $"{item.request_id}:{response.message}";
            }

            new DBContext.Table("push_data_report")
                        .Add("status", success)
                        .Add("request_id", item.request_id)
                        .Add("update_time", DateTime.Now)
                        .Add("last_push_time", DateTime.Now)
                        .Where("id=@id", new { id })
                        .Update();

            return new APIResult(new
            {
                data = new { success, msg = success ? "Push成功" : "Push失败" },
            });
        }


        [HttpPost]
        public async Task<ActionResult> delete([FromBody] JsonElement form)
        {
            int id = form.Read<int>("id");

            using var conn = DBContext.GetOpenConnection();
            var item = new DBContext.Table(conn, "push_data_report").Get<PushDataReportDTO>("id=@id", new { id });
            if (item == null) return new APIResult(new { data = new { success = false, msg = "删除失败，记录不存在" } });

            // 临时锁定所有口令推送数据
            //if (item.type == 1) return new APIResult(new { data = new { success = false, msg = "删除失败，类型错误" } });

            var result = new DBContext.Table("push_data_report").Delete("id=@id", new { id });
            bool success = result > 0;
            return new APIResult(new
            {
                data = new { success, msg = success ? "删除成功" : "删除失败" },
            });
        }


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

            using var conn = DBContext.GetOpenConnection();
            int result = 0;
            bool success = false;

            try
            {
                int id = from.Read("id", 0);
                var report_date = from.Read<DateTime>("report_date", DateTime.Now).Date;
                var platform = from.Read<int>("platform", 0);
                var type = from.Read<int>("type", 0);

                // 临时锁定所有口令推送数据
                //if (type == 1) return new APIResult(new { data = new { success = false, msg = "更新失败，类型错误" } });

                var update = new DBContext.Table("push_data_report");

                //PushDataReportCore core = new();
                //await core.FillCpsCouponData(report_date);

                //return new APIResult(new
                //{
                //    data = new { success = false, msg = $"更新失败，test" },
                //});

                update.Fill(from);
                update.Add("report_date", report_date);
                update.Loader<bool>("is_settlement");
                update.Loader<int>("status");
                update.Loader<int>("type");
                update.Loader<int>("sub_type");
                update.Loader<int>("platform");
                update.Loader<string>("platform_name");
                update.Loader<string>("adId");
                update.Loader<string>("adzoneId");
                update.Loader<int>("distribution");
                update.Loader<int>("req_count");
                update.Loader<int>("dp_transition_succ_count");
                update.Loader<int>("transition_succ_count");
                update.Loader<int>("expose_count");
                update.Loader<int>("expose_user_count");
                update.Loader<int>("click_count");
                update.Loader<int>("click_user_count");
                update.Loader<int>("app_open_count");
                update.Loader<int>("app_open_user_count");
                update.Loader<int>("order_count");
                update.Loader<int>("order_user_count");
                update.Loader<decimal>("gmv");
                update.Loader<decimal>("income");

                if (id == 0)
                {

                    result = update.Create();
                    success = result > 0;
                    if (success)
                    {
                        OperationLogCore.LogOperation(token.AccessKey, clientIp, $"push_data_report:{report_date}:{platform}:{type}", from.Convert2Json(), "新增");
                    }
                }
                else
                {
                    var item = new DBContext.Table(conn, "push_data_report").Get<PushDataReportDTO>("id=@id", new { id });
                    if (item == null) return new APIResult(new { data = new { success = false, msg = "更新失败，记录不存在" } });

                    result = update.Where("id=@id", new { id }).Update();

                    success = result > 0;
                    if (success)
                    {
                        var newItem = new DBContext.Table(conn, "push_data_report").Get<PushDataReportDTO>("id=@id", new { id });
                        string desc = ObjectComparer.PrintCompareToString(item, newItem).Trim();
                        OperationLogCore.LogOperation(token.AccessKey, clientIp, $"push_data_report:{report_date}:{platform}:{type}", item.Convert2Json(), desc);
                    }
                }
            }
            catch (Exception ex)
            {
                return new APIResult(new
                {
                    data = new { success = false, msg = $"更新失败，{ex.Message}" },
                });
            }
            return new APIResult(new
            {
                data = new { success, msg = success ? "更新成功" : "更新失败，请检查输入信息" },
            });
        }




    }
}