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()
        {
            // for (int i = 2; i <= 6; i++)
            // {
            //     PosPushDataNewHelper.Trade(new MySystem.SpModels.TradeRecord()
            //     {
            //         TradeSnNo = "1453432669",
            //         MerNo = "1453432669",
            //         TradeAmount = 9.9M,
            //         TradeSerialNo = Guid.NewGuid().ToString(),
            //         CreateDate = DateTime.Parse("2025-0" + i + "-01 01:00:00"),
            //         ProductType = "23",
            //     });
            // }
            // PosPushDataNewHelper.Trade(new MySystem.SpModels.TradeRecord()
            // {
            //     ErrorCode = "0.6",
            //     ErrorMsg = "",
            //     TradeAmount = 1002.00M,
            //     ProductType = "12",
            //     TradeSnNo = "00005702880118402720",
            //     TradeType = "0",
            //     BankCardType = "C",
            //     Field2 = "",
            //     Field3 = "0",
            //     MerNo = "039350508527759",
            //     TradeSerialNo = "20250102H00041573514Y",
            //     CreateDate = DateTime.Parse("2025-01-02 12:25:58"),
            //     ChannelSerial = "",
            // });
            // PosPushDataNewHelper.Deposit(new MySystem.SpModels.ActivateRecord()
            // {
            //     SeoTitle = "0.00",
            //     ProductType = "23",
            //     SnNo = "217F8106532",
            //     MerNo = "217F8106532",
            //     Id = 780709,
            // });
            // PosPushDataNewHelper.Bind(new MySystem.SpModels.Merchants()
            // {
            //     ProductType = "200",
            //     SnNo = "QR939300200002",
            //     MerNo = "L00000000000400",
            //     MerIdcardNo = "522121********6811",
            //     MerName = "金银新村社区服务站",
            //     MerMobile = "139****2383",
            //     CreateTime = DateTime.Parse("2025-06-27 10:36:00"),
            // }, "33");
            // string FeeRate = "0.63";
            // string FeeAmt = "0";
            // Dictionary<string, string> fee = PosPushDataNewHelper.GetFee("00000602H3R000100392323", FeeRate, FeeAmt, "1");
            // fee = PosPushDataNewHelper.GetFee2("00000602H3R000100392323", FeeRate, FeeAmt, "1");
            // FeeRate = fee["FeeRate"];
            // FeeAmt = fee["FeeAmt"];


            // Dictionary<string, int> userids = new Dictionary<string, int>();
            // string userString = function.ReadInstance("tmpdata/2.txt");
            // string[] user = userString.Split('\n');
            // foreach (string item in user)
            // {
            //     string[] userInfo = item.Split('|');
            //     userids.Add(userInfo[0], int.Parse(userInfo[1]));
            // }
            string content = function.ReadInstance("tmpdata/1.txt");
            string[] list = content.Split('\n');
            foreach(string line in list)
            {
                string[] lineData = line.Split('|');
                string SnNo = lineData[0];
                string PrizeKind = "995";
                // decimal PrizeAmt = decimal.Parse(function.CheckNum(lineData[2]));
                int BrandId = int.Parse(function.CheckInt(lineData[2]));
                int UserId = int.Parse(function.CheckInt(lineData[1]));
                Dictionary<string, object> prizeData = new Dictionary<string, object>();
                prizeData.Add("brand_id", BrandId);
                prizeData.Add("ext_field", PrizeKind);
                prizeData.Add("pos_sn", SnNo);
                prizeData.Add("user_id", UserId);
                // prizeData.Add("prize", PrizeAmt);
                string req = Newtonsoft.Json.JsonConvert.SerializeObject(prizeData);
                // string ids = PrizeKind == "833_02" ? "82" : "81";
                // function.GetWebRequest("http://logic-executor-api.kexiaoshuang.com/noauth/prize/pushbyone?n=QUEUE_KXS_HAODA_PRIZE_CONFIG_DIVISION&m=" + req + "&ids=" + ids + ",83");
                function.GetWebRequest("http://logic-executor-api.kexiaoshuang.com/noauth/prize/pushbyone?n=QUEUE_KXS_HAODA_PRIZE_CONFIG_DIVISION&m=" + req + "&ids=83");
            }

            return "ok";
        }

        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 add()
        {
            DateTime now = DateTime.Now;
            WebCMSEntities db = new WebCMSEntities();
            List<string> poslist = new List<string>();
            foreach(string PosSn in poslist)
            {
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn);
                if(pos != null)
                {
                    PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                    if (merchant != null)
                    {
                        DateTime TransferTime = pos.TransferTime == null ? DateTime.Now : pos.TransferTime.Value;

                        //广电卡批量补盟主奖励和运营中心奖励
                        if (pos.BrandId == 14 && pos.BuyUserId > 0 && pos.ActivationState == 1 && TransferTime < pos.BindingTime && pos.BindingTime > now.AddDays(-30) && pos.CardType > 0 && pos.CardType < 100)
                        {
                            if(pos.LeaderUserId > 0 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > now))
                            {
                                RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                            }
                            RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
                        }

                        //0押金返30的奖励批量补录
                        // if(pos.ActivationState == 1 && (string.IsNullOrEmpty(pos.SeoKeyword) || pos.SeoKeyword == "0") && pos.CreditTrade >= 5000 && pos.CardType < 100)
                        // {
                        //     Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                        //     if (user != null)
                        //     {
                        //         int GetUserId = user.Id;
                        //         string ParentNav = user.ParentNav;
                        //         int TopUserId = 0;
                        //         if (!string.IsNullOrEmpty(ParentNav))
                        //         {
                        //             TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        //         }
                        //         if(pos.BindingTime.Value.AddDays(30) >= pos.ActivationTime)
                        //         {
                        //             StatService.Instance.doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 30);
                        //             if(pos.LeaderUserId > 0 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > now))
                        //             {
                        //                 RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                        //             }
                        //             RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
                        //         }
                        //     }
                        // }
                    }

                    //批量补服务费奖励
                    // if(decimal.Parse(function.CheckNum(pos.SeoKeyword)) > 0 && pos.CardType < 100)
                    // {
                    //     StatService.Instance.PreActPrize(db, pos, merchant, pos.SeoKeyword);
                    // }
                }
            }
            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";
        }
    


        public string addprize()
        {
            List<int> ids = new List<int>();
            foreach(int id in ids)
            {
                RedisDbconn.Instance.AddList("LeaderPrizeQueue", id);
            }
            return "ok";
        }

        public string addprize2()
        {
            List<int> ids = new List<int>();
            foreach(int id in ids)
            {
                RedisDbconn.Instance.AddList("OperatePrizeQueue", id);
            }
            return "ok";
        }
    
    
        public string addprize3()
        {
            List<int> ids = new List<int>();
            foreach(int id in ids)
            {
                LeaderApplyCouponsHelper.Instance.addprize(id);
            }
            return "ok";
        }


        public string addprize4(int id)
        {
            RedisDbconn.Instance.AddList("PosCouponPrizeQueue2", id.ToString());
            return "ok";
        }    
    

        public string pushwifi()
        {
            List<string> snnos = new List<string>();
            List<string> snnos2 = new List<string>();
            WebCMSEntities db = new WebCMSEntities();
            List<WifiTradeRecord> list = db.WifiTradeRecord.Where(m => snnos.Contains(m.SnNo) && !snnos2.Contains(m.SnNo)).ToList();
            foreach(WifiTradeRecord sub in list)
            {
                decimal TradeAmt = sub.TradeAmount / sub.Duration;
                TradeAmt = PublicFunction.NumberFormat(TradeAmt);
                //推送wifi交易给java
                PosPushDataNewHelper.Trade(new MySystem.SpModels.TradeRecord()
                {
                    TradeSnNo = sub.SnNo,
                    MerNo = sub.SnNo,
                    TradeAmount = TradeAmt,
                    TradeSerialNo = Guid.NewGuid().ToString(),
                    CreateDate = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01 01:00:00"),
                    ProductType = sub.BrandId.ToString(),
                });
            }
            db.Dispose();
            return "ok";
        }
    }
}