using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
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);
                // }
                DataTable dt = CustomerSqlConn.dtable("select Id,MchtNo from MerchantAddInfo where Id in (select Id from MerchantInfo where Sort=1 and `Status`=0 and QueryCount=0) and MchtNo!='' and MchtNo is not null", AppConfig.Base.SqlConnStr);
                foreach (DataRow dr in dt.Rows)
                {
                    StartDo(new QueryMerchantStatus()
                    {
                        MerchantId = dr["Id"].ToString(),
                        MerchantNo = dr["MchtNo"].ToString(),
                    });
                    Thread.Sleep(10000);
                }
                if(Library.ConfigurationManager.EnvironmentFlag == 2)
                {
                    Thread.Sleep(300000);
                }
                else
                {
                    Thread.Sleep(3600000);
                }
            }
        }

        public string StartDo(QueryMerchantStatus query)
        {
            try
            {
                var mId = int.Parse(query.MerchantId);
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == mId);

                var BrhCode = HaodaUnionParam.BrhCode;
                if (merchantadd.BrandId == 1) BrhCode = HaodaParam.BrhCode;

                //查询商户审核状态
                var returnInfo = HaoDaHelper.Instance.QueryMerchantStatus(BrhCode, query.MerchantNo, merchantadd.BrandId);
                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()))
                {
                    //查询商户是否存在
                    if (merchantadd != null)
                    {
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == mId);
                        merchantadd.StoreNo = dic["data"]["storeNo"].ToString();
                        merchantadd.HdStatus = 1; //0 待审核 1 已通过 2 已开通分账 3 已添加接收方
                        merchantadd.OutMchtNo = dic["data"]["outMchtNo"].ToString();
                        if (merchantadd.BrandId == 1)
                        {
                            merchantadd.Status = 2;
                            merchantadd.QueryCount = 2;

                            merchant.Status = 2;
                            merchant.QueryCount = 2;
                        }
                        else
                        {
                            if (merchant != null)
                            {
                                merchant.Status = 1;
                            }
                            //商户开通分账
                            JsonData Info = JsonMapper.ToObject(HaoDaHelper.Instance.OpenDivideAccounts(merchantadd.OutMchtNo, merchantadd.StoreNo, merchantadd.BrandId));
                            //开通失败
                            if (Info["resultCode"].ToString() == "0")
                            {
                                merchantadd.Status = -1;
                                merchantadd.WeChatRemark = Info["errorDesc"].ToString();
                            }
                            //开通成功
                            if (Info["resultCode"].ToString() == "1")
                            {
                                merchantadd.OpenAct = 1;//是否开通分账(1 是 0 否)
                                merchantadd.HdStatus = 2; //0 待审核 1 已通过 2 已开通分账 3 已添加接收方
                                                          //分账接收方签约
                                JsonData Infos = JsonMapper.ToObject(HaoDaHelper.Instance.DivideAccountsSign(AppConfig.Haoda.AcctNo, merchantadd.OutMchtNo, merchantadd.StoreNo, merchantadd.BrandId));
                                //失败
                                if (Infos["resultCode"].ToString() == "0")
                                {
                                    merchantadd.WeChatRemark = Infos["errorDesc"].ToString();
                                }
                                //成功
                                else
                                {
                                    merchantadd.HdStatus = 3; //0 待审核 1 已通过 2 已开通分账 3 已添加接收方
                                    if (!string.IsNullOrEmpty(merchantadd.ToAcctNo))
                                    {
                                        if (!merchantadd.ToAcctNo.Contains("," + AppConfig.Haoda.AcctNo + ","))
                                        {
                                            merchantadd.ToAcctNo += "," + AppConfig.Haoda.AcctNo + ",";
                                        }
                                    }
                                    else
                                    {
                                        merchantadd.ToAcctNo += "," + AppConfig.Haoda.AcctNo + ",";
                                    }
                                    merchantadd.HdPassDate = DateTime.Now;
                                }
                            }

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

                        //创客账号
                        Models.Main1.WebCMSEntities db1 = new Models.Main1.WebCMSEntities();
                        string pwd = merchantadd.MobilePhone.Substring(5);
                        merchant.LoginPwd = function.MD532(pwd);
                        Models.Main1.MerchantLoginInfo info = db1.MerchantLoginInfo.FirstOrDefault(m => m.LoginMobile == merchantadd.MobilePhone);
                        if (info == null)
                        {
                            info = db1.MerchantLoginInfo.Add(new Models.Main1.MerchantLoginInfo()
                            {
                                LoginMobile = merchantadd.MobilePhone,
                            }).Entity;
                            db1.SaveChanges();
                        }
                        info.LoginPwd = function.MD532(pwd);
                        db1.SaveChanges();
                        Models.Main1.MerchantAccountLinkInfo infolink = db1.MerchantAccountLinkInfo.FirstOrDefault(m => m.LoginId == info.Id && m.MerchantId == merchantadd.Id && m.Kind == 2);
                        if (infolink == null)
                        {
                            infolink = db1.MerchantAccountLinkInfo.Add(new Models.Main1.MerchantAccountLinkInfo()
                            {
                                LoginId = info.Id,
                                MerchantId = merchantadd.Id,
                                Kind = 2,
                            }).Entity;
                            db1.SaveChanges();
                        }
                        db1.Dispose();

                        if (merchantadd.BrandId == 1 && !string.IsNullOrEmpty(merchantadd.CybMakerCode))
                        {
                            SortedList<string, string> obj = new SortedList<string, string>();
                            obj.Add("bind_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            obj.Add("merch_no", merchantadd.MchtNo);
                            obj.Add("name", merchantadd.CertMerchantName);
                            string IdCardNumber = merchantadd.IdCardNumber;
                            if(!string.IsNullOrEmpty(IdCardNumber))
                            {
                                IdCardNumber = IdCardNumber.Substring(0, 6) + "**********" + IdCardNumber.Substring(IdCardNumber.Length - 4);
                            }
                            obj.Add("supplement_info", IdCardNumber);
                            obj.Add("mobile", merchantadd.MobilePhone);
                            obj.Add("maker_code", merchantadd.CybMakerCode);
                            PushHelper.Instance.Do(obj);
                        }
                    }
                }
                //审核被拒绝
                else if (dic["data"]["code"].ToString() == "3")
                {
                    if (merchantadd != null)
                    {
                        string WeChatRemark = dic["data"]["option"].ToString();
                        if (WeChatRemark.Contains("租赁协议") && WeChatRemark.Contains("水电煤") && WeChatRemark.Contains("门头合影") && WeChatRemark.Contains("下载地址"))
                        {
                            WeChatRemark = "门头不一致需补充 “名称不一致说明函”";
                        }
                        if (WeChatRemark.Contains("盒伙人在门头合影"))
                        {
                            WeChatRemark = "门头不一致需补充 “名称不一致说明函”";
                        }
                        if (WeChatRemark.Contains("不支持跨商户进件"))
                        {
                            WeChatRemark = "该商户已注册，错误指令【404】";
                        }
                        merchantadd.WeChatRemark = WeChatRemark;
                        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 "";
        }
    }
}