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

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

        public void StartListen()
        {
            while (true)
            {
                string CheckDate = DateTime.Now.AddMinutes(-15).ToString("yyyy-MM-dd HH:mm:ss");
                DataTable dt = CustomerSqlConn.dtable("select Id from MerchantAddInfo where HdStatus=3 and HdBindWeChat=0 and BrandId=0 and HdPassDate<'" + CheckDate + "' and OutMchtNo!='' and OutMchtNo is not null", AppConfig.Base.SqlConnStr);
                foreach (DataRow dr in dt.Rows)
                {
                    StartDo(int.Parse(function.CheckInt(dr["Id"].ToString())));
                }
                Thread.Sleep(10000);
            }
        }

        public string StartDo(int MerchantId)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
                if (merchantadd != null)
                {
                    //绑定微信appid接口
                    JsonData bindInfo = JsonMapper.ToObject(HaoDaHelper.Instance.BindWeChatAppId(merchantadd.OutMchtNo, merchantadd.StoreNo, AppConfig.Haoda.SubAppId, merchantadd.BrandId));
                    //失败
                    if (bindInfo["resultCode"].ToString() == "0")
                    {
                        merchantadd.WeChatRemark = bindInfo["errorDesc"].ToString();
                    }
                    else
                    {
                        merchantadd.HdBindWeChat = 1;
                    }
                    db.SaveChanges();
                }
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒商户进件状态查询异常");
            }
            return "";
        }
    }
}