using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.Models;
using Library;
using LitJson;
using System.Text.RegularExpressions;
using System.Threading;
/// <summary>
/// 更新签约码
/// </summary>
namespace MySystem
{
    public class UpdateSignUrlService
    {
        public readonly static UpdateSignUrlService Instance = new UpdateSignUrlService();
        private UpdateSignUrlService()
        { }

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

        public void StartListen()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("UpdateSignUrlQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    JsonData json = JsonMapper.ToObject(content);
                    string result = UpdateSignUrl(int.Parse(json["MerchantId"].ToString()), int.Parse(json["Kind"].ToString()));
                    if (result == "wait")
                    {
                        Thread.Sleep(10000);
                        RedisDbconn.Instance.AddList("UpdateSignUrlQueue", content);
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public string UpdateSignUrl(int MerchantId, int Kind)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);

                if (Kind == 1) //支付宝
                {
                    string content = AlipayFunction.Instance.GetBatchNo(AddInfo.IdCardName, AddInfo.MobilePhone, AddInfo.CreateMan);
                    JsonData json = JsonMapper.ToObject(content);
                    if (json["alipay_open_agent_create_response"]["code"].ToString() == "10000")
                    {
                        AddInfo.AlipayRemark = "";
                        AddInfo.QueryCount = 0;
                        merchant.QueryCount = 0;
                        db.SaveChanges();
                        string batch_no = json["alipay_open_agent_create_response"]["batch_no"].ToString();
                        string Qualifications = AddInfo.Qualifications;
                        if (!string.IsNullOrEmpty(Qualifications))
                        {
                            Qualifications = function.getPath("/" + Qualifications);
                        }
                        content = AlipayFunction.Instance.CommonSign(batch_no, AddInfo.UpdateMan, AddInfo.LicenseNumber, AddInfo.LicenseCopy, AddInfo.LicenseCopy, AddInfo.StoreEntrancePic, AddInfo.IndoorPic);
                        json = JsonMapper.ToObject(content);
                        if (json["alipay_open_agent_facetoface_sign_response"]["code"].ToString() == "10000")
                        {
                            content = AlipayFunction.Instance.AgentConfirm(batch_no);
                            json = JsonMapper.ToObject(content);
                            if (json["alipay_open_agent_confirm_response"]["code"].ToString() == "10000")
                            {
                                AddInfo.SeoTitle = batch_no;
                                db.SaveChanges();
                                RedisDbconn.Instance.AddList("AlipaySignQueue", new MerchantSign()
                                {
                                    BusinessCode = batch_no,
                                    MerchantAddInfoId = MerchantId,
                                    Status = ""
                                });
                            }
                            else
                            {
                                AddInfo.AlipayRemark = json["alipay_open_agent_confirm_response"]["sub_msg"].ToString();
                                AddInfo.QueryCount = -1;
                                merchant.QueryCount = -1;
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            AddInfo.AlipayRemark = json["alipay_open_agent_facetoface_sign_response"]["sub_msg"].ToString();
                            AddInfo.QueryCount = -1;
                            merchant.QueryCount = -1;
                            db.SaveChanges();
                        }
                    }
                    else
                    {
                        AddInfo.AlipayRemark = json["alipay_open_agent_create_response"]["sub_msg"].ToString();
                        AddInfo.QueryCount = -1;
                        merchant.QueryCount = -1;
                        db.SaveChanges();
                    }
                }
                if (Kind == 2) //微信
                {
                    string BusinessCode = AddInfo.BusinessCode;
                    if (string.IsNullOrEmpty(BusinessCode))
                    {
                        BusinessCode = "LKB" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(5);
                        AddInfo.BusinessCode = BusinessCode;
                    }
                    string result = WeChatFunction.Instance.MerchantCreate(AddInfo, merchant);
                    if (result.Contains("\"applyment_id\":"))
                    {
                        JsonData jsonObj = JsonMapper.ToObject(result);
                        AddInfo.ApplymentId = jsonObj["applyment_id"].ToString();
                        AddInfo.WeChatRemark = "";
                        AddInfo.Status = 0;
                        merchant.Status = 0;
                        db.SaveChanges();
                        List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("MerchantSignList", 1, 10000000);
                        bool op = signs.Any(m => m.BusinessCode == BusinessCode);
                        if (!op)
                        {
                            RedisDbconn.Instance.AddList("WeChatSignQueue", new MerchantSign()
                            {
                                BusinessCode = BusinessCode,
                                MerchantAddInfoId = MerchantId,
                                Status = ""
                            });
                        }
                        signs.Clear();
                        AddInfo.ApplymentId = AddInfo.ApplymentId;
                        db.SaveChanges();
                    }
                    else if (result.Contains("\"message\":"))
                    {
                        JsonData jsonObj = JsonMapper.ToObject(result);
                        AddInfo.Status = -1;
                        merchant.Status = -1;
                        AddInfo.WeChatRemark = jsonObj["message"].ToString();
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "更新签约码队列异常");
            }
            return "";
        }
    }
}