using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySystem.Models;
using Library;
using System.Security.Cryptography;
using System.Text;
using System.IO;

namespace MySystem.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Error()
        {
            string isapi = Request.Headers["Api"].ToString();
            if (isapi != "1")
            {
                if (Response.StatusCode == 500)
                {
                    return Redirect("/public/errpage/pc/500.html");
                }
                else if (Response.StatusCode == 502)
                {
                    return Redirect("/public/errpage/pc/502.html");
                }
                else if (Response.StatusCode == 404)
                {
                    return Redirect("/public/errpage/pc/404.html");
                }
            }
            return View();
        }



        // 推荐王奖励666 // TODO:待完善
        public string InvitePrize666(string month)
        {
            DateTime start = DateTime.Parse(month + "-01 00:00:00");
            DateTime end = start.AddMonths(1);
            string TradeMonth = start.ToString("yyyyMM");
            List<RecommendPriceList> userdic = new List<RecommendPriceList>();
            WebCMSEntities db = new WebCMSEntities();
            //判断当月是否下单
            bool checkOrder = db.Orders.Any(m => m.PayDate >= start && m.PayDate < end && m.Status > 0 && m.TotalPrice == 66);
            if(checkOrder)
            {
                //统计当月下单名单
                List<int> uids = db.Orders.Where(m => m.PayDate >= start && m.PayDate < end && m.Status > 0 && m.TotalPrice == 66).ToList().Select(m => m.UserId).Distinct().ToList();
                foreach(int uid in uids)
                {
                    int ActCount = 0;
                    List<Users> users = db.Users.Where(m => m.ParentUserId == uid && m.AuthFlag == 1 && m.AuthDate >= start).ToList();
                    foreach(Users user in users)
                    {
                        int BeforeActCount = db.PosMachinesTwo.Count(m => m.BuyUserId == user.Id && m.ActivationState == 1 && m.ActivationTime < start);
                        if(BeforeActCount == 0)
                        {
                            decimal tradeAmt = 0; //机具总交易额
                            int actPosCount = 0; //激活机具数量
                            //查询当前创客所属机具
                            var posList = db.PosMachinesTwo.Select(m => new { m.ActivationState, m.ActivationTime, m.BuyUserId, m.BindMerchantId }).Where(m => m.BuyUserId == user.Id && m.ActivationState == 1 && m.ActivationTime >= start && m.ActivationTime < end).ToList();
                            if(posList.Count > 0)
                            {
                                actPosCount = posList.Count;
                                foreach(var pos in posList)
                                {
                                    //查询机具交易额
                                    bool checkTrade = db.PosMerchantTradeSummay.Any(m => m.MerchantId == pos.BindMerchantId && m.TradeMonth == TradeMonth);
                                    if(checkTrade)
                                    {
                                        tradeAmt += db.PosMerchantTradeSummay.Where(m => m.MerchantId == pos.BindMerchantId && m.TradeMonth == TradeMonth).Sum(m => m.TradeAmount);
                                    }
                                }                                
                                decimal AvgTradeAmount = tradeAmt / actPosCount;
                                if(AvgTradeAmount >= 30000 && actPosCount >= 3)
                                {
                                    ActCount += 1;
                                }
                            }
                        }
                    }
                    RecommendPriceList item = userdic.FirstOrDefault(m => m.UserId == uid);
                    if(item != null)
                    {
                        item.ActCount += ActCount;
                    }
                    else
                    {
                        userdic.Add(new RecommendPriceList()
                        {
                            UserId = uid,
                            ActCount = ActCount,
                        });
                    }
                }
            }
            string html = "<table>";
            foreach(RecommendPriceList item in userdic)
            {
                string status = "未达标";
                if(item.ActCount >= 6)
                {
                    status = "已达标";
                }
                Users user = db.Users.FirstOrDefault(m => m.Id == item.UserId) ?? new Users();
                int subCount = db.Users.Count(m => m.ParentUserId == item.UserId && m.AuthFlag == 1 && m.AuthDate >= start);
                html += "<tr>";
                html += "<td>" + user.MakerCode + "</td>"; //创客编号
                html += "<td>" + user.RealName + "</td>"; //创客姓名
                html += "<td>" + subCount + "</td>"; //推荐总数
                html += "<td>" + item.ActCount + "</td>"; //成功推荐数
                html += "<td>" + status + "</td>"; //是否达标
                html += "</tr>";
            }
            html += "</table>";
            db.Dispose();
            return html;
        }

        // 创客达标返600
        public string shopOrder()
        {
            string html = "<table>";
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = "server=47.108.231.170;port=3306;user=KxsMain;password=mzeqjriUWore0dwT;database=KxsMainServer;charset=utf8;ConnectionTimeout=600;DefaultCommandTimeout=600;";
            DataTable pos = OtherMySqlConn.dtable("select");
            // DataTable dt = OtherMySqlConn.dtable("select BuyUserId,count(Id) from PosMachinesTwo where BuyUserId in (select DISTINCT UserId from Orders where TotalPrice=600 and `Status`>0 and CreateDate<'2022-07-01 00:00:00') and ActivationState=1 and ActivationTime<'2022-07-01 00:00:00' group by BuyUserId HAVING count(Id)>=20");
            DataTable dt = OtherMySqlConn.dtable("select BuyUserId,count(Id) from PosMachinesTwo where ActivationState=1 and ActivationTime<'2022-07-01 00:00:00' and BuyUserId in (69542,124745) group by BuyUserId HAVING count(Id)>=20");
            foreach(DataRow dr in dt.Rows)
            {
                int BuyUserId = int.Parse(dr["BuyUserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == BuyUserId) ?? new Users();
                int ActCount = int.Parse(dr[1].ToString());
                decimal TradeAmount = 0;
                DataTable dtTrade = OtherMySqlConn.dtable("select sum(TradeAmount) from PosMerchantTradeSummay where TradeMonth='202206' and MerchantId in (select DISTINCT BindMerchantId from PosMachinesTwo where BuyUserId=" + BuyUserId + " and ActivationState=1 and ActivationTime<'2022-07-01 00:00:00')");
                if(dtTrade.Rows.Count > 0)
                {
                    TradeAmount = decimal.Parse(function.CheckNum(dtTrade.Rows[0][0].ToString()));
                }
                decimal AvgTradeAmount = TradeAmount / ActCount;
                string Result = "未达标";
                if(AvgTradeAmount >= 30000)
                {
                    Result = "达标";
                }
                html += "<tr>";
                html += "<td>" + user.MakerCode + "</td>";
                html += "<td>" + user.RealName + "</td>";
                html += "<td>" + ActCount + "</td>";
                html += "<td>" + TradeAmount + "</td>";
                html += "<td>" + AvgTradeAmount.ToString("f2") + "</td>";
                html += "<td>" + Result + "</td>";
                html += "</tr>";
            }
            html += "</table>";
            db.Dispose();
            return html;
        }
    
        public string test(string p)
        {
            
            // BsModels.WebCMSEntities db = new BsModels.WebCMSEntities();
            // var sysadmins = db.SysAdmin.ToList();
            // foreach(var sysadmin in sysadmins)
            // {
            //     BsModels.SysAdmin edit = db.SysAdmin.FirstOrDefault(m => m.Id == sysadmin.Id);
            //     if(edit != null)
            //     {
            //         string pwd = function.get_Random(8);
            //         edit.Password = function.MD5_32(pwd);
            //         db.SaveChanges();
            //         function.WriteLog(edit.AdminName + ":" + pwd, "pwd");
            //     }
            // }
            // db.Dispose();

            // WebCMSEntities db = new WebCMSEntities();
            // List<string> nos = new List<string>();
            // nos.Add("BC2024010814562964923941884");
            // List<UserCashRecord> list = db.UserCashRecord.Where(m => nos.Contains(m.CashOrderNo)).ToList();
            // foreach (UserCashRecord edit in list)
            // {
            //     RedisDbconn.Instance.AddList("JkCashPayApplyQueue", Newtonsoft.Json.JsonConvert.SerializeObject(edit));
            // }
            return "ok";
        }

        private SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
        public string DecryptString(string Value, string sKey, string sIV = "12345678")
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            DES.Key =  Convert.FromBase64String(sKey);
            DES.Mode = CipherMode.CBC;
            DES.Padding = System.Security.Cryptography.PaddingMode.None;
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sIV);
            ICryptoTransform DESDecrypt = DES.CreateDecryptor();
            string result = "";
            try
            {
                byte[] Buffer = Convert.FromBase64String(Value);

                result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));

                //MemoryStream msDecrypt = new MemoryStream(Buffer);
                //CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                //       DES.CreateDecryptor(DES.Key, DES.IV),
                //       CryptoStreamMode.Read);

                //// Create buffer to hold the decrypted data.
                //byte[] fromEncrypt = new byte[Buffer.Length];

                //// Read the decrypted data out of the crypto stream
                //// and place it into the temporary buffer.
                //csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                //result = System.Text.Encoding.Default.GetString(fromEncrypt);
            }
            catch (Exception e)
            {
                result = e.ToString();
            }
            return result;
        }



        public string cash()
        {
            WebCMSEntities db = new WebCMSEntities();
            List<int> ids = new List<int>();
            ids.Add(179761);
            ids.Add(180213);
            ids.Add(180651);
            ids.Add(180810);
            ids.Add(181026);
            ids.Add(181187);
            ids.Add(181300);
            ids.Add(181376);
            ids.Add(181428);
            ids.Add(181468);
            ids.Add(181601);
            ids.Add(181814);
            foreach(int Id in ids)
            {
                UserCashRecord edit = db.UserCashRecord.FirstOrDefault(m => m.Id == Id && m.Status == 0);
                if (edit != null)
                {
                    edit.Status = 2;
                    edit.Remark = "出款银行故障，请重试";
                    edit.UpdateMan = "系统";
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == edit.UserId);
                    if (account != null)
                    {
                        decimal TradeAmount = edit.TradeAmount;
                        decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                        account.BalanceAmount += TradeAmount;
                        // if (account.FreezeAmount >= TradeAmount)
                        // {
                            account.FreezeAmount -= TradeAmount;
                            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                            db.UserAccountRecord.Add(new UserAccountRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = edit.UserId, //创客
                                ChangeType = 6, //变动类型
                                ProductType = 99, //产品类型
                                ChangeAmount = TradeAmount, //变更金额
                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            });
                            db.SaveChanges();
                        // }
                        // else
                        // {
                        //     function.WriteLog(Id.ToString(), "冻结金额不足");
                        // }
                    }
                }
            }
            db.Dispose();
            return "ok";
        }
    }
}