using System;
using System.Collections.Generic;
using System.Linq;
using Library;
using MySystem.SpModels;

namespace MySystem
{
    public class PosPushDataNewHelper
    {
        public readonly static PosPushDataNewHelper Instance = new PosPushDataNewHelper();
        private PosPushDataNewHelper()
        { }

        //绑定数据
        public static void Bind(Merchants mer, string rnd = "")
        {
            try
            {
                if(mer.ProductType == "22")
                {
                    mer.ProductType = GetLiShuaBrand(mer.SnNo);
                }
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", mer.SnNo); //机具sn
                dataContent.Add("mer_no", mer.MerNo); //商户号
                dataContent.Add("id_card", mer.MerIdcardNo); //商户身份证
                dataContent.Add("mer_name", mer.MerName); //商户姓名
                dataContent.Add("mer_mobile", mer.MerMobile); //商户手机号
                dataContent.Add("request_id", getRequestId(mer.SnNo + mer.MerNo + rnd, "bind")); //流水号
                dataContent.Add("bind_time", mer.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //绑定时间
                dataContent.Add("brand", int.Parse(function.CheckInt(mer.ProductType))); //品牌
                if(mer.ProductType == "29")
                {
                    dataContent.Add("user_id", mer.QueryCount); //创客ID
                }
                Push("bind", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送绑定数据异常");
            }
        }
        public static void Bind0(BindRecord mer)
        {
            try
            {
                if(mer.ProductType == "22")
                {
                    mer.ProductType = GetLiShuaBrand(mer.MerSnNo);
                }
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", mer.MerSnNo); //机具sn
                dataContent.Add("mer_no", mer.MerNo); //商户号
                dataContent.Add("id_card", ""); //商户身份证
                dataContent.Add("mer_name", mer.MerName); //商户姓名
                dataContent.Add("mer_mobile", mer.MerNo); //商户手机号
                dataContent.Add("request_id", getRequestId(mer.Id, "bind")); //流水号
                dataContent.Add("bind_time", mer.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //绑定时间
                dataContent.Add("brand", int.Parse(function.CheckInt(mer.ProductType))); //品牌
                Push("bind", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送绑定数据异常");
            }
        }
        public static void Bind2(MerchantRecord mer)
        {
            try
            {
                if(mer.ProductType == "22")
                {
                    mer.ProductType = GetLiShuaBrand(mer.MerSnNo);
                }
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", mer.MerSnNo); //机具sn
                dataContent.Add("mer_no", mer.MerNo); //商户号
                dataContent.Add("id_card", mer.LegalIdCard); //商户身份证
                dataContent.Add("mer_name", mer.MerName); //商户姓名
                dataContent.Add("mer_mobile", ""); //商户手机号
                dataContent.Add("request_id", getRequestId(mer.Id, "merchant")); //流水号
                dataContent.Add("bind_time", mer.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //绑定时间
                dataContent.Add("brand", int.Parse(function.CheckInt(mer.ProductType))); //品牌
                Push("bind", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送绑定数据异常");
            }
        }

        //解绑数据
        public static void UnBind(UnBindRecord mer)
        {
            try
            {
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", mer.MerSnNo); //机具sn
                dataContent.Add("mer_no", mer.MerNo); //商户号
                dataContent.Add("request_id", getRequestId(mer.Id, "unbind")); //流水号
                dataContent.Add("un_bind_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //绑定时间
                dataContent.Add("brand", int.Parse(function.CheckInt(mer.ProductType))); //品牌
                Push("un_bind", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送解绑数据异常");
            }
        }

        //换绑数据
        public static void ChangeBind(ChangeBindRecord mer)
        {
            try
            {
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("request_id", getRequestId(mer.Id, "changebind")); //流水号
                dataContent.Add("mer_no", mer.MerNo); //商户号
                dataContent.Add("source_pos_sn", mer.MerSnNo); //来源机具sn
                dataContent.Add("source_brand", int.Parse(function.CheckInt(mer.ProductType))); //来源品牌
                dataContent.Add("to_pos_sn", mer.MerNewSnNo); //兑换机具sn
                dataContent.Add("to_brand", int.Parse(function.CheckInt(mer.ProductType))); //兑换品牌
                dataContent.Add("change_bind_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //换绑时间
                Push("change_bind", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送换绑数据异常");
            }
        }

        //押金数据
        public static void Deposit(ActivateRecord act)
        {
            try
            {
                List<string> BrandIds = new List<string>();
                decimal TradeAmount = decimal.Parse(function.CheckNum(act.SeoTitle));
                BrandIds.Add("1");
                BrandIds.Add("4");
                BrandIds.Add("6");
                BrandIds.Add("8");
                BrandIds.Add("9");
                BrandIds.Add("15");
                BrandIds.Add("22");
                BrandIds.Add("27");
                BrandIds.Add("30");
                BrandIds.Add("33");
                if(BrandIds.Contains(act.ProductType))
                {
                    TradeAmount = TradeAmount / 100;
                }
                if(act.ProductType == "22")
                {
                    act.ProductType = GetLiShuaBrand(act.SnNo);
                }
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", act.SnNo); //机具sn
                dataContent.Add("mer_no", act.MerNo); //商户号
                if(Utils.Instance.IsWifi(int.Parse(act.ProductType)) || Utils.Instance.IsHaoDa(int.Parse(act.ProductType)))
                {
                    dataContent.Add("request_id", getRequestId(act.SnNo + act.MerMobile, "deposit")); //流水号
                }
                else
                {
                    dataContent.Add("request_id", getRequestId(act.Id, "deposit")); //流水号
                }
                if(act.ProductType == "14")
                {
                    dataContent.Add("deposit_amount", 0); //押金金额
                }
                else
                {
                    dataContent.Add("deposit_amount", TradeAmount); //押金金额
                }
                dataContent.Add("trade_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //交易时间
                dataContent.Add("card_type", 1); //卡类型
                dataContent.Add("brand", int.Parse(function.CheckInt(act.ProductType))); //品牌
                if(act.ProductType == "29")
                {
                    dataContent.Add("ext_field", act.Field4); //押金活动编码
                }
                else if(act.ProductType == "36")
                {
                    dataContent.Add("ext_field", act.Field3); //奖励金额
                }
                else if(act.ProductType == "14" && (function.CheckNull(act.SeoKeyword).Contains("双百套餐") || act.SnNo.StartsWith("CS")))
                {
                    dataContent.Add("fee_amt", TradeAmount); //秒到费
                }
                Push("deposit", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送押金数据异常");
            }
        }
        public static void Deposit(TradeRecord trade)
        {
            try
            {
                List<string> BrandIds = new List<string>();
                decimal TradeAmount = trade.TradeAmount;
                BrandIds.Add("1");
                BrandIds.Add("4");
                BrandIds.Add("6");
                // BrandIds.Add("7");
                BrandIds.Add("8");
                BrandIds.Add("9");
                BrandIds.Add("15");
                BrandIds.Add("22");
                BrandIds.Add("27");
                BrandIds.Add("30");
                BrandIds.Add("33");
                if(BrandIds.Contains(trade.ProductType))
                {
                    TradeAmount = TradeAmount / 100;
                }
                if(trade.ProductType == "22")
                {
                    trade.ProductType = GetLiShuaBrand(trade.TradeSnNo);
                }
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", trade.TradeSnNo); //机具sn
                dataContent.Add("mer_no", trade.MerNo); //商户号
                dataContent.Add("request_id", getRequestId(trade.Id, "deposit1")); //流水号
                dataContent.Add("deposit_amount", TradeAmount); //押金金额
                dataContent.Add("trade_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //交易时间
                dataContent.Add("card_type", 1); //卡类型
                dataContent.Add("brand", int.Parse(function.CheckInt(trade.ProductType))); //品牌
                Push("deposit", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送押金数据异常");
            }
        }

        //激活数据
        public static void Active(ActivateRecord act)
        {
            try
            {
                if(act.ProductType == "22")
                {
                    act.ProductType = GetLiShuaBrand(act.SnNo);
                }
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", act.SnNo); //机具sn
                dataContent.Add("mobile", act.MerMobile); //商户号
                dataContent.Add("request_id", getRequestId(act.Id, "active")); //流水号
                dataContent.Add("activation_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //激活时间
                dataContent.Add("brand", int.Parse(function.CheckInt(act.ProductType))); //品牌
                Push("active", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送激活数据异常");
            }
        }

        //交易数据
        public static void Trade(TradeRecord trade)
        {
            try
            {
                int QrPayFlag = 0;
                int BankCardType = 1;
                string FeeRate = function.CheckNum(trade.ErrorCode);
                string FeeAmt = function.CheckNum(trade.ErrorMsg);
                List<string> BrandIds = new List<string>();
                decimal TradeAmount = trade.TradeAmount;
                BrandIds.Add("1");
                BrandIds.Add("4");
                BrandIds.Add("6");
                BrandIds.Add("7");
                BrandIds.Add("8");
                BrandIds.Add("9");
                BrandIds.Add("15");
                BrandIds.Add("22");
                BrandIds.Add("27");
                BrandIds.Add("30");
                BrandIds.Add("33");
                if(BrandIds.Contains(trade.ProductType))
                {
                    TradeAmount = TradeAmount / 100;
                }
                if(trade.ProductType == "22")
                {
                    trade.ProductType = GetLiShuaBrand(trade.TradeSnNo);
                }
                if (trade.ProductType == "1" || trade.ProductType == "27")
                {
                    if (trade.TradeType == "02") QrPayFlag = 1;
                    BankCardType = int.Parse(trade.BankCardType);
                    decimal feeRateStr = decimal.Parse(FeeRate) * 100;
                    FeeRate = feeRateStr.ToString().TrimEnd('0');
                    if(FeeRate != "0") FeeRate = FeeRate.TrimEnd('0');
                    if(FeeAmt != "0" && !string.IsNullOrEmpty(FeeAmt)) FeeAmt = FeeAmt.TrimEnd('0');
                }
                else if (trade.ProductType == "2")
                {
                    if (trade.TradeType == "CLOUD_PAY") QrPayFlag = 1;
                    if (trade.TradeType == "CREDIT_BY_CARD")
                    {
                        BankCardType = 1;
                    }
                    else
                    {
                        BankCardType = 0;
                    }
                    FeeRate = FeeRate.Replace("0.00", "0.");
                }
                else if (trade.ProductType == "4")
                {
                    if (trade.TradeType == "200") QrPayFlag = 1;
                    if (trade.BankCardType == "100")
                    {
                        BankCardType = 1;
                    }
                    else if (trade.BankCardType == "200")
                    {
                        BankCardType = 0;
                    }
                    decimal feeRateStr = decimal.Parse(FeeRate) / 10000;
                    FeeRate = feeRateStr.ToString().TrimEnd('0');
                    if(FeeRate != "0") FeeRate = FeeRate.TrimEnd('0');
                    if(FeeAmt != "0" && !string.IsNullOrEmpty(FeeAmt)) FeeAmt = FeeAmt.TrimEnd('0');
                }
                else if (trade.ProductType == "6" || trade.ProductType == "22" || trade.ProductType == "33")
                {
                    if (trade.BankCardType == "02" || trade.BankCardType == "12" || trade.BankCardType == "30" || trade.BankCardType == "31" || trade.BankCardType == "M3" || trade.Field2 == "1517")
                    {
                        BankCardType = 1;
                    }
                    else
                    {
                        BankCardType = 0;
                    }
                }
                else if (trade.ProductType == "7")
                {
                    if (trade.BankCardType == "OA" || trade.BankCardType == "CC" || trade.BankCardType == "SCC")
                    {
                        BankCardType = 1;
                    }
                    else
                    {
                        BankCardType = 0;
                    }
                }
                else if (trade.ProductType == "8" || trade.ProductType == "9")
                {
                    if (trade.TradeType == "200") QrPayFlag = 1;
                    if (trade.BankCardType == "100")
                    {
                        BankCardType = 1;
                    }
                    else if (trade.BankCardType == "200")
                    {
                        BankCardType = 0;
                    }
                    decimal feeRateStr = decimal.Parse(FeeRate) / 10000;
                    FeeRate = feeRateStr.ToString().TrimEnd('0');
                    if(FeeRate != "0") FeeRate = FeeRate.TrimEnd('0');
                    if(FeeAmt != "0" && !string.IsNullOrEmpty(FeeAmt)) FeeAmt = FeeAmt.TrimEnd('0');
                }
                else if (trade.ProductType == "10" || trade.ProductType == "11")
                {
                    if (trade.TradeType == "F010") QrPayFlag = 1;
                    if (trade.BankCardType == "01")
                    {
                        BankCardType = 1;
                    }
                    else if (trade.BankCardType == "00")
                    {
                        BankCardType = 0;
                    }
                    FeeRate = FeeRate.Replace("0.00", "0.");
                }
                else if (trade.ProductType == "12") //盒易付
                {
                    if (trade.Field3 == "1") QrPayFlag = 1;
                    if (trade.BankCardType == "C" || trade.TradeType == "1" || trade.TradeType == "2" || trade.TradeType == "3")
                    {
                        BankCardType = 1;
                    }
                    else if (trade.BankCardType == "D")
                    {
                        BankCardType = 0;
                    }
                }
                else if (trade.ProductType == "15")
                {
                    if (trade.BankCardType == "02")
                    {
                        BankCardType = 1;
                    }
                    else
                    {
                        BankCardType = 0;
                    }
                    if(FeeAmt != "0") FeeAmt = FeeAmt.TrimEnd('0');
                }
                else if (trade.ProductType == "30") //拉卡拉
                {
                    if (trade.BankCardType == "01" || trade.BankCardType == "61" || trade.BankCardType == "91" || trade.BankCardType == "92")
                    {
                        BankCardType = 1;
                    }
                    else
                    {
                        BankCardType = 0;
                    }
                }
                else if (trade.ProductType == "34") //联动掌中宝
                {
                    if (trade.TradeType == "QuickPass") QrPayFlag = 1;
                    if (trade.BankCardType == "CC" || trade.TradeType == "AliPay" || trade.TradeType == "Wechat")
                    {
                        BankCardType = 1;
                    }
                    else
                    {
                        BankCardType = 0;
                    }
                }
                else if (Utils.Instance.IsWifi(int.Parse(trade.ProductType)))
                {
                    FeeRate = "0.60";
                    FeeAmt = trade.ErrorMsg;
                }
                Dictionary<string, string> fee = GetFee(trade.TradeSnNo, FeeRate, FeeAmt, trade.ProductType);
                FeeRate = fee["FeeRate"];
                FeeAmt = fee["FeeAmt"];
                Dictionary<string, object> dataContent = new Dictionary<string, object>();
                dataContent.Add("pos_sn", trade.TradeSnNo); //机具sn
                dataContent.Add("mer_no", trade.MerNo); //商户号
                dataContent.Add("request_id", trade.TradeSerialNo); //流水号
                dataContent.Add("trade_amount", TradeAmount); //交易金额
                dataContent.Add("trade_time", trade.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //交易时间
                dataContent.Add("brand", int.Parse(function.CheckInt(trade.ProductType))); //品牌
                dataContent.Add("card_type", BankCardType); //卡类型
                dataContent.Add("qr_pay_flag", QrPayFlag); //云闪付标记
                dataContent.Add("fee_rate", FeeRate); //费率
                dataContent.Add("fee_amt", FeeAmt); //秒到费
                if(trade.ProductType == "14")
                {
                    dataContent.Add("is_first", 1);
                }
                if(trade.ProductType == "23" || trade.ProductType == "24" || trade.ProductType == "25" || trade.ProductType == "26" || trade.ProductType == "32")
                {
                    dataContent.Add("ext_field", trade.ChannelSerial);
                }
                Push("trade", dataContent);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "推送交易数据异常");
            }
        }

        public static void Push(string dataType, Dictionary<string, object> dataContent)
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("data_type", dataType);
            data.Add("data_content", dataContent);
            // if(RedisDbconn.Instance.Get<string>("KxsPosDataQueueStatus") == "1")
            // {
            //     RedisDbconn.Instance.AddList("KxsPosDataQueue", Newtonsoft.Json.JsonConvert.SerializeObject(data));
            // }
            PosPushHelper.Instance.DoSomeThing(Newtonsoft.Json.JsonConvert.SerializeObject(data));
        }

        public static string getRequestId(int id, string type)
        {
            if(id > 0)
            {
                return function.MD5_32(id.ToString() + type);
            }
            return DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
        }

        public static string getRequestId(string str, string type)
        {
            return function.MD5_32(str + type);
        }
    
    
        public static string GetLiShuaBrand(string PosSn)
        {
            string brand = "22";
            JavaProductModels.WebCMSEntities db = new JavaProductModels.WebCMSEntities();
            JavaProductModels.KxsMachine pos = db.KxsMachine.FirstOrDefault(m => m.PosSn == PosSn);
            if(pos != null)
            {
                brand = pos.BrandId.ToString();
            }
            db.Dispose();
            return brand;
        }

        public static Dictionary<string, string> GetFee(string PosSn, string FeeRate, string FeeAmt, string ProductType)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                if(decimal.Parse(FeeRate) > 0.63M) FeeRate = "0.63";
                List<int> BrandIds = new List<int>();
                BrandIds.Add(7);
                BrandIds.Add(10);
                BrandIds.Add(11);
                BrandIds.Add(12);
                BrandIds.Add(13);
                BrandIds.Add(15);
                BrandIds.Add(16);
                Utils.WriteLog("start");
                bool op = false;
                if(ProductType == "1" || ProductType == "27")
                {
                    op = true;
                }
                else if(BrandIds.Contains(int.Parse(ProductType)))
                {
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    op = db.TmpTradeNo.Any(m => m.RecordNo == PosSn);
                    db.Dispose();
                }
                if(op)
                {
                    PosFeeItem pos = RedisDbconn.Instance.Get<PosFeeItem>("PosFee:" + PosSn);
                    if(pos == null)
                    {
                        JavaProductModels.WebCMSEntities db = new JavaProductModels.WebCMSEntities();
                        JavaProductModels.KxsMachine p = db.KxsMachine.FirstOrDefault(m => m.PosSn == PosSn && BrandIds.Contains(m.BrandId));
                        pos = new PosFeeItem() { PosSn = p.PosSn, FeeRate = p.MachineRatio, FeeAmt = p.SecondFee };
                        RedisDbconn.Instance.Set("PosFee:" + PosSn, pos);
                        db.Dispose();
                    }
                    if(pos != null)
                    {
                        result.Add("FeeRate", pos.FeeRate.ToString("f2"));
                        result.Add("FeeAmt", pos.FeeAmt.ToString("f2"));
                    }
                    else
                    {
                        result.Add("FeeRate", FeeRate);
                        result.Add("FeeAmt", FeeAmt);
                    }
                }
                else
                {
                    result.Add("FeeRate", FeeRate);
                    result.Add("FeeAmt", FeeAmt);
                }
                Utils.WriteLog("end");
            }
            catch
            {
                result.Add("FeeRate", FeeRate);
                result.Add("FeeAmt", FeeAmt);
            }
            return result;
        }


        public static Dictionary<string, string> GetFee2(string PosSn, string FeeRate, string FeeAmt, string ProductType)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                if(decimal.Parse(FeeRate) > 0.63M) FeeRate = "0.63";
                List<int> BrandIds = new List<int>();
                BrandIds.Add(1);
                BrandIds.Add(7);
                BrandIds.Add(10);
                BrandIds.Add(11);
                BrandIds.Add(15);
                BrandIds.Add(16);
                BrandIds.Add(27);
                Utils.WriteLog("start");
                if(BrandIds.Contains(int.Parse(ProductType)))
                {
                    JavaProductModels.WebCMSEntities db = new JavaProductModels.WebCMSEntities();
                    JavaProductModels.KxsMachine pos = db.KxsMachine.FirstOrDefault(m => m.PosSn == PosSn && BrandIds.Contains(m.BrandId));
                    if(pos != null)
                    {
                        result.Add("FeeRate", pos.MachineRatio.ToString("f2"));
                        result.Add("FeeAmt", pos.SecondFee.ToString("f2"));
                    }
                    else
                    {
                        result.Add("FeeRate", FeeRate);
                        result.Add("FeeAmt", FeeAmt);
                    }
                }
                else
                {
                    result.Add("FeeRate", FeeRate);
                    result.Add("FeeAmt", FeeAmt);
                }
                Utils.WriteLog("end");
            }
            catch
            {
                result.Add("FeeRate", FeeRate);
                result.Add("FeeAmt", FeeAmt);
            }
            return result;
        }
    
    }
}