using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using MySystem.PxcModels;
using Library;
using LitJson;

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

        public void Start(string MerchantIdString, int Kind = 0)
        {
            try
            {
                int MerchantId = int.Parse(function.CheckInt(MerchantIdString));
                PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                PxcModels.MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
                PxcModels.MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
                if (AddInfo != null && merchant != null)
                {
                    string BusinessCode = AddInfo.BusinessCode;
                    if (string.IsNullOrEmpty(BusinessCode))
                    { 
                        BusinessCode = "KXS" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(5);
                        AddInfo.BusinessCode = BusinessCode;
                    }
                    merchant.LoginPwd = function.MD532(AddInfo.MobilePhone.Substring(5));
                    PxcModels.MerchantParamSet query = db.MerchantParamSet.FirstOrDefault(m => m.Id == MerchantId);
                    if (query == null)
                    {
                        query = new PxcModels.MerchantParamSet();
                        query.IsAll = 1;
                        db.MerchantParamSet.Add(query);
                        db.SaveChanges();
                        RedisDbconn.Instance.Set("MerchantParamSet:" + MerchantId, query);
                    }
                    PxcModels.MerchantForMobile merchantForMobile = db.MerchantForMobile.FirstOrDefault(m => m.Mobile == AddInfo.MobilePhone);
                    if (merchantForMobile == null)
                    {
                        merchantForMobile = db.MerchantForMobile.Add(new PxcModels.MerchantForMobile()
                        {
                            Mobile = AddInfo.MobilePhone,
                        }).Entity;
                        db.SaveChanges();
                    }
                    merchantForMobile.MerchantId = MerchantId;
                    db.SaveChanges();
                    List<MerchantInfo> merchants = RedisDbconn.Instance.GetList<MerchantInfo>("MerchantList:" + merchant.UserId, 1, 10000000);

                    //微信
                    if (Kind == 0 || Kind == 2)
                    {
                        string result = new WeChatFunction().MerchantCreate(AddInfo, merchant);
                        if (result.Contains("\"applyment_id\":"))
                        {
                            JsonData jsonObj = JsonMapper.ToObject(result);
                            AddInfo.ApplymentId = jsonObj["applyment_id"].ToString();
                            AddInfo.Status = 0;
                            db.SaveChanges();
                            List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("MerchantSignList", 1, 10000000);
                            bool op = signs.Any(m => m.BusinessCode == BusinessCode);
                            if (!op)
                            {
                                RedisDbconn.Instance.AddList("WeChatSignList", new MerchantSign()
                                {
                                    BusinessCode = BusinessCode,
                                    MerchantAddInfoId = MerchantId,
                                    Status = ""
                                });
                            }
                            signs.Clear();
                            if (merchants.Any(m => m.Id == merchant.Id) == false)
                            {
                                RedisDbconn.Instance.AddList("MerchantList:" + merchant.UserId, merchant);
                            }
                            else
                            {
                                PxcModels.MerchantAddInfo merchantAddInfo = RedisDbconn.Instance.Get<PxcModels.MerchantAddInfo>("MerchantAddInfo:" + MerchantId);
                                if (merchantAddInfo != null)
                                {
                                    merchantAddInfo.ApplymentId = AddInfo.ApplymentId;
                                    merchantAddInfo.Status = AddInfo.Status;
                                    RedisDbconn.Instance.Set("MerchantAddInfo:" + MerchantId, merchantAddInfo);
                                }
                            }
                        }
                        else if (result.Contains("\"message\":"))
                        {
                            JsonData jsonObj = JsonMapper.ToObject(result);
                            AddInfo.Status = -1;
                            merchant.Status = -1;
                            string Season = function.CheckNull(AddInfo.SeoDescription);
                            if (string.IsNullOrEmpty(Season))
                            {
                                Season = "WeChat:" + jsonObj["message"].ToString() + ";";
                            }
                            else
                            {
                                Season = Regex.Replace(Season, "WeChat:.*?;", "");
                                Season += "WeChat:" + jsonObj["message"].ToString() + ";";
                            }
                            AddInfo.SeoDescription = Season;
                            db.SaveChanges();
                            if (merchants.Any(m => m.Id == merchant.Id) == false)
                            {
                                RedisDbconn.Instance.AddList("MerchantList:" + merchant.UserId, merchant);
                            }
                            else
                            {
                                PxcModels.MerchantAddInfo merchantAddInfo = RedisDbconn.Instance.Get<PxcModels.MerchantAddInfo>("MerchantAddInfo:" + MerchantId);
                                if (merchantAddInfo != null)
                                {
                                    merchantAddInfo.SeoDescription = AddInfo.SeoDescription;
                                    merchantAddInfo.Status = AddInfo.Status;
                                    RedisDbconn.Instance.Set("MerchantAddInfo:" + MerchantId, merchantAddInfo);
                                }
                            }
                            List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("WeChatSignList", 1, 10000000);
                            MerchantSign sign = signs.FirstOrDefault(m => m.BusinessCode == BusinessCode);
                            if (sign != null)
                            {
                                signs.Remove(sign);
                                RedisDbconn.Instance.Clear("WeChatSignList");
                                RedisDbconn.Instance.AddList("WeChatSignList", signs.ToArray());
                            }
                        }
                    }

                    //支付宝
                    if (Kind == 0 || Kind == 1)
                    {
                        bool checkAlipay = true;
                        string content = new AlipayFunction().GetBatchNo(AddInfo.CreateMan, AddInfo.IdCardName, AddInfo.MobilePhone, AddInfo.ContactEmail);
                        JsonData json = JsonMapper.ToObject(content);
                        if (json["alipay_open_agent_create_response"]["code"].ToString() == "10000")
                        {
                            string batch_no = json["alipay_open_agent_create_response"]["batch_no"].ToString();
                            string Qualifications = AddInfo.Qualifications;
                            if (!string.IsNullOrEmpty(Qualifications))
                            {
                                Qualifications = function.getPath("/bsserver_com" + Qualifications);
                            }
                            content = new AlipayFunction().CommonSign(batch_no, AddInfo.UpdateMan, AddInfo.LicenseNumber, function.getPath("/bsserver_com" + AddInfo.LicenseCopy), Qualifications);
                            json = JsonMapper.ToObject(content);
                            if (json["alipay_open_agent_common_sign_response"]["code"].ToString() == "10000")
                            {
                                content = new AlipayFunction().CommonSignConfirm(batch_no);
                                json = JsonMapper.ToObject(content);
                                if (json["alipay_open_agent_commonsign_confirm_response"]["code"].ToString() == "10000")
                                {
                                    AddInfo.QueryCount = 0;
                                    AddInfo.SeoTitle = batch_no;
                                    db.SaveChanges();
                                    List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("MerchantSignList", 1, 10000000);
                                    bool op = signs.Any(m => m.BusinessCode == batch_no);
                                    if (!op)
                                    {
                                        RedisDbconn.Instance.AddList("AlipaySignList", new MerchantSign()
                                        {
                                            BusinessCode = batch_no,
                                            MerchantAddInfoId = MerchantId,
                                            Status = ""
                                        });
                                    }
                                    signs.Clear();
                                    if (merchants.Any(m => m.Id == merchant.Id) == false)
                                    {
                                        RedisDbconn.Instance.AddList("MerchantList:" + merchant.UserId, merchant);
                                    }
                                }
                                else
                                {
                                    checkAlipay = false;
                                }
                            }
                            else
                            {
                                checkAlipay = false;
                            }
                        }
                        else
                        {
                            checkAlipay = false;
                        }
                        if (!checkAlipay)
                        {
                            JsonData jsonObj = JsonMapper.ToObject(content);
                            AddInfo.QueryCount = -1;
                            merchant.Status = -1;
                            string Season = function.CheckNull(AddInfo.SeoDescription);
                            if (string.IsNullOrEmpty(Season))
                            {
                                Season = "Alipay:" + jsonObj["alipay_open_agent_create_response"]["sub_msg"].ToString() + ";";
                            }
                            else
                            {
                                Season = Regex.Replace(Season, "Alipay:.*?;", "");
                                Season = "Alipay:" + jsonObj["alipay_open_agent_create_response"]["sub_msg"].ToString() + ";" + Season;
                            }
                            AddInfo.SeoDescription = Season;
                            db.SaveChanges();
                            if (merchants.Any(m => m.Id == merchant.Id) == false)
                            {
                                RedisDbconn.Instance.AddList("MerchantList:" + merchant.UserId, merchant);
                            }
                            else
                            {
                                PxcModels.MerchantAddInfo merchantAddInfo = RedisDbconn.Instance.Get<PxcModels.MerchantAddInfo>("MerchantAddInfo:" + MerchantId);
                                if (merchantAddInfo != null)
                                {
                                    merchantAddInfo.SeoDescription = AddInfo.SeoDescription;
                                    merchantAddInfo.QueryCount = AddInfo.QueryCount;
                                    RedisDbconn.Instance.Set("MerchantAddInfo:" + MerchantId, merchantAddInfo);
                                }
                            }
                            List<MerchantSign> signs = RedisDbconn.Instance.GetList<MerchantSign>("AlipaySignList", 1, 10000000);
                            MerchantSign sign = signs.FirstOrDefault(m => m.BusinessCode == BusinessCode);
                            if (sign != null)
                            {
                                signs.Remove(sign);
                                RedisDbconn.Instance.Clear("AlipaySignList");
                                RedisDbconn.Instance.AddList("AlipaySignList", signs.ToArray());
                            }
                        }
                    }
                }
                db.Dispose();
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
            }
        }
    }
}