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 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>("WeChatSignQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    string result = StartDo(Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantSign>(content));
                    if(result == "wait")
                    {
                        Thread.Sleep(10000);
                        RedisDbconn.Instance.AddList("WeChatSignQueue", content);
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public string StartDo(MerchantSign sign)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                List<MerchantSign> deletes = new List<MerchantSign>();
                Dictionary<string, object> dic = WeChatFunction.Instance.QueryMerchant(sign.BusinessCode);
                if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_SIGNED")
                {
                    string sign_url = dic["sign_url"].ToString();
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                    if (merchantadd != null)
                    {
                        merchantadd.Status = 1;
                        merchantadd.SubMchid = dic["sub_mchid"].ToString();
                        merchantadd.WeChatSignUrl = sign_url;
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchant != null)
                        {
                            merchant.Status = 1;
                        }
                        db.SaveChanges();
                    }
                    return "wait";
                }
                else if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_TO_BE_CONFIRMED")
                {
                    string sign_url = dic["sign_url"].ToString();
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                    if (merchantadd != null)
                    {
                        merchantadd.Status = 1;
                        merchantadd.WeChatSignUrl = sign_url;
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchant != null)
                        {
                            merchant.Status = 1;
                        }
                        db.SaveChanges();
                    }
                    return "wait";
                }
                else if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_FINISHED")
                {
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                    if (merchantadd != null)
                    {
                        merchantadd.Status = 2;
                        merchantadd.SubMchid = dic["sub_mchid"].ToString();
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchant != null)
                        {
                            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);
                            }
                            merchant.Status = 2;
                            if(merchant.SignDate == null)
                            {
                                merchant.SignDate = DateTime.Now;
                            }
                        }
                        db.SaveChanges();
                        if (merchant.Latitude == 0)
                        {
                            //签约成功调用腾讯地图接口获取地址
                            RedisDbconn.Instance.AddList("GetTencentAddressInfoQueue", "{\"MerChantId\":\"" + merchant.Id + "\",\"Address\":\"" + merchant.Areas + merchant.Address + "\"}");
                        }
                    }
                }
                else if (dic["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
                {
                    MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                    if (merchantadd != null)
                    {
                        merchantadd.WeChatRemark = dic["reject_reason"].ToString();
                        merchantadd.Status = -1;
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == sign.MerchantAddInfoId);
                        if (merchant != null)
                        {
                            merchant.Status = -1;
                        }
                        db.SaveChanges();
                        deletes.Add(sign);
                    }
                }
                else
                {
                    return "wait";
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "微信进件回调队列异常");
            }
            return "";
        }
    }
}