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

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

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

        public void StartListen()
        {
            while (true)
            {
                WebCMSEntities db = new WebCMSEntities();
                DateTime checkDate = DateTime.Now.AddMinutes(-2);
                var list = db.ConsumerOrders.Select(m => new { m.Id, m.DivideDate, m.DivideFlag, m.IsAct, m.PayMode }).Where(m => m.DivideFlag == 1 && m.IsAct == 1 && m.DivideDate < checkDate).OrderBy(m => m.Id).Take(100).ToList();
                foreach (var sub in list)
                {
                    RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + sub.PayMode + ":List", sub.Id.ToString());
                    ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
                    if (order != null)
                    {
                        order.DivideFlag = 2;
                        db.SaveChanges();
                    }
                }
                db.Dispose();
                Thread.Sleep(5000);

                // string content = RedisDbconn.Instance.RPop<string>("PartOrderStatusQueue");
                // if(!string.IsNullOrEmpty(content))
                // {
                //     StartExcute(content);
                // }
                // else
                // {
                //     Thread.Sleep(60000);
                // }
            }
        }

        public void StartExcute(string content)
        {
            JsonData jsonData = JsonMapper.ToObject(content);
            string applyNo = jsonData["applyNo"].ToString();
            string mchtNo = jsonData["mchtNo"].ToString();
            string status = jsonData["status"].ToString();
            string payTime = jsonData["payTime"].ToString();
            WebCMSEntities db = new WebCMSEntities();
            ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.TradePayNo == applyNo);
            if(order != null)
            {
                if(status == "0")
                {
                    order.DivideFlag = 2;
                    order.DivideDate = DateTime.Now;
                }
                else
                {
                    order.DivideFlag = -1;
                    string desc = jsonData["desc"].ToString();
                    order.DivideLog = desc;
                }
                db.SaveChanges();
                RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + order.PayMode + ":List", order.Id.ToString());
            }
            db.Dispose();
        }

        public void StartCheck()
        {
            Thread th = new Thread(StartCheckListen);
            th.IsBackground = true;
            th.Start();
        }
        public void StartCheckListen()
        {
            while (true)
            {
                try
                {
                    if(DateTime.Now.Hour > 0 && DateTime.Now.Hour < 20)
                    {
                        string CheckDate = DateTime.Now.ToString("yyyyMMdd");
                        string check = function.ReadInstance("/CheckYesterdayPartOrder/" + CheckDate + ".txt");
                        if (string.IsNullOrEmpty(check))
                        {
                            function.WritePage("/CheckYesterdayPartOrder/", CheckDate + ".txt", DateTime.Now.ToString());
                            WebCMSEntities db = new WebCMSEntities();
                            DateTime checkDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
                            var list = db.ConsumerOrders.Select(m => new { m.Id, m.DivideDate, m.DivideFlag, m.IsAct, m.PayMode }).Where(m => m.DivideFlag < 2 && m.IsAct == 1 && m.DivideDate < checkDate).OrderBy(m => m.Id).Take(100).ToList();
                            foreach (var sub in list)
                            {
                                StartCheckDo(sub.Id);
                            }
                            db.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "分账复核头天订单异常");
                }
                Thread.Sleep(3600000);
            }
        }

        public void StartCheckDo(int Id)
        {
            WebCMSEntities db = new WebCMSEntities();

            ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == Id) ?? new ConsumerOrders();
            MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();

            JsonData result = JsonMapper.ToObject(HaoDaHelper.Instance.OrderDivideAccountsQuery(order.TradePayNo, merchantAdd.OutMchtNo, merchantAdd.BrandId));
            if(result["resultCode"].ToString() == "1")
            {
                string status = result["data"]["status"].ToString();
                string desc = result["data"]["desc"].ToString();
                if (status == "0")
                {
                    order.DivideFlag = 2;
                    order.DivideDate = DateTime.Now;                        
                    RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + order.PayMode + ":List", order.Id.ToString());
                }
                else
                {
                    order.DivideFlag = -1;
                }
                order.DivideLog = desc;
            }
            else
            {
                string errorCode = result["errorCode"].ToString();
                string errorDesc = result["errorDesc"].ToString();
                order.DivideFlag = -1;
                order.DivideLog = errorCode + ":" + errorDesc;
            }
            db.SaveChanges();

            db.Dispose();
        }

        // public void StartDo(string content)
        // {
        //     try
        //     {
        //         JsonData jsonObj = JsonMapper.ToObject(content);
        //         string ApplyNo = jsonObj["ApplyNo"].ToString(); //微信订单号
        //         string MchtNo = jsonObj["MchtNo"].ToString(); //商户订单号
        //         string OrderNo = jsonObj["OrderNo"].ToString(); //商户订单号
        //         JsonData result = JsonMapper.ToObject(HaoDaHelper.Instance.OrderDivideAccountsQuery(ApplyNo, MchtNo));
        //         string state = result["data"]["status"].ToString();
        //         if (result["data"]["status"].ToString() == "0")
        //         {
        //             WebCMSEntities db = new WebCMSEntities();
        //             ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.OrderNo == OrderNo && m.Status == 2);
        //             if (order != null)
        //             {
        //                 RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + order.PayMode + ":List", order.Id.ToString());
        //             }
        //             db.Dispose();
        //         }
        //         else
        //         {
        //             RedisDbconn.Instance.AddList("ProfitShareHdQueue", content);
        //         }
        //     }
        //     catch (Exception ex)
        //     {
        //         LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "分账队列异常");
        //     }
        // }
    }
}