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

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

        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(-30);
                    List<ChangeBindRecord> Binds = spdb.ChangeBindRecord.Where(m => m.ReBindTime >= start && m.Status == 1).OrderByDescending(m => m.Id).ToList();
                    foreach (ChangeBindRecord Bind in Binds)
                    {
                        var tran = db.Database.BeginTransaction();
                        try
                        {
                            string OldSnNum = Bind.MerSnNo;
                            string NewSnNum = Bind.MerNewSnNo;
                            string MerNo = Bind.MerNo;
                            PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == MerNo) ?? new PxcModels.PosMerchantInfo();
                            PxcModels.MachineForSnNo oldForSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == OldSnNum) ?? new PxcModels.MachineForSnNo();
                            PxcModels.MachineForSnNo newForSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == NewSnNum) ?? new PxcModels.MachineForSnNo();
                            PxcModels.PosMachinesTwo oldpos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == oldForSnNo.SnId);
                            PxcModels.PosMachinesTwo newpos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == newForSnNo.SnId);
                            PxcModels.StoreHouse BackStore = db.StoreHouse.FirstOrDefault(m => m.Id == oldpos.StoreId) ?? new PxcModels.StoreHouse();
                            PxcModels.StoreHouse OutStore = db.StoreHouse.FirstOrDefault(m => m.Id == newpos.StoreId) ?? new PxcModels.StoreHouse();
                            string ChangeNo = "BMC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(3);
                            PxcModels.MachineChange add = db.MachineChange.Add(new PxcModels.MachineChange()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                ChangeNo = ChangeNo, //转换单号
                                UserId = 0, //创客
                                ChangeTime = DateTime.Now, //转换时间
                                BackStoreId = BackStore.Id, //退回仓库
                                BackStoreName = BackStore.StoreName, //退回仓库名称
                                Remark = "机具更换", //订单备注
                                BackStoreUserId = BackStore.UserId, //退回仓库归属人
                                OutProductType = int.Parse(OutStore.BrandId), //出库产品类型
                                OutProductName = OutStore.ProductName, //出库产品名称
                                OutStoreId = OutStore.Id, //出库仓库
                                OutStoreName = OutStore.StoreName, //出库仓库名称
                                OutStoreAreas = OutStore.Areas, //出库仓库所在地区
                                OutStoreAddress = OutStore.Address, //出库仓库地址
                                OutStoreManager = "", //出库仓库联系人
                                OutStoreManagerMobile = OutStore.ManageMobile, //出库仓库联系人手机号
                            }).Entity;
                            db.SaveChanges();
                            int BackProductType = 0;
                            string BackProductName = "";
                            string ChangeDeviceName = "";
                            string ChangeSnExpand = "";
                            PxcModels.KqProducts oldPosBrand = db.KqProducts.FirstOrDefault(m => m.Id == oldpos.BrandId) ?? new PxcModels.KqProducts();
                            PxcModels.KqProducts newPosBrand = db.KqProducts.FirstOrDefault(m => m.Id == newpos.BrandId) ?? new PxcModels.KqProducts();
                            newpos.BindMerchantId = merchant.Id;
                            newpos.BuyUserId = oldpos.BuyUserId;
                            newpos.UserId = oldpos.UserId;
                            newpos.RecycEndDate = oldpos.RecycEndDate;
                            newpos.ScanQrTrade = oldpos.ScanQrTrade;
                            newpos.DebitCardTrade = oldpos.DebitCardTrade;
                            newpos.CreditTrade = oldpos.CreditTrade;
                            newpos.PosSnType = oldpos.PosSnType;
                            newpos.TransferTime = oldpos.TransferTime;
                            newpos.IsPurchase = oldpos.IsPurchase;
                            newpos.BindingState = oldpos.BindingState;
                            newpos.ActivationState = oldpos.ActivationState;
                            newpos.BindingTime = oldpos.BindingTime;
                            newpos.ActivationTime = oldpos.ActivationTime;
                            newpos.IsFirst = oldpos.IsFirst;
                            // bool checkActReward = db.ActiveReward.Any(m => m.KqMerNo == merchant.KqMerNo);
                            // if (!checkActReward)
                            // {
                            newpos.SeoKeyword = oldpos.SeoKeyword;
                            newpos.PrizeParams = oldpos.PrizeParams;
                            newpos.LeaderUserId= oldpos.LeaderUserId;
                            // }
                            // oldpos.BuyUserId = 0;
                            // oldpos.UserId = 0;
                            oldpos.Status = -1;
                            PxcModels.MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == merchant.KqMerNo);
                            if (forMerNo != null)
                            {
                                forMerNo.SnId = newpos.Id;
                            }
                            merchant.KqSnNo = NewSnNum;
                            db.MachineChangeDetail.Add(new PxcModels.MachineChangeDetail()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                ChangeNo = ChangeNo, //订单号
                                ChangeId = add.Id, //订单Id
                                BackProductType = oldpos.BrandId, //退回产品类型
                                BackProductName = oldPosBrand.Name, //退回产品名称
                                UserId = oldpos.BuyUserId, //创客
                                BackSnNo = oldpos.PosSn, //设备SN编号
                                OutProductType = newpos.BrandId, //出库产品类型
                                OutProductName = newPosBrand.Name, //出库产品名称
                                OutSnNo = newpos.PosSn, //出库设备SN编号
                                OutSnType = newpos.PosSnType, //出库SN机具类型
                                Remark = "机具更换", //备注
                                BackSnType = oldpos.PosSnType, //退回SN机具类型
                            });
                            db.SaveChanges();
                            BackProductType = oldpos.BrandId;
                            BackProductName = newPosBrand.Name;
                            ChangeDeviceName = oldpos.DeviceName;
                            ChangeSnExpand = oldpos.PosSn;                            
                            add.BackProductType = BackProductType; //退回产品类型
                            add.BackProductName = BackProductName; //退回产品名称
                            add.ChangeDeviceName = ChangeDeviceName; //转换机具名称
                            add.ChangeDeviceNum = 1; //转换机具数量
                            add.ChangeSnExpand = ChangeSnExpand; //机具SN
                            db.SaveChanges();

                            ChangeBindRecord edit = spdb.ChangeBindRecord.FirstOrDefault(m => m.Id == Bind.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" + Bind.Id, "同步SP换绑数据到MAIN异常");
                        }
                        tran.Dispose();
                    }
                    spdb.Dispose();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP换绑数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}