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();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
            if (AddInfo.HdStatus >= 1)
            {
                //开户意愿申请
                if (AddInfo.Status == -1 && merchant.Status == -1)
                {
                    AddInfo.WeChatSignUrl = "";
                    AddInfo.WeChatRemark = "";
                    AddInfo.Status = 0;
                    RedisDbconn.Instance.AddList("WeChatForHaoDaQueue", AddInfo.Id);
                }
                if (AddInfo.QueryCount == -1 && merchant.QueryCount == -1)
                {
                    AddInfo.AlipaySignUrl = "";
                    AddInfo.AlipayRemark = "";
                    AddInfo.QueryCount = 0;
                    RedisDbconn.Instance.AddList("AlipayForHaoDaQueue", AddInfo.Id);
                }
                db.SaveChanges();
            }
            else
            {
                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;
                    }
                    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();

                    if (AddInfo.Status <= 0)
                    {
                        //好哒新建商户
                        string result = HaoDaHelper.Instance.AddNewMerchant(AddNewMerchantSetUtil.SetValue(AddInfo), AddInfo.BrandId);
                        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;
                            AddInfo.HdStatus = 0; //0 待审核 1 已通过 2 已开通分账 3 已添加接收方
                            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;
                            string errorDesc = jsonObj["errorDesc"].ToString();
                            if (errorDesc.Contains("租赁协议") && errorDesc.Contains("水电煤") && errorDesc.Contains("门头合影") && errorDesc.Contains("下载地址"))
                            {
                                errorDesc = "门头不一致，需上传名称不一致说明函";
                            }
                            AddInfo.WeChatRemark = errorDesc;
                            // if (string.IsNullOrEmpty(AddInfo.MchtNo))
                            // {
                            //     if (jsonObj.ToJson().Contains("mchtNo"))
                            //     {
                            //         AddInfo.MchtNo = jsonObj["data"]["mchtNo"].ToString();
                            //     }
                            // }
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }
    }
}