using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.SpModels;
using Library;
using LitJson;
using System.Threading;

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

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

        public void StartDo()
        {
            while (true)
            {
                try
                {
                    WebCMSEntities spdb = new WebCMSEntities();
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    DateTime start = DateTime.Now.AddDays(-5);
                    int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/MerchantsId.txt")));
                    var Mers = spdb.Merchants.Where(m => m.Id >= StartId && m.CreateTime >= start && m.Status == 1).OrderByDescending(m => m.Id).ToList();
                    foreach (var Mer in Mers)
                    {
                        var tran = db.Database.BeginTransaction();
                        try
                        {
                            PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == Mer.SnNo) ?? new PxcModels.PosMachinesTwo();
                            if (pos.BindingState == 1 && Mer.Field2 != "解绑")
                            {
                                PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new PxcModels.Users();
                                int TopUserId = 0;
                                if (!string.IsNullOrEmpty(user.ParentNav))
                                {
                                    TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                }
                                int BrandId = pos.BrandId;
                                if (BrandId == 12 || BrandId == 13)
                                {
                                    MerchantRecord merinfo = spdb.MerchantRecord.FirstOrDefault(m => m.MerNo == Mer.MerNo);
                                    if(merinfo != null)
                                    {
                                        Mer.MerIdcardNo = merinfo.LegalIdCard;
                                        Mer.MerName = merinfo.LegalName;
                                    }
                                }

                                PxcModels.PosMerchantInfo add = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == Mer.MerNo);
                                if (add == null)
                                {
                                    int IsFirst = 1;
                                    if(!string.IsNullOrEmpty(Mer.MerIdcardNo))
                                    {
                                        string startNo = Mer.MerIdcardNo.Substring(0, 6);
                                        string endNo = Mer.MerIdcardNo.Substring(Mer.MerIdcardNo.Length - 4, 4).ToUpper();
                                        string Name = Mer.MerName;
                                        if (Mer.ProductType == "2")
                                        {
                                            if (Name.Contains("-"))
                                            {
                                                Name = Name.Split('-')[1];
                                            }
                                            else if (Name.Contains("_"))
                                            {
                                                Name = Name.Split('_')[1];
                                            }
                                        }
                                        else if (Mer.ProductType == "4" || Mer.ProductType == "8" || Mer.ProductType == "9")
                                        {
                                            Name = Mer.SeoTitle;
                                        }
                                        else if (Mer.ProductType == "10")
                                        {
                                            Name = Name.Replace("*", "");
                                        }
                                        Name = Name.Replace("个体户", "");
                                        Name = Name.Replace("个体商户", "");
                                        Name = Name.Replace("企业户", "");
                                        Name = Name.Replace("企业商户", "");
                                        function.WriteLog(DateTime.Now.ToString() + "-----startNo:" + startNo + ",endNo:" + endNo + ",Name:" + Name, "监控机具是否互斥");
                                        PxcModels.PosMerchantInfo check = db.PosMerchantInfo.FirstOrDefault(m => m.MerIdcardNo.StartsWith(startNo) && m.MerIdcardNo.EndsWith(endNo) && m.MerchantName.Contains(Name));
                                        if(check != null)
                                        {
                                            function.WriteLog("互斥机具---sn:" + check.KqSnNo + ",merno:" + check.KqMerNo + ",name:" + check.MerchantName, "监控机具是否互斥");
                                            IsFirst = 0;
                                            int RecordId = PublicFunction.FeeSetRecord(db, pos, check, 0.63M);
                                            string info = "{\"RecordId\":\"" + RecordId + "\",\"PosId\":\"" + pos.Id + "\",\"Fee\": \"0.63\",\"Kind\": \"2\",\"OpMan\": \""+"系统"+"\"}";
                                            RedisDbconn.Instance.AddList("SetDepositQueue", info);
                                        }
                                    }
                                    add = db.PosMerchantInfo.Add(new PxcModels.PosMerchantInfo()
                                    {
                                        CreateDate = Mer.CreateTime,
                                        KqMerNo = Mer.MerNo,
                                        MerchantNo = Mer.MerNo.Length > 16 ? Mer.MerNo.Substring(0, 16) : Mer.MerNo,
                                    }).Entity;
                                    //查询商户备份表，如果有记录则继承之前的商户Id
                                    if(Mer.ProductType == "1") //判断是否金控
                                    {
                                        function.WriteLog(DateTime.Now.ToString(), "监控金控换绑机具日志");
                                        function.WriteLog("Mer.MerNo:" + Mer.MerNo, "监控金控换绑机具日志");
                                        PxcModels.PosMerchantInfoBak MerBak = db.PosMerchantInfoBak.FirstOrDefault(m => m.KqMerNo == Mer.MerNo);
                                        if(MerBak != null)
                                        {
                                            function.WriteLog("有备份商户-机具SN:" + MerBak.KqSnNo, "监控金控换绑机具日志");
                                            PxcModels.PosMachinesTwo OldPos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == MerBak.KqSnNo);
                                            if(OldPos != null)
                                            {
                                                function.WriteLog("首台机标记:新机具" + pos.IsFirst + ",老机具" + OldPos.IsFirst, "监控金控换绑机具日志");
                                                pos.IsFirst = OldPos.IsFirst;
                                            }
                                            add.Id = MerBak.Id;
                                            db.PosMerchantInfoBak.Remove(MerBak);
                                        }
                                        else
                                        {
                                            function.WriteLog("无备份商户", "监控金控换绑机具日志");
                                            pos.IsFirst = IsFirst;
                                        }
                                        function.WriteLog("\n\n", "监控金控换绑机具日志");
                                    }
                                    else
                                    {
                                        pos.IsFirst = IsFirst;
                                    }
                                    db.SaveChanges();
                                    function.WriteLog("MerNo:" + Mer.MerNo + ",PosSn:" + pos.PosSn + ",IsFirst:" + IsFirst + "\n\n", "监控机具是否互斥");
                                }
                                add.UpdateDate = Mer.UpdateTime;
                                add.TopUserId = TopUserId;
                                add.BrandId = BrandId;
                                add.SnStoreId = pos.StoreId;
                                add.SnType = pos.PosSnType;
                                add.UserId = pos.UserId;
                                add.MgrName = Mer.AgentName;
                                add.MerStatus = 1;
                                add.KqSnNo = Mer.SnNo;
                                string CertId = function.CheckNull(Mer.MerIdcardNo).ToUpper();
                                if(BrandId == 15 || BrandId == 16)
                                {
                                    CertId = CertId.Substring(0, 6) + "********" + CertId.Substring(CertId.Length - 4);
                                }
                                add.MerIdcardNo = CertId;
                                add.MerRealName = Mer.MerRealName;
                                add.MerchantMobile = Mer.MerMobile;
                                add.MerchantName = Mer.MerName;
                                pos.BindMerchantId = add.Id;
                                pos.LastMerchantId = add.Id;
                                db.SaveChanges();
                                PxcModels.Users buser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new PxcModels.Users();
                                if(buser.BusinessFlag == 1)
                                {
                                    bool checkMer = db.BusinessPartnerMerchant.Any(m => m.MerchantId == add.Id);
                                    if(!checkMer)
                                    {
                                        PxcModels.BusinessPartnerPos bpos = db.BusinessPartnerPos.FirstOrDefault(m => m.PosId == pos.Id) ?? new PxcModels.BusinessPartnerPos();
                                        db.BusinessPartnerMerchant.Add(new PxcModels.BusinessPartnerMerchant()
                                        {
                                            CreateDate = DateTime.Now,
                                            MerNo = Mer.MerNo,
                                            MerchantId = add.Id,
                                            PartnerId = bpos.PartnerId,
                                            UserId = pos.BuyUserId,
                                        });
                                        db.SaveChanges();
                                    }
                                }

                                // if(pos.PrizeParams == "0")
                                // {
                                //     int RecordId = PublicFunction.FeeSetRecord(db, pos, add, 0.63M);
                                //     string info = "{\"RecordId\":\"" + RecordId + "\",\"PosId\":\"" + pos.Id + "\",\"Fee\": \"0.63\",\"Kind\": \"2\",\"OpMan\": \""+"系统"+"\"}";
                                //     RedisDbconn.Instance.AddList("SetDepositQueue", info);
                                // }

                                Merchants edit = spdb.Merchants.FirstOrDefault(m => m.Id == Mer.Id);
                                if (edit != null)
                                {
                                    edit.Status = 2;
                                    spdb.SaveChanges();
                                }
                                tran.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Mer.Id, "同步SP商户数据到MAIN异常");
                        }
                        tran.Dispose();
                    }
                    spdb.SaveChanges();
                    spdb.Dispose();
                    db.SaveChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP商户数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}