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 HaoDaExtQueryHelper
{
    public readonly static HaoDaExtQueryHelper Instance = new HaoDaExtQueryHelper();
    private HaoDaExtQueryHelper()
    {
    }

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

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

    public void WeChatAddInfo(int Id, string ApplymentId)
    {
        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.QueryMerchant(ApplymentId);
            LogHelper.Instance.WriteLog(result, "查询微信商户意愿申请状态");
            JsonData jsonObj = JsonMapper.ToObject(result);
            if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT")
            {
                LogHelper.Instance.WriteLog("starts", "查询微信商户意愿申请状态");
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                info.Status = 1;
                merchant.Status = 1;
                info.WeChatRemark = "";
                info.WeChatSignUrl = jsonObj["qrcode_data"].ToString();
                db.SaveChanges();
                // RedisDbconn.Instance.AddList("HaoDaAuthQueryHelper", "{\"MerchantId\":\"" + Id + "\",\"MchtNo\":\"" + info.MchtNo + "\",\"StoreNo\":\"" + info.StoreNo + "\"}");
                LogHelper.Instance.WriteLog("startsend", "查询微信商户意愿申请状态");
            }
            else if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
            {
                LogHelper.Instance.WriteLog("start1", "查询微信商户意愿申请状态");
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                info.Status = -1;
                merchant.Status = -1;
                info.WeChatRemark = jsonObj["reject_reason"].ToString();
                LogHelper.Instance.WriteLog("start1end", "查询微信商户意愿申请状态");
                db.SaveChanges();
            }
            else if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_PASSED")
            {
                LogHelper.Instance.WriteLog("start1", "查询微信商户意愿申请状态");
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                info.Status = 2;
                merchant.Status = 2;
                info.WeChatRemark = "";
                LogHelper.Instance.WriteLog("start1end", "查询微信商户意愿申请状态");
                if (merchant.Latitude == 0)
                {
                    //签约成功调用腾讯地图接口获取地址
                    RedisDbconn.Instance.AddList("GetTencentAddressInfoQueueHd", "{\"MerChantId\":\"" + merchant.Id + "\",\"Address\":\"" + merchant.Areas + merchant.Address + "\"}");
                }
                db.SaveChanges();
            }
            // else
            // {
            //     LogHelper.Instance.WriteLog("starte", "查询微信商户意愿申请状态");
            //     RedisDbconn.Instance.AddList("WeChatResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\",\"ApplymentId\":\"" + ApplymentId + "\"}");
            //     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>("AlipayResultForHaoDaQueue");
            // if (!string.IsNullOrEmpty(content))
            // {
            //     JsonData json = JsonMapper.ToObject(content);
            //     AlipayAddInfo(int.Parse(json["MerchantId"].ToString()), json["order_no"].ToString());
            // }
            // else
            // {
            //     Thread.Sleep(10000);
            // }
            DataTable dt = CustomerSqlConn.dtable("select Id,SeoTitle from MerchantAddInfo where HdStatus=3 and BrandId=0 and `QueryCount`=0 and SeoTitle!='' and SeoTitle is not null", AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                AlipayAddInfo(int.Parse(dr["Id"].ToString()), dr["SeoTitle"].ToString());
            }
            Thread.Sleep(120000);
        }
    }

    public void AlipayAddInfo(int Id, string OrderNo)
    {
        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.AuthOrderQuery(OrderNo);
            JsonData jsonObj = JsonMapper.ToObject(result);
            LogHelper.Instance.WriteLog(result, "查询支付宝商户意愿申请状态");
            if (jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["code"].ToString() == "10000")
            {
                LogHelper.Instance.WriteLog("starts", "查询支付宝商户意愿申请状态");
                string order_status = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["order_status"].ToString();
                LogHelper.Instance.WriteLog(order_status, "查询支付宝商户意愿申请状态");
                if (order_status == "CONTACT_CONFIRM")
                {
                    LogHelper.Instance.WriteLog("start1", "查询支付宝商户意愿申请状态");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.QueryCount = 1;
                    merchant.QueryCount = 1;
                    info.AlipayRemark = "";
                    info.AlipaySignUrl = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["qr_code"].ToString();
                    db.SaveChanges();
                    // RedisDbconn.Instance.AddList("HaoDaAuthQueryHelper", "{\"MerchantId\":\"" + Id + "\",\"MchtNo\":\"" + info.MchtNo + "\",\"StoreNo\":\"" + info.StoreNo + "\"}");
                    LogHelper.Instance.WriteLog("start1end", "查询支付宝商户意愿申请状态");
                }
                else if (order_status == "AUDIT_FREEZE")
                {
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    LogHelper.Instance.WriteLog("start2", "查询支付宝商户意愿申请状态");
                    if (result.Contains("\"qr_code\":"))
                    {
                        info.QueryCount = 1;
                        merchant.QueryCount = 1;
                        info.AlipayRemark = "";
                        info.AlipaySignUrl = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["qr_code"].ToString();
                    }
                    else
                    {
                        info.QueryCount = -1;
                        merchant.QueryCount = -1;
                        info.AlipayRemark = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["msg"].ToString();
                    }
                    LogHelper.Instance.WriteLog("start2end", "查询支付宝商户意愿申请状态");
                    db.SaveChanges();
                }
                else if (order_status == "AUDIT_REJECT")
                {
                    LogHelper.Instance.WriteLog("start2", "查询支付宝商户意愿申请状态");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.QueryCount = -1;
                    merchant.QueryCount = -1;
                    info.AlipayRemark = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["verify_list"][0]["fail_reason"].ToString();
                    LogHelper.Instance.WriteLog("start2end", "查询支付宝商户意愿申请状态");
                    db.SaveChanges();
                }
                else if (order_status == "AUDIT_PASS")
                {
                    LogHelper.Instance.WriteLog("start2", "查询支付宝商户意愿申请状态");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.QueryCount = 2;
                    merchant.QueryCount = 2;
                    info.AlipayRemark = "";
                    LogHelper.Instance.WriteLog("start2end", "查询支付宝商户意愿申请状态");
                    if (merchant.Latitude == 0)
                    {
                        //签约成功调用腾讯地图接口获取地址
                        RedisDbconn.Instance.AddList("GetTencentAddressInfoQueueHd", "{\"MerChantId\":\"" + merchant.Id + "\",\"Address\":\"" + merchant.Areas + merchant.Address + "\"}");
                    }
                    db.SaveChanges();
                }
                // else
                // {
                //     RedisDbconn.Instance.AddList("AlipayResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\",\"order_no\":\"" + OrderNo + "\"}");
                // }
            }
            else
            {
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                info.QueryCount = -1;
                merchant.QueryCount = -1;
                info.AlipayRemark = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["msg"].ToString();
                db.SaveChanges();
            }
            db.Dispose();
        }
        catch (Exception ex)
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "支付宝开户意愿申请异常");
        }
    }
}