using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.Hosting;
using MySystem;
using MySystem.Models;
using LitJson;
using Library;
using MySystem.Models.Main;

public class HaoDaAuthQueryHelper
{
    public readonly static HaoDaAuthQueryHelper Instance = new HaoDaAuthQueryHelper();
    private HaoDaAuthQueryHelper()
    {
    }

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

    private void StartDo()
    {
        while (true)
        {
            string content = RedisDbconn.Instance.RPop<string>("HaoDaAuthQueryHelper");
            if (!string.IsNullOrEmpty(content))
            {
                JsonData json = JsonMapper.ToObject(content);
                QueryAuthStatus(json["MerchantId"].ToString(), json["MchtNo"].ToString(), json["StoreNo"].ToString());
            }
            else
            {
                Thread.Sleep(10000);
            }
        }
    }

    public void QueryAuthStatus(string MerchantId, string MchtNo, string StoreNo)
    {
        try
        {
            var Id = int.Parse(MerchantId);
            var jsonObj = JsonMapper.ToObject(HaoDaHelper.Instance.QueryAuthStatus(MchtNo, StoreNo));
            //成功(已认证)
            if (jsonObj["resultCode"].ToString() == "1")
            {
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                var wxcheck = jsonObj["wechatVerifyState"].ToString();
                var alicheck = jsonObj["aliVerifyState"].ToString();
                if (wxcheck == "1")
                {
                    info.Status = 2;
                    info.WeChatMerchantId = jsonObj["wechatMerchantId"].ToString();
                    merchant.Status = 2;
                    info.WeChatRemark = "";
                }
                if (alicheck == "1")
                {
                    info.QueryCount = 2;
                    info.AliMerchantId = jsonObj["aliMerchantId"].ToString();
                    merchant.QueryCount = 2;
                    info.AlipayRemark = "";
                }
                if (wxcheck != "1" || alicheck != "1")
                {
                    RedisDbconn.Instance.AddList("HaoDaAuthQueryHelper", "{\"MerchantId\":\"" + MerchantId + "\",\"MchtNo\":\"" + info.OutMchtNo + "\",\"StoreNo\":\"" + info.StoreNo + "\"}");
                }

                db.SaveChanges();
            }
        }
        catch (Exception ex)
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "查询实名认证状态异常");
        }
    }
}