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

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

        public void Start()
        {
            Thread th = new Thread(Listen);
            th.IsBackground = true;
            th.Start();
        }

        public void Listen()
        {
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("PayCallBack");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        dosomething(content);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "支付宝回调异常");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        private void dosomething(string content)
        {
            //{"out_trade_no":"2023061514385419860385846","transaction_id":"2023061522001451251430691917","total_fee":"0.01","pay_mode":"1","openid":"","attach":""}
            JsonData orderObj = JsonMapper.ToObject(content);
            string OrderNo = orderObj["out_trade_no"].ToString();
            string TradeNo = orderObj["transaction_id"].ToString();
            WebCMSEntities db = new WebCMSEntities();
            ConsumerOrderForNo forNo = db.ConsumerOrderForNo.FirstOrDefault(m => m.OrderNo == OrderNo);
            if (forNo != null)
            {
                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == forNo.OrderIds && m.Status == 0);
                if (order != null)
                {
                    order.Status = 1;
                    order.UpdateDate = DateTime.Now;
                    order.PayMoney = order.PayMoney;
                    order.MaxDivi = order.MaxDivi;
                    order.SeoTitle = TradeNo;
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
                    MerchantAddInfo addMer = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                    order.UserId = merchant.UserId;
                    ConsumerOrders check = db.ConsumerOrders.FirstOrDefault(m => m.Id < order.Id && m.Status > 0 && m.PayMode == order.PayMode && m.MerchantId == order.MerchantId);
                    if (check != null)
                    {
                        order.QueryCount = check.QueryCount + 1;
                    }
                    else
                    {
                        order.QueryCount = 1;
                    }
                    db.SaveChanges();

                    //语音播报
                    var machines = db.PosMachines.Select(m => new { m.DeviceKind, m.BrandId, m.Detail, m.BindMerchantId }).Where(m => m.DeviceKind == "1" && m.BindMerchantId == order.MerchantId);
                    foreach (var machine in machines)
                    {
                        if (machine.BrandId == 2)
                        {
                            TianYuVoiceHelper.Instance.doSomething(DateTime.Now.ToString("yyyyMMddHHmmssfff"), machine.Detail, order.PayMoney.ToString("f2"));
                        }
                        else if (machine.BrandId == 3)
                        {
                            MqLinksHelper.Instance.doSomething(machine.Detail, order.PayMoney.ToString("f2"));
                        }
                    }

                    //发送订单到客小爽MQ
                    OrderMessageHelper.SendOrderMsg(order);

                    //推送交易给java
                    PosPushDataNewHelper.Trade(order, addMer);
                }
            }
            db.Dispose();
        }






        //分账队列
        public void StartProfitShare()
        {
            Thread th = new Thread(StartProfitShareListen);
            th.IsBackground = true;
            th.Start();
        }

        public void StartProfitShareListen()
        {
            bool op = true;
            while (op)
            {
                try
                {
                    WebCMSEntities db = new WebCMSEntities();
                    DateTime checkDate = DateTime.Now.AddMinutes(-1);
                    var list = db.ConsumerOrders.Select(m => new { m.Id, m.CreateDate, m.Status, m.IsAct, m.PayMode }).Where(m => m.Status == 1 && m.PayMode == 1 && m.IsAct == 1 && m.CreateDate < checkDate).OrderBy(m => m.Id).Take(10).ToList();
                    foreach (var sub in list)
                    {
                        ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
                        if (order != null)
                        {
                            order.Status = 2;
                            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
                            MerchantParamSet set = db.MerchantParamSet.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantParamSet();
                            if (order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
                            {
                                MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                                //添加分账接收方
                                if (merchantAdd.Sort == 0)
                                {
                                    string content = AlipayFunction.Instance.BindSettleRelation(DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8), AlipayFunction.Instance.Pid, merchantAdd.AlipayAuthToken);
                                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + content, "支付宝添加分账方");
                                    merchantAdd.Sort = 1;
                                    db.SaveChanges();
                                }
                                //发起分账
                                decimal fee = order.PayMoney * 0.01M;
                                if (fee >= 0.01M)
                                {
                                    string TradeNo = order.SeoTitle;
                                    string OrderNo = order.OrderNo;
                                    // decimal hdfee = 0.0038M * order.PayMoney * (1 - set.GetPercent - 0.01M);
                                    // hdfee = decimal.Parse(hdfee.ToString("f2"));
                                    // decimal servicefee = 0.01M * order.PayMoney - hdfee;
                                    // servicefee = decimal.Parse(servicefee.ToString("f2"));
                                    List<RoyaltyParameters> Parameters = new List<RoyaltyParameters>();
                                    Parameters.Add(new RoyaltyParameters()
                                    {
                                        Account = AlipayFunction.Instance.Pid,
                                        Amount = fee.ToString("f2"),
                                    });
                                    string ProfitShareResult = AlipayFunction.Instance.Settle(OrderNo, TradeNo, Parameters, merchantAdd.AlipayAuthToken);
                                    order.DivideLog = "请求分账日志：" + ProfitShareResult;
                                    order.DivideFlag = 1;
                                    db.SaveChanges();

                                    //开始监听分账状态
                                    Dictionary<string, object> req = new Dictionary<string, object>();
                                    req.Add("TradeNo", TradeNo); //支付宝订单号
                                    req.Add("OrderNo", OrderNo); //商户订单号
                                    req.Add("AuthToken", merchantAdd.AlipayAuthToken);
                                    RedisDbconn.Instance.AddList("AlipayShareQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
                                }
                                else
                                {
                                    RedisDbconn.Instance.AddList("ConsumerOrders:Divi:1:List", order.Id.ToString());
                                    // RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:1:" + order.MerchantId, order);
                                }
                            }
                        }
                    }
                    db.SaveChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "支付宝分账队列异常");
                }
                Thread.Sleep(2000);
            }
        }



        //触发分账接口
        public void StartDivi()
        {
            Thread th = new Thread(ListenDivi);
            th.IsBackground = true;
            th.Start();
        }

        public void ListenDivi()
        {
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("AddAlipayDiviQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        int id = int.Parse(function.CheckInt(content));
                        WebCMSEntities db = new WebCMSEntities();
                        ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == id);
                        if (order != null)
                        {
                            MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                            MerchantParamSet set = db.MerchantParamSet.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantParamSet();
                            if (order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
                            {
                                //发起分账
                                decimal fee = order.PayMoney * 0.01M;
                                if (fee >= 0.01M)
                                {
                                    string TradeNo = order.SeoTitle;
                                    string OrderNo = order.OrderNo;
                                    List<RoyaltyParameters> Parameters = new List<RoyaltyParameters>();
                                    Parameters.Add(new RoyaltyParameters()
                                    {
                                        Account = AlipayFunction.Instance.Pid,
                                        Amount = fee.ToString("f2"),
                                    });
                                    string ProfitShareResult = AlipayFunction.Instance.Settle(OrderNo, TradeNo, Parameters, merchantAdd.AlipayAuthToken);
                                    order.DivideLog = "请求分账日志：" + ProfitShareResult;
                                    order.DivideFlag = 1;
                                    db.SaveChanges();

                                    //开始监听分账状态
                                    Dictionary<string, object> req = new Dictionary<string, object>();
                                    req.Add("TradeNo", TradeNo); //支付宝订单号
                                    req.Add("OrderNo", OrderNo); //商户订单号
                                    req.Add("AuthToken", merchantAdd.AlipayAuthToken);
                                    RedisDbconn.Instance.AddList("AlipayShareQueue", Newtonsoft.Json.JsonConvert.SerializeObject(req));
                                }
                            }
                        }
                        db.Dispose();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "补微信分账异常");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }
    }
}