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.MachineForMerNo posFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Mer.MerNo) ?? new PxcModels.MachineForMerNo();
                            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;

                                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, "监控机具是否互斥");
                                        bool check = db.PosMerchantInfo.Any(m => m.MerIdcardNo.StartsWith(startNo) && m.MerIdcardNo.EndsWith(endNo) && m.MerchantName.Contains(Name));
                                        if(check)
                                        {
                                            IsFirst = 0;
                                        }
                                    }
                                    pos.IsFirst = IsFirst;
                                    add = db.PosMerchantInfo.Add(new PxcModels.PosMerchantInfo()
                                    {
                                        CreateDate = Mer.CreateTime,
                                        KqMerNo = Mer.MerNo,
                                        MerchantNo = Mer.MerNo,
                                    }).Entity;
                                    db.SaveChanges();
                                    function.WriteLog("MerNo:" + Mer.MerNo + ",PosSn:" + pos.PosSn + ",IsFirst:" + IsFirst + "\n\n", "监控机具是否互斥");
                                }
                                // else
                                // {
                                //     string SnNo = add.KqSnNo;
                                //     PxcModels.MachineForMerNo oldPosFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == SnNo) ?? new PxcModels.MachineForMerNo();
                                //     PxcModels.PosMachinesTwo oldPos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == oldPosFor.SnId) ?? new PxcModels.PosMachinesTwo();
                                //     pos.IsFirst = oldPos.IsFirst;
                                // }
                                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;
                                add.MerIdcardNo = function.CheckNull(Mer.MerIdcardNo).ToUpper();
                                add.MerRealName = Mer.MerRealName;
                                add.MerchantMobile = Mer.MerMobile;
                                add.MerchantName = Mer.MerName;
                                pos.BindMerchantId = 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();
                                    }
                                }
                                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);
            }
        }
    }
}