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

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

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

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

        public string StartDo(MerchantSign sign)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                string content = AlipayFunction.Instance.QuerySignStatus(sign.BusinessCode);
                JsonData dic = JsonMapper.ToObject(content);
                if (dic["alipay_open_agent_order_query_response"]["code"].ToString() == "10000")
                {
                    // MERCHANT_INFO_HOLD=暂存，提交事务出现业务校验异常时，会暂存申请单信息，可以调用业务接口修正参数，并重新提交
                    // MERCHANT_AUDITING=审核中，申请信息正在人工审核中
                    // MERCHANT_CONFIRM=待商户确认，申请信息审核通过，等待联系人确认签约或授权
                    // MERCHANT_CONFIRM_SUCCESS=商户确认成功，商户同意签约或授权
                    // MERCHANT_CONFIRM_TIME_OUT=商户超时未确认，如果商户受到确认信息15天内未确认，则需要重新提交申请信息
                    // MERCHANT_APPLY_ORDER_CANCELED=审核失败或商户拒绝，申请信息审核被驳回，或者商户选择拒绝签约或授权
                    if (dic["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_CONFIRM")
                    {
                        string sign_url = dic["alipay_open_agent_order_query_response"]["confirm_url"].ToString();
                        MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchantadd != null)
                        {
                            merchantadd.QueryCount = 1;
                            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                            if (merchant != null)
                            {
                                merchant.QueryCount = 1;
                            }
                            string confirm_url = dic["alipay_open_agent_order_query_response"]["confirm_url"].ToString();
                            string fileName = function.MD5_16(Guid.NewGuid().ToString());
                            function.CreateQRCode2(sign_url, fileName, "/" + confirm_url);
                            merchantadd.AlipaySignUrl = confirm_url;
                            merchantadd.AlipayPid = dic["alipay_open_agent_order_query_response"]["merchant_pid"].ToString();
                            db.SaveChanges();
                        }
                        return "wait";
                    }
                    else if (dic["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_CONFIRM_SUCCESS")
                    {
                        //{"alipay_open_agent_order_query_response":{"code":"10000","msg":"Success","order_no":"20230704034000100000030319581766","product_agent_status_infos":[{"product_code":"FACE_TO_FACE_PAYMENT","product_name":"当面付","status":"EFFECTED"}],"order_status":"MERCHANT_CONFIRM_SUCCESS","merchant_pid":"2088641525908640"},"sign":"UyyrAf+Q+2jd5VVsaKUyWTMW8gFadUWWQIoYSTLzYFx0NOetjbN4XE9xq2kYvoJIYgQQOhohDKyAZZ7FOnOz9J849AXaqW1VYfVY9FSDvnSCdcUrAdyXGQEp7TcbnMtP5RTXZO+VCKRpvvUc/LVdXMPMetUbzhyaahQf/T512aQNuYFjxH5QfMdzGDwevt47iNoANITwXqns1A+ETBCuxHlx2Ps7WXpPxzqvFYK9CBD5MQCaq7IrDityzAUcMFiMjE3LlXb1zgg6PlsHnJBZm0Zde1PYzKZcHKnx2bxWl2upwpC3uj6drxzkGqzcZ4D21cTlndm8GIRLo2XHpd79Hw=="}
                        MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchantadd != null)
                        {
                            merchantadd.AlipayPid = dic["alipay_open_agent_order_query_response"]["merchant_pid"].ToString();
                            if(content.Contains("restrict_infos"))
                            {
                                if(dic["alipay_open_agent_order_query_response"]["restrict_infos"].Count > 0)
                                {
                                    merchantadd.QueryCount = -1;
                                    merchantadd.AlipayRemark = dic["alipay_open_agent_order_query_response"]["restrict_infos"][0]["restrict_reason"].ToString();
                                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                                    if (merchant != null)
                                    {
                                        merchant.QueryCount = -1;
                                    }
                                }
                                else
                                {
                                    merchantadd.QueryCount = 2;
                                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                                    if (merchant != null)
                                    {
                                        merchant.QueryCount = 2;
                                    }
                                }
                            }
                            else
                            {
                                merchantadd.QueryCount = 2;
                                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                                if (merchant != null)
                                {
                                    merchant.QueryCount = 2;
                                }
                            }
                            db.SaveChanges();
                        }
                    }
                    else if (dic["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_APPLY_ORDER_CANCELED")
                    { 
                        MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchantadd != null)
                        {
                            string reason = "";
                            if(dic["alipay_open_agent_order_query_response"]["restrict_infos"].Count > 0)
                            {
                                reason = dic["alipay_open_agent_order_query_response"]["restrict_infos"][0]["restrict_reason"].ToString();
                            }
                            merchantadd.AlipayRemark = reason;
                            merchantadd.QueryCount = -1;
                            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                            if (merchant != null)
                            {
                                merchant.QueryCount = -1;
                            }
                            db.SaveChanges();
                        }
                    }
                    else if (dic["alipay_open_agent_order_query_response"]["order_status"].ToString() == "MERCHANT_AUDITING")
                    { 
                        return "wait";
                    }
                }
                else
                {
                    if(dic["alipay_open_agent_order_query_response"]["code"].ToString() == "40004" && dic["alipay_open_agent_order_query_response"]["sub_msg"].ToString() == "系统繁忙")
                    {
                        return "wait";
                    }
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                    if (merchantadd != null)
                    {
                        merchantadd.QueryCount = -1;
                        merchantadd.AlipayRemark = dic["alipay_open_agent_order_query_response"]["sub_msg"].ToString();
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchant != null)
                        {
                            merchant.QueryCount = -1;
                        }
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "支付宝签约审核队列异常");
            }
            return "";
        }
    }
}