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

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

        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>("AlipaySignList", 1, 10000000); // TODO: 换成mysql存储遍历
                foreach (MerchantSign sign in signs)
                {
                    string content = new AlipayFunction().QuerySignStatus(sign.BusinessCode);
                    JsonData dic = JsonMapper.ToObject(content);
                    if (dic["alipay_open_agent_order_query_response"]["code"].ToString() == "10000")
                    {
                        if (dic["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_CONFIRM")
                        {
                            string sign_url = dic["alipay_open_agent_order_query_response"]["confirm_url"].ToString();
                            PxcModels.MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId && m.QueryCount == 0);
                            if (merchantadd != null)
                            {
                                merchantadd.QueryCount = 1;
                                string confirm_url = "/static/alipay_confirm_url/";
                                string fileName = function.MD5_16(Guid.NewGuid().ToString());
                                function.CreateQRCode2(sign_url, fileName, "/bsserver_com" + confirm_url);
                                string SignUrlList = function.CheckNull(merchantadd.SeoKeyword);
                                if (string.IsNullOrEmpty(SignUrlList))
                                {
                                    SignUrlList = "Alipay:" + confirm_url + ";";
                                }
                                else
                                {
                                    SignUrlList = "Alipay:" + confirm_url+ ";" + SignUrlList;
                                }
                                merchantadd.SeoKeyword = SignUrlList;
                                merchantadd.SeoTitle = dic["alipay_open_agent_order_query_response"]["merchant_pid"].ToString();
                                db.SaveChanges();
                                RedisDbconn.Instance.Set("MerchantAddInfo:" + sign.MerchantAddInfoId, merchantadd);
                            }
                        }
                        else if (dic["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_CONFIRM_SUCCESS")
                        {
                            PxcModels.MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId && m.QueryCount < 2);
                            if (merchantadd != null)
                            {
                                merchantadd.QueryCount = 2;
                                db.SaveChanges();
                                RedisDbconn.Instance.Set("MerchantAddInfo:" + sign.MerchantAddInfoId, merchantadd);
                                if (merchantadd.Status == 2 && merchantadd.QueryCount == 2)
                                {
                                    PxcModels.MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                                    List<PxcModels.MerchantInfo> merchants = RedisDbconn.Instance.GetList<PxcModels.MerchantInfo>("TmpMerchantInfo:" + merchant.UserId, 1, 1000000);
                                    PxcModels.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["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_APPLY_ORDER_CANCELED")
                        { 
                            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 = "Alipay:" + dic["alipay_open_agent_order_query_response"]["reject_reason"].ToString() + ";";
                                }
                                else
                                {
                                    Season = Regex.Replace(Season, "Alipay:.*?;", "");
                                    Season += "Alipay:" + dic["alipay_open_agent_order_query_response"]["reject_reason"].ToString() + ";";
                                }
                                merchantadd.SeoDescription = Season;
                                merchantadd.QueryCount = -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);
                            }
                        }
                    }
                }
                if (deletes.Count > 0)
                {
                    foreach (MerchantSign delete in deletes)
                    {
                        signs.Remove(delete);
                    }
                    RedisDbconn.Instance.Clear("AliaySignList");
                    RedisDbconn.Instance.AddList("AliaySignList", 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");
            }
        }
    }
}