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

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

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

        public void StartListen()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("MerchantConfirmQueue");
                if (!string.IsNullOrEmpty(content))
                {                    
                    try
                    {
                        JsonData jsonObj = JsonMapper.ToObject(content);
                        int MerchantId = int.Parse(jsonObj["MerchantId"].ToString());
                        int Kind = 0;
                        if(content.Contains("\"Kind\""))
                        {
                            Kind = int.Parse(jsonObj["Kind"].ToString());
                        }
                        StartDo(MerchantId, Kind);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void StartDo(int MerchantId, int Kind = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
            if (AddInfo != null && merchant != null)
            {
                string BusinessCode = AddInfo.BusinessCode;
                if (string.IsNullOrEmpty(BusinessCode))
                { 
                    BusinessCode = "LKB" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(5);
                    AddInfo.BusinessCode = BusinessCode;
                }
                string pwd = AddInfo.MobilePhone.Substring(5);
                merchant.LoginPwd = function.MD532(pwd);
                MerchantParamSet query = db.MerchantParamSet.FirstOrDefault(m => m.Id == MerchantId);
                if (query == null)
                {
                    query = new MerchantParamSet();
                    query.IsAll = 1;
                    db.MerchantParamSet.Add(query);
                    db.SaveChanges();
                }
                MerchantForMobile merchantForMobile = db.MerchantForMobile.FirstOrDefault(m => m.Mobile == AddInfo.MobilePhone);
                if (merchantForMobile == null)
                {
                    merchantForMobile = db.MerchantForMobile.Add(new MerchantForMobile()
                    {
                        Mobile = AddInfo.MobilePhone,
                    }).Entity;
                    db.SaveChanges();
                }
                merchantForMobile.MerchantId = MerchantId;
                MerchantLoginInfo info = db.MerchantLoginInfo.FirstOrDefault(m => m.LoginMobile == AddInfo.MobilePhone);
                if (info == null)
                {
                    info = db.MerchantLoginInfo.Add(new MerchantLoginInfo()
                    {
                        LoginMobile = AddInfo.MobilePhone,
                    }).Entity;
                    db.SaveChanges();
                }
                info.LoginPwd = function.MD532(pwd);
                db.SaveChanges();
                MerchantAccountLinkInfo infolink = db.MerchantAccountLinkInfo.FirstOrDefault(m => m.LoginId == info.Id && m.MerchantId == MerchantId && m.Kind == 1);
                if (infolink == null)
                {
                    infolink = db.MerchantAccountLinkInfo.Add(new MerchantAccountLinkInfo()
                    {
                        LoginId = info.Id,
                        MerchantId = MerchantId,
                        Kind = 1,
                    }).Entity;
                    db.SaveChanges();
                }
                //微信
                if ((Kind == 0 || Kind == 2) && AddInfo.Status <= 0)
                {
                    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();
                    }
                }

                //支付宝
                if ((Kind == 0 || Kind == 1) && AddInfo.QueryCount <= 0)
                {
                    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.AlipayAuthToken = json["alipay_open_agent_confirm_response"]["app_auth_token"].ToString();
                                AddInfo.SeoTitle = batch_no;
                                db.SaveChanges();
                                RedisDbconn.Instance.AddList("AlipaySignQueue", new MerchantSign()
                                {
                                    BusinessCode = batch_no,
                                    MerchantAddInfoId = MerchantId,
                                    Status = ""
                                });
                                // content = AlipayFunction.Instance.QuerySignStatus(batch_no);

                                // content = AlipayFunction.Instance.CommonSignConfirm(batch_no);
                                // json = JsonMapper.ToObject(content);
                                // if (json["alipay_open_agent_commonsign_confirm_response"]["code"].ToString() == "10000")
                                // {
                                //     AddInfo.QueryCount = 0;
                                //     AddInfo.SeoTitle = batch_no;
                                //     db.SaveChanges();
                                //     List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("MerchantSignList", 1, 10000000);
                                //     bool op = signs.Any(m => m.BusinessCode == batch_no);
                                //     if (!op)
                                //     {
                                //         RedisDbconn.Instance.AddList("AlipaySignQueue", new MerchantSign()
                                //         {
                                //             BusinessCode = batch_no,
                                //             MerchantAddInfoId = MerchantId,
                                //             Status = ""
                                //         });
                                //     }
                                //     signs.Clear();
                                //     if (db.MerchantInfo.Any(m => m.Id == merchant.Id) == false)
                                //     {
                                //         RedisDbconn.Instance.AddList("MerchantList:" + merchant.UserId, merchant);
                                //     }
                                // }
                                // else
                                // {
                                //     checkAlipay = false;
                                // }
                            }
                            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();
                    }
                }
            }
            db.Dispose();
        }
    }
}