using System;
using System.Collections.Generic;
using Library;
using LitJson;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.PxcModels;
using System.Security.Cryptography;
using System.Text;

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

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

        public void dosomething()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("SetDepositQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        WebCMSEntities db = new WebCMSEntities();
                        JsonData jsonObj = JsonMapper.ToObject(data);
                        string PosIds = jsonObj["PosId"].ToString();
                        int Kind = int.Parse(function.CheckInt(jsonObj["Kind"].ToString()));
                        int RecordId = 0;
                        if(data.Contains("\"RecordId\""))
                        {
                            RecordId = int.Parse(function.CheckInt(jsonObj["RecordId"].ToString()));
                        }
                        string OpMan = jsonObj["OpMan"].ToString();
                        if(!string.IsNullOrEmpty(PosIds))
                        {
                            List<int> ids = new List<int>();
                            string[] PosIdList = PosIds.Split(',');
                            foreach(string sub in PosIdList)
                            {
                                ids.Add(int.Parse(sub));
                            }
                            List<KqProducts> brands = db.KqProducts.ToList();
                            List<PosMachinesTwo> poslist = db.PosMachinesTwo.Where(m => ids.Contains(m.Id)).ToList();
                            List<int> mids = poslist.Select(m => m.BindMerchantId).ToList();
                            List<PosMerchantInfo> merchantlist = db.PosMerchantInfo.Where(m => mids.Contains(m.Id)).ToList();
                            Dictionary<int, List<PosMachinesTwo>> userPosList = new Dictionary<int, List<PosMachinesTwo>>();
                            foreach(PosMachinesTwo pos in poslist)
                            {
                                PosMerchantInfo merchant = merchantlist.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                                if(merchant != null)
                                {
                                    decimal Fee = Kind == 1 ? 0.63M : 0.6M;
                                    if(Kind == 0)
                                    {
                                        pos.UpFeeFlag = 1;
                                        pos.UpFeeMan = OpMan;
                                        pos.UpFeeDate = DateTime.Now;
                                        merchant.Status = 1;
                                        // merchant.SeoKeyword = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    }
                                    else if(Kind == 1)
                                    {
                                        pos.UpFeeFlag = 1;
                                        pos.UpFeeMan = OpMan;
                                        pos.UpFeeDate = DateTime.Now;
                                        merchant.Status = 1;
                                        // merchant.SeoKeyword = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    }
                                    else if(Kind == 2)
                                    {
                                        pos.DownFeeFlag = 1;
                                        pos.DownFeeMan = OpMan;
                                        pos.DownFeeDate = DateTime.Now;
                                        if(pos.BrandId == 12 || pos.BrandId == 13)
                                        {
                                            pos.DownFee = 0.6M;
                                        }
                                        else
                                        {
                                            pos.DownFee = 0.63M;
                                        }
                                        merchant.Status = 0;
                                        // merchant.SeoKeyword = "";
                                        // SetRecordResult(db, RecordId, 1);
                                    }
                                    else if(Kind == 3)
                                    {
                                        pos.DownFeeFlag = 1;
                                        pos.DownFeeMan = OpMan;
                                        pos.DownFeeDate = DateTime.Now;
                                        pos.DownFee = 0.6M;
                                        merchant.Status = 0;
                                        // merchant.SeoKeyword = "";
                                        // SetRecordResult(db, RecordId, 1);
                                    }
                                    db.SaveChanges();
                                    pos.QueryCount = Kind;
                                    if(Kind > 1) //只有调降发消息
                                    {
                                        if(userPosList.ContainsKey(pos.BuyUserId))
                                        {
                                            userPosList[pos.BuyUserId].Add(pos);
                                        }
                                        else
                                        {
                                            List<PosMachinesTwo> subPos = new List<PosMachinesTwo>();
                                            subPos.Add(pos);
                                            userPosList.Add(pos.BuyUserId, subPos);
                                        }
                                    }
                                    if(Kind > 1)
                                    {
                                        RedisDbconn.Instance.AddList("SetDepositPostQueue", data);
                                    }
                                }
                            }
                            foreach(int UserId in userPosList.Keys)
                            {
                                string snhtml = "", snhtml2 = "";
                                foreach (var items in userPosList[UserId])
                                {
                                    var mer = merchantlist.FirstOrDefault(m => m.Id == items.BindMerchantId) ?? new PosMerchantInfo();
                                    var brand = brands.FirstOrDefault(m => m.Id == items.BrandId) ?? new KqProducts();
                                    if(items.QueryCount == 1)
                                    {
                                        snhtml += "<div style='margin-bottom: .48rem;'><div class='f16'>商户姓名：" + mer.MerRealName + "</div>";
                                        snhtml += "<div class='f16'>机具品牌：" + brand.Name + "</div>";
                                        snhtml += "<div class='f16'>SN：" + items.PosSn + "</div>";
                                        string DownFeeDate = items.DownFeeDate == null ? "" : items.DownFeeDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                    }
                                    else if(items.QueryCount == 2)
                                    {
                                        snhtml2 += "<div style='margin-bottom: .48rem;'><div class='f16'>商户姓名：" + mer.MerRealName + "</div>";
                                        snhtml2 += "<div class='f16'>机具品牌：" + brand.Name + "</div>";
                                        snhtml2 += "<div class='f16'>SN：" + items.PosSn + "</div>";
                                        string DownFeeDate = items.DownFeeDate == null ? "" : items.DownFeeDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                        if(items.BrandId == 12 || items.BrandId == 13)
                                        {
                                            snhtml2 += "<div class='f16'>当前费率：0.6%</div>";
                                        }
                                        else
                                        {
                                            snhtml2 += "<div class='f16'>当前费率：0.63%</div>";
                                        }
                                        snhtml2 += "<div class='f16'>费率调整时间：" + DownFeeDate + "</div>";
                                    }
                                }
                                if(!string.IsNullOrEmpty(snhtml))
                                {
                                    snhtml = "<div style='margin-bottom: .48rem;'>" + snhtml + "</div>";
                                    // RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                                    // {
                                    //     UserId = Convert.ToInt32(UserId), //创客
                                    //     Title = "商户费率变更通知", //标题
                                    //     Content = "<div class='f16' style='margin-bottom: .72rem'>您的部分机具已绑定超过180天，刷卡费率已自动变更为0.63%，如需调整费率，请前往我的商户-商户详情中调整费率</div>" + snhtml, //内容
                                    //     Summary = "您的部分机具已绑定超过180天，刷卡费率已自动变更为0.63%，如需调整费率，请前往我的商户-商户详情中调整费率",
                                    //     CreateDate = DateTime.Now,
                                    // }));
                                    RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                                    {
                                        UserId = Convert.ToInt32(UserId), //创客
                                        Title = "机具费率即将调升提醒", //标题
                                        Content = "<div class='f16' style='margin-bottom: .72rem'>您的部分机具已绑定满88天，48小时后该机具刷卡费率将恢复0.63%，如需调整费率，请前往我的商户-商户详情中点击调整</div>" + snhtml, //内容
                                        Summary = "您的部分机具已绑定满88天，48小时后该机具刷卡费率将恢复0.63%，如需调整费率，请前往我的商户-商户详情中点击调整",
                                        CreateDate = DateTime.Now,
                                    }));
                                }
                                else if(!string.IsNullOrEmpty(snhtml2))
                                {
                                    snhtml2 = "<div style='margin-bottom: .48rem;'>" + snhtml2 + "</div>";
                                    RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                                    {
                                        UserId = Convert.ToInt32(UserId), //创客
                                        Title = "商户费率变更通知", //标题
                                        Content = "<div class='f16' style='margin-bottom: .72rem'>您的商户刷卡交易费率已变更成功！</div>" + snhtml2, //内容
                                        Summary = "您的商户刷卡交易费率已变更成功！",
                                        CreateDate = DateTime.Now,
                                    }));
                                }
                            }
                        }
                        db.Dispose();
                    }
                    catch (Exception ex)
                    {                        
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "设置费率队列异常");
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }

        private void SetRecordResult(WebCMSEntities db, int RecordId, int Status, string Note = "")
        {
            if(RecordId > 0)
            {
                PosMachinesFeeChangeRecord record = db.PosMachinesFeeChangeRecord.FirstOrDefault(m => m.Id == RecordId);
                if(record != null)
                {
                    record.Status = Status;
                    record.SeoDescription = Note;
                }
            }
        }
    }
}