using System;
using System.Threading;
using System.Linq;
using System.Data;
using Library;
using MySystem.Models;
using System.Collections.Generic;
using LitJson;
using Newtonsoft.Json;

/// <summary>
/// 广电卡交易数据导入
/// </summary>
namespace MySystem
{
    public class SIMPosMerchantTradeService
    {
        public readonly static SIMPosMerchantTradeService Instance = new SIMPosMerchantTradeService();
        private SIMPosMerchantTradeService()
        {
        }

        public void Start()//启动
        {
            Thread thread = new Thread(ImportPostDo); // 广电卡导激活和交易
            thread.IsBackground = true;
            thread.Start();

            Thread thread1 = new Thread(SIMActDo); // 通过接口获取广电卡激活数据
            thread1.IsBackground = true;
            thread1.Start();
        }

        public void ImportPostDo()
        {
            while (true)
            {
                try
                {
                    string data = RedisDbconn.Instance.RPop<string>("SIMPosMerchantTradeQueue");
                    if (!string.IsNullOrEmpty(data))
                    {
                        string[] dataList = data.Split("#cut#");
                        string _ExcelPath = dataList[0];
                        string _Kind = dataList[1];
                        string checkKey = dataList[2];
                        string Operator = dataList[3]; // 操作人
                        int SuccessCount = 0;
                        int DoCount = 0;
                        string FullExcelPath = function.getPath(_ExcelPath);
                        FullExcelPath = FullExcelPath.Replace("//", "/");
                        DataTable list = new PublicFunction().ExcelToDataTable(FullExcelPath);
                        int TotalCount = list.Rows.Count;
                        while (DoCount < list.Rows.Count)
                        {
                            WebCMSEntities db = new WebCMSEntities();
                            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
                            //导激活
                            if (_Kind == "1")
                            {
                                var tran = db.Database.BeginTransaction();
                                try
                                {
                                    int Size = 100;
                                    if (list.Rows.Count - DoCount < 100)
                                    {
                                        Size = list.Rows.Count - DoCount;
                                    }
                                    Dictionary<string, int> storeData = new Dictionary<string, int>();
                                    for (int i = DoCount; i < DoCount + Size; i++)
                                    {
                                        DataRow dr = list.Rows[i];
                                        SIMActInfo sIMActInfo = new SIMActInfo
                                        {
                                            OrderNo = dr["订单编码"].ToString(),
                                            CreateDate = dr["订单创建时间"].ToString(),
                                            PhoneNumber = dr["选择号码"].ToString(),
                                            HasFirstCharge = dr["是否有首充"].ToString(),
                                            FirstChargeAmount = dr["首充金额（元）"].ToString(),
                                            Province = dr["号码归属省份"].ToString(),
                                            City = dr["号码归属地市"].ToString(),
                                            ProductName = dr["商品名称"].ToString(),
                                            ActiveName = dr["促销活动名称"].ToString(),
                                            ProductType = dr["商品类型名称"].ToString(),
                                            ActualAmount = dr["实付金额(元)"].ToString(),
                                            OrderStatus = dr["订单状态"].ToString(),
                                            ActStatus = dr["激活状态名称"].ToString(),
                                            ActDate = dr["激活时间"].ToString(),
                                            WorkNo = dr["BOSS员工工号"].ToString(),
                                            AccountName = dr["账号姓名"].ToString(),
                                            SimNo = dr["SIM卡号"].ToString()
                                        };

                                        AddSIMActInfo(sIMActInfo);

                                        SuccessCount += 1;
                                    }
                                    DoCount += Size;
                                    spdb.SaveChanges();
                                    tran.Commit();
                                    if (DoCount >= list.Rows.Count)
                                    {
                                        RedisDbconn.Instance.Set("SIMPosMerchantTradeCheckImport:" + checkKey, "success|" + SuccessCount);
                                        RedisDbconn.Instance.SetExpire("SIMPosMerchantTradeCheckImport:" + checkKey, 60000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DoCount = list.Rows.Count;
                                    function.WriteLog(ex.ToString(), "导入广电卡激活数据");
                                    tran.Rollback();
                                    ErrorMsg msg = new ErrorMsg()
                                    {
                                        Time = DateTime.Now,
                                        ErrorContent = ex.ToString(),
                                    };
                                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "导入广电卡激活数据Excel文件异常");
                                }
                                tran.Dispose();
                            }
                            //导交易
                            if (_Kind == "2")
                            {
                                var tran = db.Database.BeginTransaction();
                                try
                                {
                                    int Size = 100;
                                    if (list.Rows.Count - DoCount < 100)
                                    {
                                        Size = list.Rows.Count - DoCount;
                                    }
                                    Dictionary<string, int> storeData = new Dictionary<string, int>();
                                    for (int i = DoCount; i < DoCount + Size; i++)
                                    {
                                        DataRow dr = list.Rows[i];
                                        SIMTradeInfo sIMTradeInfo = new SIMTradeInfo
                                        {
                                            Mobile = dr["用户手机号"].ToString(),
                                            SimNo = dr["SIM卡号"].ToString(),
                                            CreateMonth = dr["入网月份"].ToString(),
                                            SettleMonth = dr["结算月份"].ToString(),
                                            SettleTime = dr["结算账期"].ToString(),
                                            SettleSpace = dr["结算场景"].ToString(),
                                            BusinessType = dr["业务类型"].ToString(),
                                            Province = dr["用户省份"].ToString(),
                                            City = dr["用户地市"].ToString(),
                                            Team = dr["团队归属"].ToString(),
                                            WorkName = dr["行销宝姓名"].ToString(),
                                            WorkNo = dr["行销宝工号"].ToString(),
                                            ProductName = dr["商品名称"].ToString(),
                                            TotalAmount = dr["账单总金额"].ToString(),
                                            InAmount = dr["套内金额"].ToString(),
                                            OutAmount = dr["套外金额"].ToString(),
                                            UserStatus = dr["用户状态"].ToString(),
                                            ChannelCode = dr["渠道编码"].ToString(),
                                            ChannelName = dr["渠道名称"].ToString(),
                                            OrderCreateTime = dr["订单创建时间"].ToString(),
                                            OrderStatus = dr["订单状态"].ToString(),
                                            ActTime = dr["激活时间"].ToString(),
                                            SourceProductName = dr["原订单商品名称"].ToString(),
                                            ProductType = dr["商品类型名称"].ToString(),
                                            ActivityName = dr["促销活动名称"].ToString(),
                                            Percent = dr["分成比例"].ToString(),
                                            OrgDivi = dr["机构分成"].ToString()
                                        };

                                        AddSIMTradeInfo(sIMTradeInfo);
                                        SuccessCount += 1;
                                    }
                                    DoCount += Size;
                                    db.SaveChanges();
                                    tran.Commit();
                                    if (DoCount >= list.Rows.Count)
                                    {
                                        RedisDbconn.Instance.Set("SIMPosMerchantTradeCheckImport:" + checkKey, "success|" + SuccessCount);
                                        RedisDbconn.Instance.SetExpire("SIMPosMerchantTradeCheckImport:" + checkKey, 60000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DoCount = list.Rows.Count;
                                    function.WriteLog(ex.ToString(), "导入广电卡交易数据");
                                    tran.Rollback();
                                    ErrorMsg msg = new ErrorMsg()
                                    {
                                        Time = DateTime.Now,
                                        ErrorContent = ex.ToString(),
                                    };
                                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "导入广电卡交易数据Excel文件异常");
                                }
                                tran.Dispose();
                            }

                        }
                    }
                    else
                    {
                        Thread.Sleep(5000);
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "后台导入Excel文件队列异常");
                }
            }
        }


        /// <summary>
        /// 通过接口获取广电卡激活数据
        /// </summary>
        public void SIMActDo()
        {
            while (true)
            {
                string Info = RedisDbconn.Instance.RPop<string>("SIMActInfo");
                if (!string.IsNullOrEmpty(Info))
                {
                    try
                    {
                        var time = function.ReadInstance("/GetSIMActInfo/LastDate.txt");
                        if(string.IsNullOrEmpty(time))
                        {
                            time = "2024-03-18";
                        }
                        string check = function.ReadInstance("/GetSIMActInfo/check" + time + ".txt");
                        if (string.IsNullOrEmpty(check))
                        {
                            function.WritePage("/GetSIMActInfo/", "check" + time + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                            var result = RadioCardHelper.Instance.QueryCardOrderInfo(time, time, "1", "99999");
                            result = result.Replace("null", "\"\"");
                            JsonData jsonObj = JsonMapper.ToObject(result);
                            if (jsonObj["resultCode"].ToString() == "1")
                            {
                                SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
                                var data = jsonObj["data"]["records"];
                                for (int i = 0; i < data.Count; i++)
                                {
                                    var iccId = data[i]["iccId"].ToString();
                                    var bindRecord = spdb.BindRecord.FirstOrDefault(m => m.MerSnNo == iccId) ?? new SpModels.BindRecord();
                                    var merchants = spdb.Merchants.FirstOrDefault(m => m.SnNo == iccId) ?? new SpModels.Merchants();
                                    if (bindRecord.Id == 0 && merchants.Id == 0)
                                    {
                                        // {"orderNo":"B20240319215437195664","orderCreateTime":"03/19/2024 21:54:37","phoneNo":"19238664877","firstCharge":"否","initialChargeAmount":"0.00","province":"贵州省","city":"遵义市","productName":"双百套餐","promotionName":null,"productTypeName":"基础套餐","paidInAmount":"100.00","orderStatus":"已完成","activationStatusName":"已激活","activationTime":"03/19/2024 21:58:23","jobId":"VCH010131087","iccId":"89861500232320195477"}

                                        SIMActInfo sIMActInfo = new SIMActInfo
                                        {
                                            OrderNo = data[i]["orderNo"].ToString(), //订单编码
                                            CreateDate = data[i]["orderCreateTime"].ToString(), //订单创建时间
                                            PhoneNumber = data[i]["phoneNo"].ToString(), //选择号码
                                            HasFirstCharge = data[i]["firstCharge"].ToString(), //是否有首充
                                            FirstChargeAmount = data[i]["initialChargeAmount"].ToString(), //首充金额（元）
                                            Province = data[i]["province"].ToString(), //号码归属省份
                                            City = data[i]["city"].ToString(), //号码归属地市
                                            ProductName = data[i]["productName"].ToString(), //商品名称
                                            ActiveName = data[i]["promotionName"].ToString(), //促销活动名称
                                            ProductType = data[i]["productTypeName"].ToString(), //商品类型名称
                                            ActualAmount = data[i]["paidInAmount"].ToString(), //实付金额(元)
                                            OrderStatus = data[i]["orderStatus"].ToString(), //订单状态
                                            ActStatus = data[i]["activationStatusName"].ToString(), //激活状态名称
                                            ActDate = data[i]["activationTime"].ToString(), //激活时间
                                            WorkNo = data[i]["jobId"].ToString(), //BOSS员工工号
                                            // sIMActInfo.AccountName = data[""].ToString(); //账号姓名
                                            AccountName = "", //账号姓名
                                            SimNo = iccId //SIM卡号
                                        };

                                        AddSIMActInfo(sIMActInfo);
                                    }
                                }
                            }
                        }
                        function.WritePage("/GetSIMActInfo/", "LastDate.txt", DateTime.Now.ToString("yyyy-MM-dd"));
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "获取广电卡激活信息队列异常");
                    }
                }
                Thread.Sleep(6000);
            }
        }

        /// <summary>
        /// 添加广电卡激活数据
        /// </summary>
        /// <param name="sIMActInfo"></param>
        public void AddSIMActInfo(SIMActInfo sIMActInfo)
        {
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();

            string json = "{";
            json += "\"OrderNo\":\"" + sIMActInfo.OrderNo + "\",";
            json += "\"CreateDate\":\"" + sIMActInfo.CreateDate + "\",";
            json += "\"PhoneNumber\":\"" + sIMActInfo.PhoneNumber + "\",";
            json += "\"HasFirstCharge\":\"" + sIMActInfo.HasFirstCharge + "\",";
            json += "\"FirstChargeAmount\":\"" + sIMActInfo.FirstChargeAmount + "\",";
            json += "\"Province\":\"" + sIMActInfo.Province + "\",";
            json += "\"City\":\"" + sIMActInfo.City + "\",";
            json += "\"ProductName\":\"" + sIMActInfo.ProductName + "\",";
            json += "\"ActiveName\":\"" + sIMActInfo.ActiveName + "\",";
            json += "\"ProductType\":\"" + sIMActInfo.ProductType + "\",";
            json += "\"ActualAmount\":\"" + sIMActInfo.ActualAmount + "\",";
            json += "\"OrderStatus\":\"" + sIMActInfo.OrderStatus + "\",";
            json += "\"ActStatus\":\"" + sIMActInfo.ActStatus + "\",";
            json += "\"ActDate\":\"" + sIMActInfo.ActDate + "\",";
            json += "\"WorkNo\":\"" + sIMActInfo.WorkNo + "\",";
            json += "\"AccountName\":\"" + sIMActInfo.AccountName + "\",";
            json += "\"SimNo\":\"" + sIMActInfo.SimNo + "\"";
            json += "}";

            spdb.BindRecord.Add(new SpModels.BindRecord()
            {
                CreateDate = DateTime.Parse(sIMActInfo.CreateDate),
                UpdateTime = DateTime.Parse(sIMActInfo.CreateDate), //机具绑定、解绑时间
                CreateTime = DateTime.Parse(sIMActInfo.CreateDate), //商户操作时间
                MerNewSnNo = sIMActInfo.PhoneNumber, //商户手机号
                MerSnNo = sIMActInfo.SimNo, //序列号
                MerName = sIMActInfo.AccountName, //商户名称
                MerNo = sIMActInfo.PhoneNumber, //商户编号
                Remark = sIMActInfo.ProductType,
                Field1 = sIMActInfo.Province,
                Field2 = sIMActInfo.ActiveName,
                Field3 = sIMActInfo.ProductName,
                Field4 = sIMActInfo.WorkNo,
                Field5 = sIMActInfo.ActStatus,
                SeoTitle = sIMActInfo.ActualAmount,
                SeoKeyword = sIMActInfo.ActDate,
                SeoDescription = json,
                ProductType = "14",
                Status = 1,
            });

            spdb.Merchants.Add(new SpModels.Merchants()
            {
                SnNo = sIMActInfo.SimNo,
                CreateTime = DateTime.Parse(sIMActInfo.CreateDate),
                UpdateTime = DateTime.Parse(sIMActInfo.CreateDate),
                AgentName = sIMActInfo.AccountName,
                MerRealName = sIMActInfo.AccountName,
                MerMobile = sIMActInfo.PhoneNumber,
                MerNo = sIMActInfo.PhoneNumber,
                MerName = sIMActInfo.AccountName,
                ProductType = "14",
                Status = 1,
            });

            spdb.SaveChanges();
        }


        /// <summary>
        /// 添加广电卡激活数据
        /// </summary>
        /// <param name="sIMActInfo"></param>
        public void AddSIMTradeInfo(SIMTradeInfo sIMTradeInfo)
        {
            WebCMSEntities db = new WebCMSEntities();
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();

            string json = "{";
            json += "\"Mobile\":\"" + sIMTradeInfo.Mobile + "\",";
            json += "\"SimNo\":\"" + sIMTradeInfo.SimNo + "\",";
            json += "\"CreateMonth\":\"" + sIMTradeInfo.CreateMonth + "\",";
            json += "\"SettleMonth\":\"" + sIMTradeInfo.SettleMonth + "\",";
            json += "\"SettleTime\":\"" + sIMTradeInfo.SettleTime + "\",";
            json += "\"SettleSpace\":\"" + sIMTradeInfo.SettleSpace + "\",";
            json += "\"BusinessType\":\"" + sIMTradeInfo.BusinessType + "\",";
            json += "\"Province\":\"" + sIMTradeInfo.Province + "\",";
            json += "\"City\":\"" + sIMTradeInfo.City + "\",";
            json += "\"Team\":\"" + sIMTradeInfo.Team + "\",";
            json += "\"WorkName\":\"" + sIMTradeInfo.WorkName + "\",";
            json += "\"WorkNo\":\"" + sIMTradeInfo.WorkNo + "\",";
            json += "\"ProductName\":\"" + sIMTradeInfo.ProductName + "\",";
            json += "\"TotalAmount\":\"" + sIMTradeInfo.TotalAmount + "\",";
            json += "\"InAmount\":\"" + sIMTradeInfo.InAmount + "\",";
            json += "\"OutAmount\":\"" + sIMTradeInfo.OutAmount + "\",";
            json += "\"UserStatus\":\"" + sIMTradeInfo.UserStatus + "\",";
            json += "\"ChannelCode\":\"" + sIMTradeInfo.ChannelCode + "\",";
            json += "\"ChannelName\":\"" + sIMTradeInfo.ChannelName + "\",";
            json += "\"OrderCreateTime\":\"" + sIMTradeInfo.OrderCreateTime + "\",";
            json += "\"OrderStatus\":\"" + sIMTradeInfo.OrderStatus + "\",";
            json += "\"ActTime\":\"" + sIMTradeInfo.ActTime + "\",";
            json += "\"SourceProductName\":\"" + sIMTradeInfo.SourceProductName + "\",";
            json += "\"ProductType\":\"" + sIMTradeInfo.ProductType + "\",";
            json += "\"ActivityName\":\"" + sIMTradeInfo.ActivityName + "\",";
            json += "\"Percent\":\"" + sIMTradeInfo.Percent + "\",";
            json += "\"OrgDivi\":\"" + sIMTradeInfo.OrgDivi + "\"";
            json += "}";

            bool op = true;
            string OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            decimal TotalAmountNum = decimal.Parse(function.CheckNum(numberString: sIMTradeInfo.TotalAmount));
            DateTime CreateDate = DateTime.Parse(sIMTradeInfo.OrderCreateTime);
            string CheckDate = DateTime.Now.AddMonths(-3).ToString("yyyyMM");
            if (int.Parse(sIMTradeInfo.CreateMonth) >= int.Parse(CheckDate)) op = false;
            if (sIMTradeInfo.OrderStatus == "待激活") op = false;
            if (sIMTradeInfo.UserStatus.Contains("注销") || sIMTradeInfo.UserStatus.Contains("欠费"))
            {
                op = false;
                SimposMerchantInfo checkSimMer = db.SimposMerchantInfo.FirstOrDefault(m => m.KqMerNo == sIMTradeInfo.Mobile && m.KqSnNo == sIMTradeInfo.SimNo);
                if (checkSimMer != null)
                {
                    checkSimMer.Status = -1;
                    if (sIMTradeInfo.UserStatus.Contains("欠费") && checkSimMer.Status != -1)
                    {
                        checkSimMer.Status = -2;
                    }
                    db.SaveChanges();
                }
                PosMerchantInfo checkMer = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == sIMTradeInfo.Mobile && m.KqSnNo == sIMTradeInfo.SimNo);
                if (checkMer != null)
                {
                    checkMer.Status = -1;
                    if (sIMTradeInfo.UserStatus.Contains("欠费") && checkMer.Status != -1)
                    {
                        checkMer.Status = -2;
                    }
                    db.SaveChanges();
                }
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == sIMTradeInfo.SimNo);
                if (pos != null)
                {
                    pos.Status = -1;
                    if (sIMTradeInfo.UserStatus.Contains("欠费") && pos.Status != -1)
                    {
                        pos.Status = -2;
                    }
                    db.SaveChanges();
                }
            }
            if (sIMTradeInfo.UserStatus.Contains("正常"))
            {
                SimposMerchantInfo checkSimMer = db.SimposMerchantInfo.FirstOrDefault(m => m.KqMerNo == sIMTradeInfo.Mobile && m.KqSnNo == sIMTradeInfo.SimNo);
                if (checkSimMer != null)
                {
                    if (checkSimMer.Status == -2) checkSimMer.Status = 0;
                    db.SaveChanges();
                }
                PosMerchantInfo checkMer = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == sIMTradeInfo.Mobile && m.KqSnNo == sIMTradeInfo.SimNo);
                if (checkMer != null)
                {
                    if (checkMer.Status == -2) checkMer.Status = 1;
                    db.SaveChanges();
                }

                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == sIMTradeInfo.SimNo);
                if (pos != null && pos.Status < 0)
                {
                    if (pos.Status == -2)
                    {
                        pos.Status = 0;
                    }
                    db.SaveChanges();
                }
            }

