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

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

        public void Start(JobMqMsg jobInfo)
        {
            try
            {
                PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                List<MerchantSign> deletes = new List<MerchantSign>();
                List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("WeChatSignList", 1, 10000000); // TODO: 换成mysql存储遍历
                foreach (MerchantSign sign in signs)
                {
                    Dictionary<string, object> dic = new WeChatFunction().QueryMerchant(sign.BusinessCode);
                    if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_SIGNED")
                    {
                        string sign_url = dic["sign_url"].ToString();
                        PxcModels.MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId && m.Status == 0);
                        if (merchantadd != null)
                        {
                            merchantadd.Status = 1;
                            string SignUrlList = function.CheckNull(merchantadd.SeoKeyword);
                            if (string.IsNullOrEmpty(SignUrlList))
                            {
                                SignUrlList = "WeChat:" + sign_url + ";";
                            }
                            else
                            {
                                SignUrlList += "WeChat:" + sign_url+ ";";
                            }
                            merchantadd.SeoKeyword = SignUrlList;
                            PxcModels.MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                            if (merchantadd.Status > 0 && merchantadd.QueryCount > 0)
                            {
                                merchant.Status = 1;
                            }
                            db.SaveChanges();
                            RedisDbconn.Instance.Set("MerchantAddInfo:" + sign.MerchantAddInfoId, merchantadd);
                        }
                    }
                    else if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_FINISHED")
                    { 
                        PxcModels.MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId && m.Status == 1);
                        if (merchantadd != null)
                        {
                            merchantadd.Status = 2;
                            RedisDbconn.Instance.Set("MerchantAddInfo:" + sign.MerchantAddInfoId, merchantadd);
                            PxcModels.MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                            if (merchantadd.Status == 2 && merchantadd.QueryCount == 2)
                            {
                                merchant.Status = 2;
                            }
                            db.SaveChanges();
                            if (merchantadd.Status == 2 && merchantadd.QueryCount == 2)
                            {
                                List<MerchantInfo> merchants = RedisDbconn.Instance.GetList<MerchantInfo>("TmpMerchantInfo:" + merchant.UserId, 1, 1000000);
                                MerchantInfo check = merchants.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                                if (check != null)
                                {
                                    merchants.Remove(check);
                                    RedisDbconn.Instance.Clear("TmpMerchantInfo:" + merchant.UserId);
                                    RedisDbconn.Instance.AddList("TmpMerchantInfo:" + merchant.UserId, merchants.ToArray());
                                }
                            }
                            deletes.Add(sign);
                        }
                    }
                    else if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
                    {
                        PxcModels.MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchantadd != null)
                        {
                            string Season = function.CheckNull(merchantadd.SeoDescription);
                            if (string.IsNullOrEmpty(Season))
                            {
                                Season = "WeChat:" + dic["reject_reason"].ToString() + ";";
                            }
                            else
                            {
                                Season = Regex.Replace(Season, "WeChat:.*?;", "");
                                Season += "WeChat:" + dic["reject_reason"].ToString() + ";";
                            }
                            merchantadd.SeoDescription = Season;
                            merchantadd.Status = -1;
                            db.SaveChanges();
                            RedisDbconn.Instance.Set("MerchantAddInfo:" + sign.MerchantAddInfoId, merchantadd);
                            PxcModels.MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                            if (merchant != null)
                            {
                                merchant.Status = -1;
                                RedisDbconn.Instance.Set("MerchantInfo:" + sign.MerchantAddInfoId, merchant);
                            }
                            deletes.Add(sign);
                        }
                    }
                    else
                    {
                        string sub_mchid = "";
                        if (dic.ContainsKey("sub_mchid"))
                        {
                            sub_mchid = dic["sub_mchid"].ToString();
                            PxcModels.MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                            if (merchantadd != null)
                            {
                                merchantadd.SubMchid = sub_mchid;
                                db.SaveChanges();
                                RedisDbconn.Instance.Set("MerchantAddInfo:" + sign.MerchantAddInfoId, merchantadd);
                            }
                        }
                    }
                }
                if (deletes.Count > 0)
                {
                    foreach (MerchantSign delete in deletes)
                    {
                        signs.Remove(delete);
                    }
                    RedisDbconn.Instance.Clear("WeChatSignList");
                    RedisDbconn.Instance.AddList("WeChatSignList", signs.ToArray());
                }
                // jobInfo.Status = 1;
                // jobInfo.Msg = "执行完成";
                // RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "PublicBack");
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public:merchant:signerr");
            }
        }
    }
}