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

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

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

        public void StartListen()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("MerchantConfirmHdQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        JsonData jsonObj = JsonMapper.ToObject(content);
                        int MerchantId = int.Parse(jsonObj["MerchantId"].ToString());
                        StartDo(MerchantId);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒商户进件异常");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void StartDo(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            Models.Main1.WebCMSEntities db1 = new Models.Main1.WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
            if (AddInfo != null && merchant != null)
            {
                string BusinessCode = AddInfo.BusinessCode;
                if (string.IsNullOrEmpty(BusinessCode))
                {
                    BusinessCode = "LKB" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(5);
                    AddInfo.BusinessCode = BusinessCode;
                }
                string pwd = AddInfo.MobilePhone.Substring(5);
                merchant.LoginPwd = function.MD532(pwd);
                MerchantParamSet query = db.MerchantParamSet.FirstOrDefault(m => m.Id == MerchantId);
                if (query == null)
                {
                    query = new MerchantParamSet();
                    query.IsAll = 1;
                    db.MerchantParamSet.Add(query);
                    db.SaveChanges();
                }
                MerchantForMobile merchantForMobile = db.MerchantForMobile.FirstOrDefault(m => m.Mobile == AddInfo.MobilePhone);
                if (merchantForMobile == null)
                {
                    merchantForMobile = db.MerchantForMobile.Add(new MerchantForMobile()
                    {
                        Mobile = AddInfo.MobilePhone,
                    }).Entity;
                    db.SaveChanges();
                }
                merchantForMobile.MerchantId = MerchantId;
                db.SaveChanges();
                Models.Main1.MerchantLoginInfo info = db1.MerchantLoginInfo.FirstOrDefault(m => m.LoginMobile == AddInfo.MobilePhone);
                if (info == null)
                {
                    info = db1.MerchantLoginInfo.Add(new Models.Main1.MerchantLoginInfo()
                    {
                        LoginMobile = AddInfo.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 == MerchantId && m.Kind == 2);
                if (infolink == null)
                {
                    infolink = db1.MerchantAccountLinkInfo.Add(new Models.Main1.MerchantAccountLinkInfo()
                    {
                        LoginId = info.Id,
                        MerchantId = MerchantId,
                        Kind = 2,
                    }).Entity;
                    db1.SaveChanges();
                }
                if (AddInfo.Status <= 0)
                {
                    //好哒新建商户
                    string result = HaoDaHelper.Instance.AddNewMerchant(AddNewMerchantSetUtil.SetValue(AddInfo));
                    JsonData jsonObj = JsonMapper.ToObject(result);
                    //创建成功
                    if (jsonObj["resultCode"].ToString() == "1")
                    {
                        AddInfo.WeChatRemark = "";
                        if (string.IsNullOrEmpty(AddInfo.MchtNo))
                        {
                            AddInfo.MchtNo = jsonObj["data"]["mchtNo"].ToString();
                        }
                        AddInfo.Status = 0;
                        merchant.Status = 0;
                        db.SaveChanges();
                        QueryMerchantStatus queryMerchantStatus = new QueryMerchantStatus();
                        queryMerchantStatus.MerchantId = MerchantId.ToString();
                        queryMerchantStatus.MerchantNo = AddInfo.MchtNo;
                        RedisDbconn.Instance.AddList("WeChatSignHdQueue", queryMerchantStatus);
                    }
                    //创建失败
                    else
                    {
                        AddInfo.Status = -1;
                        merchant.Status = -1;
                        AddInfo.WeChatRemark = jsonObj["errorDesc"].ToString();
                        if (string.IsNullOrEmpty(AddInfo.MchtNo))
                        {
                            if (jsonObj.ToString().Contains("mchtNo"))
                            {
                                AddInfo.MchtNo = jsonObj["data"]["mchtNo"].ToString();
                            }
                        }
                        db.SaveChanges();
                    }
                }
            }
            db.Dispose();
            db1.Dispose();
        }
    }
}