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

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

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

    private void StartWeChatDo()
    {
        while (true)
        {
            // string content = RedisDbconn.Instance.RPop<string>("WeChatAuthResultForHaoDaQueue");
            // if (!string.IsNullOrEmpty(content))
            // {
            //     JsonData json = JsonMapper.ToObject(content);
            //     WeChatAddInfo(int.Parse(json["MerchantId"].ToString()));
            // }
            // else
            // {
            //     Thread.Sleep(10000);
            // }
            DataTable dt = CustomerSqlConn.dtable("select Id from MerchantAddInfo where HdStatus=3 and BrandId=0 and `Status`=1 and WeChatMerchantId!='' and WeChatMerchantId is not null", AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                WeChatAddInfo(int.Parse(dr["Id"].ToString()));
                Thread.Sleep(1000);
            }
            Thread.Sleep(120000);
        }
    }

    public void WeChatAddInfo(int Id)
    {
        try
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "获取微信商户开户意愿确认状态");
            LogHelper.Instance.WriteLog("start", "获取微信商户开户意愿确认状态");
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
            string result = WeChatFunctionForHD.Instance.QueryAuthMerchant(info.WeChatMerchantId);
            LogHelper.Instance.WriteLog(result, "获取微信商户开户意愿确认状态");
            JsonData jsonObj = JsonMapper.ToObject(result);
            if (result.Contains("authorize_state"))
            {
                if (jsonObj["authorize_state"].ToString() == "AUTHORIZE_STATE_AUTHORIZED")
                {
                    LogHelper.Instance.WriteLog("starts", "获取微信商户开户意愿确认状态");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    if(merchant.Status < 2 && merchant.QueryCount < 2)
                    {
                        RedisDbconn.Instance.AddList("MpMerchantActQueue", "{\"userId\":\"" + merchant.UserId + "\",\"statDate\":\"" + DateTime.Now.ToString("yyyyMMdd") + "\",\"statMonth\":\"" + DateTime.Now.ToString("yyyyMM") + "\"}");
                        Utils.Instance.SendActData(merchant);
                    }
                    info.Status = 2;
                    merchant.Status = 2;
                    db.SaveChanges();
                    if (merchant.Latitude == 0)
                    {
                        //签约成功调用腾讯地图接口获取地址
                        RedisDbconn.Instance.AddList("GetTencentAddressInfoQueueHd", "{\"MerChantId\":\"" + merchant.Id + "\",\"Address\":\"" + merchant.Areas + merchant.Address + "\"}");
                    }
                    LogHelper.Instance.WriteLog("startsend", "获取微信商户开户意愿确认状态");
                }
            }
            // else
            // {
            //     LogHelper.Instance.WriteLog("starte", "获取微信商户开户意愿确认状态");
            //     RedisDbconn.Instance.AddList("WeChatAuthResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\"}");
            //     LogHelper.Instance.WriteLog("start2end", "获取微信商户开户意愿确认状态");
            // }
            db.Dispose();
        }
        catch (Exception ex)
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "获取微信商户开户意愿确认状态异常");
        }
    }



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

    private void StartAlipayDo()
    {
        while (true)
        {
            // string content = RedisDbconn.Instance.RPop<string>("AlipayAuthResultForHaoDaQueue");
            // if (!string.IsNullOrEmpty(content))
            // {
            //     JsonData json = JsonMapper.ToObject(content);
            //     AlipayAddInfo(int.Parse(json["MerchantId"].ToString()));
            // }
            // else
            // {
            //     Thread.Sleep(10000);
            // }
            DataTable dt = CustomerSqlConn.dtable("select Id from MerchantAddInfo where HdStatus=3 and BrandId=0 and `QueryCount`=1 and AliMerchantId!='' and AliMerchantId is not null", AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                AlipayAddInfo(int.Parse(dr["Id"].ToString()));
                Thread.Sleep(1000);
            }
            Thread.Sleep(120000);
        }
    }

    public void AlipayAddInfo(int Id)
    {
        try
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "获取支付宝商家认证状态");
            LogHelper.Instance.WriteLog("start", "获取支付宝商家认证状态");
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
            string result = AlipayFunctionForHD.Instance.AuthOrderAuthQuery(info.AliMerchantId);
            JsonData jsonObj = JsonMapper.ToObject(result);
            LogHelper.Instance.WriteLog(result, "获取支付宝商家认证状态");
            if (jsonObj["alipay_merchant_indirect_smidbind_query_response"]["code"].ToString() == "10000")
            {
                LogHelper.Instance.WriteLog("starts", "获取支付宝商家认证状态");
                string order_status = jsonObj["alipay_merchant_indirect_smidbind_query_response"]["check_result"].ToString();
                LogHelper.Instance.WriteLog(order_status, "获取支付宝商家认证状态");
                if (order_status == "AUTHORIZED")
                {
                    LogHelper.Instance.WriteLog("start1", "获取支付宝商家认证状态");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    if(merchant.Status < 2 && merchant.QueryCount < 2)
                    {
                        RedisDbconn.Instance.AddList("MpMerchantActQueue", "{\"userId\":\"" + merchant.UserId + "\",\"statDate\":\"" + DateTime.Now.ToString("yyyyMMdd") + "\",\"statMonth\":\"" + DateTime.Now.ToString("yyyyMM") + "\"}");
                        Utils.Instance.SendActData(merchant);
                    }
                    info.QueryCount = 2;
                    merchant.QueryCount = 2;
                    db.SaveChanges();
                    if (merchant.Latitude == 0)
                    {
                        //签约成功调用腾讯地图接口获取地址
                        RedisDbconn.Instance.AddList("GetTencentAddressInfoQueueHd", "{\"MerChantId\":\"" + merchant.Id + "\",\"Address\":\"" + merchant.Areas + merchant.Address + "\"}");
                    }
                    LogHelper.Instance.WriteLog("start1end", "获取支付宝商家认证状态");
                }
                // else
                // {
                //     RedisDbconn.Instance.AddList("AlipayAuthResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\"}");
                // }
            }
            db.Dispose();
        }
        catch (Exception ex)
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "获取支付宝商家认证状态异常");
        }
    }
}