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

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

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

        public void StartListen()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("WeChatSignHdQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    if(content == "sleep")
                    {
                        RedisDbconn.Instance.AddList("WeChatSignHdQueue", "sleep");
                        Thread.Sleep(60000);
                    }
                    else
                    {
                        QueryMerchantStatus queryMerchantStatus = Newtonsoft.Json.JsonConvert.DeserializeObject<QueryMerchantStatus>(content);
                        string result = StartDo(queryMerchantStatus);
                        if (result == "wait")
                        {
                            Thread.Sleep(500);
                            RedisDbconn.Instance.AddList("WeChatSignHdQueue", queryMerchantStatus);
                        }
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public string StartDo(QueryMerchantStatus query)
        {
            try
            {
                var mId = int.Parse(query.MerchantId);
                WebCMSEntities db = new WebCMSEntities();
                //查询商户审核状态
                var returnInfo = HaoDaHelper.Instance.QueryMerchantStatus(HaoDaHelper.BrhCode, query.MerchantNo);
                JsonData dic = JsonMapper.ToObject(returnInfo);
                //审核成功(1- 待审核 2 -审核中 3 -审核被拒绝 4 -审核通过 6 -待复核)
                if (dic["data"]["code"].ToString() == "4" && !string.IsNullOrEmpty(dic["data"]["storeNo"].ToString()) && !string.IsNullOrEmpty(dic["data"]["outMchtNo"].ToString()))
                {
                    //查询商户是否存在
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == mId);
                    if (merchantadd != null)
                    {
                        // merchantadd.Status = 1;
                        merchantadd.StoreNo = dic["data"]["storeNo"].ToString();
                        merchantadd.OutMchtNo = dic["data"]["outMchtNo"].ToString();
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == mId);
                        if (merchant != null)
                        {
                            merchant.Status = 1;
                        }
                        //商户开通分账
                        JsonData Info = JsonMapper.ToObject(HaoDaHelper.Instance.OpenDivideAccounts(merchantadd.OutMchtNo, merchantadd.StoreNo));
                        //开通失败
                        if (Info["resultCode"].ToString() == "0")
                        {
                            merchantadd.Status = -1;
                            merchantadd.AlipayRemark = Info["errorDesc"].ToString();
                        }
                        //开通成功
                        if (Info["resultCode"].ToString() == "1")
                        {
                            merchantadd.OpenAct = 1;//是否开通分账(1 是 0 否)
                            //分账接收方签约
                            JsonData Infos = JsonMapper.ToObject(HaoDaHelper.Instance.DivideAccountsSign(AppConfig.Haoda.AcctNo, merchantadd.OutMchtNo, merchantadd.StoreNo));
                            //失败
                            if (Infos["resultCode"].ToString() == "0")
                            {
                                merchantadd.AlipayRemark = Infos["errorDesc"].ToString();
                            }
                            //成功
                            else
                            {
                                if (!string.IsNullOrEmpty(merchantadd.ToAcctNo))
                                {
                                    if (!merchantadd.ToAcctNo.Contains("," + AppConfig.Haoda.AcctNo + ","))
                                    {
                                        merchantadd.ToAcctNo += "," + AppConfig.Haoda.AcctNo + ",";
                                    }
                                }
                                else
                                {
                                    merchantadd.ToAcctNo += "," + AppConfig.Haoda.AcctNo + ",";
                                }
                                //绑定微信appid接口
                                JsonData bindInfo = JsonMapper.ToObject(HaoDaHelper.Instance.BindWeChatAppId(merchantadd.OutMchtNo, merchantadd.StoreNo, AppConfig.Haoda.SubAppId));
                                //失败
                                if (bindInfo["resultCode"].ToString() == "0")
                                {
                                    merchantadd.AlipayRemark = bindInfo["errorDesc"].ToString();
                                }
                            }
                        }
                        db.SaveChanges();

                        //开户意愿申请
                        RedisDbconn.Instance.AddList("AlipayForHaoDaQueue",mId);
                        RedisDbconn.Instance.AddList("WeChatForHaoDaQueue",mId);

                    }
                }
                //审核被拒绝
                else if (dic["data"]["code"].ToString() == "3")
                {
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == mId);
                    if (merchantadd != null)
                    {
                        merchantadd.WeChatRemark = dic["data"]["option"].ToString();
                        merchantadd.Status = -1;
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == mId);
                        if (merchant != null)
                        {
                            merchant.Status = -1;
                        }
                        db.SaveChanges();
                    }
                }
                else
                {
                    return "wait";
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒商户进件状态查询异常");
            }
            return "";
        }
    }
}