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.PxcModels;
using System.Threading;
using Library;
using LitJson;
using System.Security.Cryptography;

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();
        }

        // 大盟主标记扫描
        public string leaderflag()
        {
            WebCMSEntities db = new WebCMSEntities();
            List<int> ids = new List<int>();
            // List<PosCouponRecord> records = db.PosCouponRecord.Where(m => m.FromUserId == 597).ToList();
            // foreach(PosCouponRecord record in records)
            // {
            //     ids.Add(record.PosCouponId);
            // }
            ids.Add(6843);
            List<PosCoupons> coupons = db.PosCoupons.Where(m => ids.Contains(m.Id) && m.IsUse == 1).ToList();
            foreach (PosCoupons coupon in coupons)
            {
                PosSns.Add(coupon.ExchangeCode);
            }
            foreach (PosCoupons coupon in coupons)
            {
                ChildNo(db, coupon.ExchangeCode, coupon.ExchangeCode, coupon.LeaderUserId);
            }
            // db.SaveChanges();
            db.Dispose();
            return "ok";
        }
        List<string> nos = new List<string>();
        private void ChildNo(WebCMSEntities db, string RootCheckNo, string CheckNo, int LeaderUserId)
        {
            MachineApply apply = db.MachineApply.FirstOrDefault(m => m.SwapSnExpand.Contains(CheckNo));
            if(apply != null)
            {
                int len = 0;
                string[] SnList = apply.SwapSnExpand.TrimEnd('\n').Split('\n');
                foreach(string sn in SnList)
                {
                    if(PosSns.Contains(sn.Split(':')[0]) || nos.Contains(sn.Split(':')[0]))
                    {
                        len += 1;
                    }
                }
                Orders order = db.Orders.FirstOrDefault(m => m.Id == apply.QueryCount);
                if(order != null)
                {
                    if(!string.IsNullOrEmpty(order.SnNos))
                    {
                        if(order.SnNos.Contains(","))
                        {
                            string[] SwapSnExpands = order.SnNos.TrimEnd(',').Split(',');
                            int index = 0;
                            foreach(string no in SwapSnExpands)
                            {
                                if(!nos.Contains(no) && index < len)
                                {
                                    index += 1;
                                    nos.Add(no);
                                    ChildNo(db, RootCheckNo, no, LeaderUserId);
                                }
                            }
                        }
                        else
                        {
                            string[] SwapSnExpands = order.SnNos.TrimEnd('\n').Split('\n');
                            int index = 0;
                            foreach(string no in SwapSnExpands)
                            {
                                if(!nos.Contains(no) && index < len)
                                {
                                    index += 1;
                                    nos.Add(no);
                                    ChildNo(db, RootCheckNo, no, LeaderUserId);
                                }
                            }
                        }
                    }
                    else
                    {
                        MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == CheckNo) ?? new MachineForSnNo();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId);
                        if(pos != null)
                        {
                            // pos.LeaderUserId = LeaderUserId;
                            // Utils.WriteLog(LeaderUserId + ":" + pos.PosSn + ":" + apply.SwapSnExpand.TrimEnd('\n').Split('\n').Length, "大盟主奖励标记机具");
                            Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                            Utils.WriteLog(pos.PosSn + ":" + RootCheckNo + ":" + user.MakerCode + ":" + user.RealName, "大盟主奖励标记机具");
                        }
                    }
                }
            }
            else
            {
                MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == CheckNo) ?? new MachineForSnNo();
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m=>m.Id == forSnNo.SnId);
                if(pos != null)
                {
                    // pos.LeaderUserId = LeaderUserId;
                    // Utils.WriteLog(LeaderUserId + ":" + pos.PosSn, "大盟主奖励标记机具");
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                    Utils.WriteLog(pos.PosSn + ":" + RootCheckNo + ":" + user.MakerCode + ":" + user.RealName, "大盟主奖励标记机具");
                }
            }
        }
        List<string> PosSns = new List<string>();
        public string ScanNos()
        {
            PosSns = new List<string>();
            PosSns.Add("00005002681889125851");
            WebCMSEntities db = new WebCMSEntities();
            foreach(string PosSn in PosSns)
            {
                ChildNo(db, PosSn, PosSn, 0);
            }
            db.Dispose();
            return "ok";
        }
        



        public string test()
        {
            WebCMSEntities db = new WebCMSEntities();
            // AlipayPayBack2Service.Instance.DoOrderV2(db, 269424);
            // db.Dispose();
            // List<int> ids = new List<int>();
            // foreach(int id in ids)
            // {
            //     TradeChangeService.Instance.StatTradeAmount(id, 2, 1);
            // }

            // OpModels.WebCMSEntities db = new OpModels.WebCMSEntities();
            // PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == "8610086012" && m.ActivationState == 0 && !string.IsNullOrEmpty(m.SeoKeyword) && m.SeoKeyword != "0" && (m.CreditTrade >= 1000 || m.BrandId == 14));
            // if(pos != null)
            // {
            //     SycnSpTradeService.Instance.ActPos(db, pos, 0, 30);
            // }

            // AlipayPayBack2Service.Instance.OperateAmountChange(db, 392, 40000, 2, 1, "商城购机");
            // AlipayPayBack2Service.Instance.OperateAmountChange(db, 392, 40000, 1, 2, "商城购机");
            // db.Dispose();

            string result = "ok";

            // result += SetDepositPostService.Instance.ModifyFee("00005002681889119293", 0.0063M, "3") + "\n\n";
            // result += SetDepositPostService.Instance.SetFeeForSft("39103661", "0.6300", "3") + "\n\n";

            // Dictionary<string, string> headers = new Dictionary<string, string>();
            // string token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQyN2E2OGY0NzY0MjRiMzJiNjhhM2JlMTc1ZjQ4OGE3In0.xjKmh1Pu9_DvwI-zpML8Z3oqKs99PQW-9aBg-ru2i-xQZYC3yKEtJ_H1_bcw2byGNnMNXMPRlBoDegLpSebXDA";
            // headers.Add("Authorization", "Bearer " + token);
            // string str = "{\"feedback_type\":\"1\",\"content\":\"电饭锅电饭锅大范甘迪\"}";
            // string resultJson = Encrypt(str, "CBTU1dD4Kd5pyiGWTsI10jRQ3SvKusSV", "DYgjCEIMVrj2W9xN");
            // string ApiResponse = function.PostWebRequest("http://47.108.118.29:8080/v1/cybmain/feedback/feedSave", resultJson, headers, "application/json");
            // string ApiResponse = function.GetWebRequest("http://47.108.118.29:8080/v1/cybmain/app/authorization");
            //{"status":1,"messge":null,"data":{"userId":1,"token":"eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQyN2E2OGY0NzY0MjRiMzJiNjhhM2JlMTc1ZjQ4OGE3In0.xjKmh1Pu9_DvwI-zpML8Z3oqKs99PQW-9aBg-ru2i-xQZYC3yKEtJ_H1_bcw2byGNnMNXMPRlBoDegLpSebXDA","loginTime":1699331586502,"expireTime":1699417986502,"ipaddr":null,"loginLocation":null,"browser":null,"os":null,"user":null},"other":null,"code":"1","timestamp":null}

            //补广电卡奖励
            // List<int> ids = new List<int>();
            // DateTime now = DateTime.Now;
            // foreach(int id in ids)
            // {
            //     PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == id);
            //     if(pos != null)
            //     {
            //         if(pos.BrandId == 14 && pos.IsFirst == 1 && pos.BindingTime > now.AddDays(-30))
            //         {
            //             RedisDbconn.Instance.AddList("OpenRewardQueue", id);
            //         }
            //         if (pos.LeaderUserId > 0 && pos.IsFirst == 1 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > now) && pos.BindingTime > now.AddDays(-30))
            //         {
            //             RedisDbconn.Instance.AddList("LeaderPrizeQueue", id);
            //         }
            //         if (pos.IsFirst == 1 && pos.BindingTime > now.AddDays(-30))
            //         {
            //             RedisDbconn.Instance.AddList("OperatePrizeQueue", id);
            //         }
            //     }
            // }

            // DataTable dt = CustomerSqlConn.dtable("select KqMerNo from PosMerchantInfo where Id in (select BindMerchantId from PosMachinesTwo where BrandId in (12,13) and DownFeeFlag=1 and DownFeeDate>'2023-11-10 00:00:00')", MysqlConn.SqlConnStr);
            // foreach(DataRow dr in dt.Rows)
            // {
            //     SetDepositPostService.Instance.BoxFee(dr["KqMerNo"].ToString(), "0.60");
            // }

            // DataTable dt = CustomerSqlConn.dtable("select Id,DownFeeMan from PosMachinesTwo where BrandId in (12,13) and DownFeeFlag=1 and DownFeeDate>='2023-12-01 00:00:00' order by DownFeeDate desc", MysqlConn.ReadSqlConnStr);
            // foreach(DataRow dr in dt.Rows)
            // {
            //     RedisDbconn.Instance.AddList("SetDepositPostQueue", "{\"RecordId\":\"\",\"PosId\":\"" + dr["Id"].ToString() + "\",\"Fee\": \"0.6\",\"Kind\": \"2\",\"OpMan\": \"" + dr["DownFeeMan"].ToString() + "\"}");
            // }

            // DataTable dt = CustomerSqlConn.dtable("select Id from Orders where Status>0 and ProductId in (10,11,77,78,79) and CreateDate>='2023-12-10 00:00:00'", MysqlConn.ReadSqlConnStr);
            // foreach(DataRow dr in dt.Rows)
            // {
            //     RedisDbconn.Instance.AddList("AddPosCouponPrizeQueue", dr["Id"].ToString());
            // }

            // WebCMSEntities db = new WebCMSEntities();
            // var poslist = db.PosMachinesTwo.Select(m => new { m.Id, m.BrandId, m.CardType, m.IsPurchase, m.PosSn }).Where(m => m.BrandId == 14 && m.CardType == 2 && m.IsPurchase == 1).ToList();
            // foreach(var pos in poslist)
            // {
            //     bool check = db.MachineApply.Any(m => m.SwapSnExpand.Contains(pos.PosSn));
            //     if(!check)
            //     {
            //         PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
            //         if(edit != null)
            //         {
            //             edit.IsPurchase = 0;
            //             db.SaveChanges();
            //         }
            //     }
            // }
            // PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == "00003102702303069436067") ?? new PosMachinesTwo();
            // PosMerchantInfo check = db.PosMerchantInfo.FirstOrDefault(m => m.KqSnNo == "00003102702303069436067") ?? new PosMerchantInfo();
            // // int RecordId = PublicFunction.FeeSetRecord(db, pos, check, 0.63M);
            // string info = "{\"RecordId\":\"65931\",\"PosId\":\"" + pos.Id + "\",\"Fee\": \"0.63\",\"Kind\": \"2\",\"OpMan\": \""+"系统"+"\"}";
            // RedisDbconn.Instance.AddList("SetDepositQueue", info);

            // StoreApplyHelper.Instance.DoSomething(db, 49690);

            // db.Dispose();

            return result;
        }

        public string Encrypt(string plainText, string keyString, string ivString)
        {
            byte[] cipherData;
            Aes aes = Aes.Create();
            aes.Key = System.Text.Encoding.UTF8.GetBytes(keyString);
            aes.IV = System.Text.Encoding.UTF8.GetBytes(ivString);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cs))
                    {
                        sw.Write(plainText);
                    }
                }

                cipherData = ms.ToArray();
            }

            return Convert.ToBase64String(cipherData);
        }


        public string setlee()
        {
            WebCMSEntities db = new WebCMSEntities();
            List<string> poslist = new List<string>();
            poslist.Add("00003102722201179816714");
            foreach(string PosSn in poslist)
            {
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn);
                if(pos != null)
                {
                    string info = "{\"RecordId\":\"\",\"PosId\":\"" + pos.Id + "\",\"Fee\": \"0.6\",\"Kind\": \"2\",\"OpMan\": \"系统\"}";
                    RedisDbconn.Instance.AddList("SetDepositPostQueue", info);
                }
            }
            db.Dispose();
            return "ok";
        }

        public string lsprize(int id = 0)
        {
            // StatService.Instance.activePrizeWithoutDeposit6(id);
            // WebCMSEntities db = new WebCMSEntities();
            // List<string> poslist = new List<string>();
            // poslist.Add("N6220Y02004331");
            // poslist.Add("N6220Y02004411");
            // poslist.Add("N6220Y02006392");
            // poslist.Add("N6220Y02008090");
            // poslist.Add("N6220Y02014659");
            // poslist.Add("N6220Y02016352");
            // poslist.Add("N6220Y02018426");
            // poslist.Add("N6220Y02009475");
            // poslist.Add("N6220Y02009601");
            // poslist.Add("N6220Y02009630");
            // poslist.Add("N6220Y02010111");
            // poslist.Add("N6220Y02010795");
            // poslist.Add("N6220Y02011199");
            // poslist.Add("N6220Y02011405");
            // poslist.Add("N6220Y02011946");
            // poslist.Add("N6220Y02172467");
            // poslist.Add("N6220Y02172563");
            // poslist.Add("N6220Y02172658");
            // poslist.Add("N6220Y02172658");
            // poslist.Add("N6220Y02007603");
            // foreach(string PosSn in poslist)
            // {
            //     PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn);
            //     if(pos != null)
            //     {
            //         // SycnSpTradeService.Instance.LiShuaActPrize(db, pos, 50);
            //         StatService.Instance.activePrizeWithoutDeposit6(pos.Id);
            //     }
            // }
            // db.Dispose();
            
            return "ok";
        }

    
    
    
    
        //金控自备机，补商户信息
        public string jkmerinfo(string sn)
        {
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
            var Bind = spdb.BindRecord.FirstOrDefault(m => m.MerSnNo == sn && m.Field1 == "解绑");
            if (Bind != null)
            {
                PxcModels.MachineForSnNo posFor = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == Bind.MerSnNo) ?? new PxcModels.MachineForSnNo();
                PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                if (pos != null)
                {
                    pos.BindingState = 1;
                    pos.BindingTime = Bind.CreateTime;
                    pos.Status = 0;

                    PxcModels.MachineForMerNo merFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
                    if (merFor == null)
                    {
                        merFor = db.MachineForMerNo.Add(new PxcModels.MachineForMerNo()
                        {
                            MerNo = Bind.MerNo,
                            SnId = pos.Id,
                        }).Entity;
                    }
                    else
                    {
                        merFor.SnId = pos.Id;
                    }
                    db.SaveChanges();

                    PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new PxcModels.Users();
                    int TopUserId = 0;
                    if (!string.IsNullOrEmpty(user.ParentNav))
                    {
                        TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    }
                    int BrandId = pos.BrandId;
                    
                    PxcModels.TradeRecord trade = db.TradeRecord.FirstOrDefault(m => m.SnNo == sn) ?? new PxcModels.TradeRecord();
                    PxcModels.PosMerchantInfo add = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == Bind.MerNo);
                    if (add == null)
                    {
                        if(trade.MerchantId > 0)
                        {
                            add = db.PosMerchantInfo.Add(new PxcModels.PosMerchantInfo()
                            {
                                CreateDate = Bind.CreateTime,
                                KqMerNo = Bind.MerNo,
                                MerchantNo = Bind.MerNo.Length > 16 ? Bind.MerNo.Substring(0, 16) : Bind.MerNo,
                                Id = trade.MerchantId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        else
                        {
                            add = db.PosMerchantInfo.Add(new PxcModels.PosMerchantInfo()
                            {
                                CreateDate = Bind.CreateTime,
                                KqMerNo = Bind.MerNo,
                                MerchantNo = Bind.MerNo.Length > 16 ? Bind.MerNo.Substring(0, 16) : Bind.MerNo,
                            }).Entity;
                            db.SaveChanges();
                        }
                    }
                    add.UpdateDate = Bind.UpdateTime;
                    add.TopUserId = TopUserId;
                    add.BrandId = BrandId;
                    add.SnStoreId = pos.StoreId;
                    add.SnType = pos.PosSnType;
                    add.UserId = pos.UserId;
                    add.MerStatus = 1;
                    add.KqSnNo = Bind.MerSnNo;
                    add.MerIdcardNo = function.CheckNull(Bind.SeoKeyword).ToUpper();
                    add.MerRealName = Bind.MerName;
                    add.MerchantMobile = Bind.MerNewSnNo;
                    add.MerchantName = Bind.MerName;
                    pos.BindMerchantId = add.Id;
                    pos.LastMerchantId = add.Id;
                    db.SaveChanges();
                    RedisDbconn.Instance.AddList("DepositReturnStatQueue", add.Id.ToString());
                    PxcModels.Users buser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new PxcModels.Users();
                    if(buser.BusinessFlag == 1)
                    {
                        bool checkMer = db.BusinessPartnerMerchant.Any(m => m.MerchantId == add.Id);
                        if(!checkMer)
                        {
                            PxcModels.BusinessPartnerPos bpos = db.BusinessPartnerPos.FirstOrDefault(m => m.PosId == pos.Id) ?? new PxcModels.BusinessPartnerPos();
                            db.BusinessPartnerMerchant.Add(new PxcModels.BusinessPartnerMerchant()
                            {
                                CreateDate = DateTime.Now,
                                MerNo = Bind.MerNo,
                                MerchantId = add.Id,
                                PartnerId = bpos.PartnerId,
                                UserId = pos.BuyUserId,
                            });
                            db.SaveChanges();
                        }
                    }
                }
            }
            spdb.Dispose();
            db.Dispose();
            return "ok";
        }

        public string sycnTrade(int Id)
        {
            PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
            PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == Id);
            if(merchant != null)
            {
                DepositReturnStatService.Instance.DoSomething(db, merchant);
            }
            return "ok";
        }
    
    
    }
}