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

namespace MySystem
{
    /// <summary>
    /// 好哒测试服务
    /// </summary>
    public class TestHaoDaService
    {
        public readonly static TestHaoDaService Instance = new TestHaoDaService();
        private TestHaoDaService()
        { }

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

        public void StartListen()
        {
            // StartProfitShareListen(152455);//提交分账
            StartProfitShareListen(153249);//提交分账
        }

        public void StartProfitShareListen(int OrderId)
        {

            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 == 2 && m.IsAct == 1 && m.CreateDate < checkDate).OrderBy(m => m.Id).Take(10).ToList();
                var list = db.ConsumerOrders.Select(m => new { m.Id, m.CreateDate, m.Status, m.IsAct, m.PayMode }).Where(m => m.Id == OrderId).OrderBy(m => m.Id).Take(10).ToList();
                foreach (var sub in list)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "微信分账队列异常");
                    LogHelper.Instance.WriteLog("Id:" + sub.Id, "微信分账队列异常");
                    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();
                        LogHelper.Instance.WriteLog("IsAct:" + order.IsAct, "微信分账队列监听");
                        LogHelper.Instance.WriteLog("PayMoney:" + order.PayMoney, "微信分账队列监听");
                        LogHelper.Instance.WriteLog("MinPayMoney:" + set.MinPayMoney, "微信分账队列监听");
                        if (order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
                        {
                            MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                            //添加分账接收方
                            if (merchant.Version == 0)
                            {
                                WeChatFunction.Instance.AddReceive(merchantAdd.SubMchid, "MERCHANT_ID", WeChatFunction.Instance.MchId, WeChatFunction.Instance.MchName, "PARTNER");
                                merchant.Version = 1;
                                db.SaveChanges();
                            }
                            LogHelper.Instance.WriteLog("准备分账", "微信分账队列监听");
                            //发起分账
                            decimal fee = order.PayMoney; //单位：分
                            if (fee >= 1)
                            {
                                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 = servicefee * 100;
                                int servicefeeNum = int.Parse(servicefee.ToString("f0"));
                                List<ReceiverList> Receivers = new List<ReceiverList>();
                                Receivers.Add(new ReceiverList()
                                {
                                    type = "MERCHANT_ID",  //分账接收方类型
                                    account = WeChatFunction.Instance.MchId,  //分账接收方账号
                                    amount = servicefeeNum,  //分账金额
                                    description = "服务费",  //分账描述
                                });
                                LogHelper.Instance.WriteLog("TradeNo:" + TradeNo, "微信分账队列监听");
                                LogHelper.Instance.WriteLog("OrderNo:" + OrderNo, "微信分账队列监听");
                                LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(Receivers), "微信分账队列监听");
                                string ProfitShareResult = WeChatFunction.Instance.ProfitShare(merchantAdd.SubMchid, TradeNo, OrderNo, Receivers);
                                LogHelper.Instance.WriteLog("分账结果:" + ProfitShareResult, "微信分账队列监听");
                                order.DivideLog = "请求分账日志：" + ProfitShareResult;
                                db.SaveChanges();

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

        }

    }
}