using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;
using System.IO;
using System.Text;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/[controller]/[action]")]
    public class PrizeController : BaseController
    {
        public PrizeController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }



        #region 获取奖励日志
        [Route("/v1/pri/PriLog/getPriLogDetail")]
        public Dictionary<string, object> Set(string value)
        {
            Utils.WriteLog(DateTime.Now.ToString() + "\n" + value, "获取奖励日志");
            JsonData data = JsonMapper.ToObject(value);
            string DataNo = data["data_no"].ToString();
            string PrizeKind = "0"; //data["prize_kind"].ToString();

            string content = function.PostWebRequest("https://logic-executor.kexiaoshuang.com/noauth/pri/logdetail", "value={\"data_no\":\"" + DataNo + "\",\"prize_kind\":\"" + PrizeKind + "\"}");
            content = content.Replace(": null", ": \"\"");
            Dictionary<string, object> result = new Dictionary<string, object>();
            JsonData json = JsonMapper.ToObject(content);
            result.Add("data", json["data"].ToJson());
            result.Add("status", json["status"].ToString());
            result.Add("msg", "成功");
            return result;
        }
        public string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7,
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
        #endregion



        #region 创客-翻倍活动
        // [Authorize]
        [Route("/api/v1/ActivityProgressBar/List")]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }

        public Dictionary<string, object> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            var lastmonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            var thismonth = DateTime.Now.ToString("yyyyMM");
            DateTime start = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
            DateTime end = DateTime.Now.AddDays(16 - DateTime.Now.Day).Date;
            // DateTime end = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);//本月月底

            int IsBuy = 0;//是否参与(0-否 1-是)
            Orders od = maindb.Orders.FirstOrDefault(m => m.UserId == UserId && m.TotalPrice == 88 && m.Status > 0 && m.CreateDate >= start && m.CreateDate <= end);
            if (od != null)
            {
                IsBuy = 1;
                string UserIdString = "," + UserId + ",";
                List<Users> users = maindb.Users.Where(m => m.ParentNav.Contains(UserIdString) || m.Id == UserId).ToList();
                List<int> uids = new List<int>();
                List<int> uids2 = new List<int>();
                foreach (var user in users)
                {
                    uids.Add(user.Id);
                }
                var orders = maindb.Orders.Select(m => new { m.Id, m.UserId, m.TotalPrice, m.Status, m.CreateDate }).Where(m => m.TotalPrice == 88 && m.Status > 0 && uids.Contains(m.UserId) && m.CreateDate >= start && m.CreateDate <= end).ToList();
                foreach (var order in orders)
                {
                    uids2.Add(order.UserId);
                }
                users = users.Where(m => uids2.Contains(m.Id)).ToList();
                List<ProgressUserList> list = new List<ProgressUserList>();
                foreach (Users user in users)
                {
                    int IsOk = 0;//是否达标(0-否 1-是)
                    decimal lastMonthAmt = maindb.TradeDaySummary.Where(m => m.TradeMonth == lastmonth && m.SeoTitle == "team" && m.UserId == user.Id).Sum(m => m.HelpNonDirectTradeAmt + m.NotHelpNonDirectTradeAmt);
                    decimal thisMonthAmt = maindb.TradeDaySummary.Where(m => m.TradeMonth == thismonth && m.SeoTitle == "team" && m.UserId == user.Id).Sum(m => m.HelpNonDirectTradeAmt + m.NotHelpNonDirectTradeAmt);
                    if (thisMonthAmt >= lastMonthAmt * 2)
                    {
                        IsOk = 1;
                    }
                    ProgressUserList item = new ProgressUserList()
                    {
                        LastMonth = lastMonthAmt,
                        ThisMonth = thisMonthAmt,
                        UserId = user.Id,
                        IsOk = IsOk,
                        ParentNav = user.ParentNav
                    };
                    list.Add(item);
                }
                list = list.OrderBy(m => m.ParentNav).ToList();
                int index = 0;
                decimal selfTrade = 0; // 自己的本月交易额
                decimal lastTrade = 0; // 自己的上月交易额
                decimal totalTrade = 0; // 自己的本月目标交易额
                string selfNav = ""; // 自己的ParentNav
                List<string> ParentNavs = new List<string>();
                if (list.Count > 0)
                {
                    foreach (ProgressUserList sub in list)
                    {
                        index += 1;
                        if (index == 1)
                        {
                            selfTrade = sub.ThisMonth;
                            lastTrade = sub.LastMonth;
                            totalTrade = lastTrade * 2;
                            selfNav = sub.ParentNav + "," + sub.UserId + ",";
                        }
                        else
                        {
                            bool op = true; //是否满足条件
                            string ParentNav = sub.ParentNav + "," + sub.UserId + ",";
                            foreach (string subNav in ParentNavs)
                            {
                                if (ParentNavs.Contains(ParentNav) && ParentNav != subNav)
                                {
                                    op = false;
                                }
                            }
                            if (op)
                            {
                                if (sub.IsOk == 1)
                                {
                                    selfTrade -= sub.ThisMonth;
                                    totalTrade -= sub.ThisMonth;
                                }
                            }
                            ParentNavs.Add(ParentNav);
                        }
                    }
                }
                if (lastTrade * 2 < 2000000 || selfTrade == 0 || totalTrade < 2000000)
                {
                    totalTrade = 2000000;
                }
                Obj.Add("IsBuy", IsBuy);
                Obj.Add("SelfTrade", selfTrade);
                Obj.Add("LastTrade", lastTrade);
                Obj.Add("TotalTrade", totalTrade);
                return Obj;
            }
            else
            {
                Obj.Add("IsBuy", IsBuy);
                return Obj;
            }

        }
        #endregion


    }
}

