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

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

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

        public void StartDo()
        {
            while (true)
            {
                try
                {
                    List<string> BrandIds = new List<string>();
                    BrandIds.Add("17");
                    WebCMSEntities spdb = new WebCMSEntities();
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    DateTime start = DateTime.Now.AddDays(-10);
                    DateTime end = DateTime.Now.AddMinutes(-1);
                    int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/TradeRecordId.txt")));
                    IQueryable<TradeRecord> trades = spdb.TradeRecord.Where(m => m.Id >= StartId && BrandIds.Contains(m.ProductType) && m.CreateDate >= start && m.Status == 1).OrderBy(m => m.CreateDate).Take(20);
                    foreach (TradeRecord trade in trades.ToList())
                    {
                        PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == trade.TradeSnNo);
                        if (pos != null)
                        {
                            PxcModels.KqProducts brand = db.KqProducts.FirstOrDefault(m => m.Id == pos.BrandId) ?? new PxcModels.KqProducts();
                            if (pos.BindMerchantId > 0)
                            {
                                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]);
                                }
                                bool check = db.SpOrderNos.Any(m => m.OrderNo == trade.TradeSerialNo);
                                if (!check)
                                {
                                    decimal TradeAmount = trade.TradeAmount / 100;
                                    int BankCardType = 1;
                                    int QrPayFlag = 0;
                                    int VipFlag = 0;
                                    int PayType = 0;
                                    int BrandId = pos.BrandId;
                                    int ActStatus = pos.ActivationState;
                                    if (TradeAmount > 0)
                                    {
                                        PxcModels.TradeRecord add = db.TradeRecord.Add(new PxcModels.TradeRecord()
                                        {
                                            ParentNav = user.ParentNav,
                                            CreateDate = trade.CreateDate,
                                            UpdateDate = trade.UpdateDate,
                                            RecordNo = trade.TradeSerialNo, //单号
                                            UserId = pos.UserId, //创客
                                            MerchantId = pos.BindMerchantId, //商户
                                            MerNo = trade.MerNo, //渠道商户编号
                                            MerHelpFlag = 0,
                                            HelpMonthCount = 0, //扶持第几个月
                                            MerBuddyType = user.MerchantType, //商户创客类型
                                            SnNo = trade.TradeSnNo, //渠道SN号
                                            TradeSerialNo = trade.ChannelSerial, //交易流水号
                                            TradeAmount = TradeAmount, //交易金额
                                            BankCardType = BankCardType, //银行卡类型
                                            QrPayFlag = QrPayFlag, //云闪付标识
                                            VipFlag = VipFlag, //会员标记
                                            PayType = PayType, //支付方式
                                            BrandId = BrandId, //品牌
                                            Remark = trade.Remark, //备注
                                            TopUserId = TopUserId, //顶级创客
                                            MerUserId = pos.UserId, //商户直属创客M
                                            ActStatus = ActStatus,
                                            CreateMan = trade.AgentNo,
                                            UpdateMan = trade.BankCardType,
                                            SeoKeyword = trade.SerEntryMode,
                                            SeoDescription = trade.TradeType,
                                            TradeDate = pos.BindingTime,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    db.SpOrderNos.Add(new PxcModels.SpOrderNos()
                                    {
                                        OrderNo = trade.TradeSerialNo
                                    });
                                    db.SaveChanges();
                                }
                                TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                                if (edit != null)
                                {
                                    edit.Status = 2;
                                }
                                spdb.SaveChanges();
                            }
                            else
                            {
                                TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                                if (edit != null)
                                {
                                    edit.Status = 0;
                                }
                                spdb.SaveChanges();
                            }
                        }
                        else
                        {
                            TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                            if (edit != null)
                            {
                                edit.Status = 0;
                            }
                            spdb.SaveChanges();
                        }
                    }
                    spdb.Dispose();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP吱客宝交易数据到MAIN异常");
                }
                Thread.Sleep(500);
            }
        }

    }
}