            if (TotalAmountNum > 0 && op)
            {
                spdb.TradeRecord.Add(new SpModels.TradeRecord()
                {
                    CreateDate = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM-20 HH:mm:ss")), //创建时间
                    TradeSerialNo = OrderNo, //订单编号
                    AgentNo = sIMTradeInfo.WorkName + sIMTradeInfo.WorkNo, //一级服务商编号
                    MerNo = sIMTradeInfo.Mobile, //商户编
                    TradeSnNo = sIMTradeInfo.SimNo, //sim卡号
                    ChannelSerial = OrderNo, //请求号
                    TradeAmount = TotalAmountNum, //账单总金额
                    TradeStatus = sIMTradeInfo.OrderStatus, //订单状态
                    TradeDate = sIMTradeInfo.CreateMonth,
                    TradeTime = CreateDate.ToString("yyyyMMdd"),
                    BankCardType = "01",
                    TradeType = "01",
                    ProductType = "14",
                    Status = 1,
                    Field1 = sIMTradeInfo.ProductName,
                    Field2 = sIMTradeInfo.SourceProductName,
                    Field3 = sIMTradeInfo.ProductType,
                    Field4 = sIMTradeInfo.BusinessType,
                    SeoDescription = json,
                });

                spdb.SaveChanges();
            }
        }

    }
}