using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Data;
using MySystem;
using MySystem.PxcModels;
using Library;
using LitJson;

public class ToBigHelper
{
    public readonly static ToBigHelper Instance = new ToBigHelper();
    private ToBigHelper()
    {
    }

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

    private void DoWorks()
    {
        while (true)
        {
            try
            {
                string content = RedisDbconn.Instance.RPop<string>("ToBigQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    WebCMSEntities db = new WebCMSEntities();
                    DoSomething(db, content);
                    db.Dispose();
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "电签机具兑换大机资格异常");
            }
        }
    }

    public void DoSomething(WebCMSEntities db, string content)
    {
        JsonData data = JsonMapper.ToObject(content);
        int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
        string SnNos = data["SnNos"].ToString(); //券列表
        Dictionary<string, object> Obj = new Dictionary<string, object>();
        List<string> Codes = SnNos.Split(',').ToList();
        List<int> LeaderUserIds = new List<int>();
        int index = 0;
        string ToCodes = "";
        List<PosMachinesTwo> list = db.PosMachinesTwo.Where(m => Codes.Contains(m.PosSn) && m.BuyUserId == UserId && m.IsPurchase == 0 && (m.ActivationState == 1 || (!string.IsNullOrEmpty(m.SeoKeyword) && m.SeoKeyword != "0"))).OrderBy(m => m.RecycEndDate).ToList();
        foreach(PosMachinesTwo sub in list)
        {
            index += 1;
            PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == sub.Id);
            if(edit != null)
            {
                if(index % 2 == 0)
                {
                    edit.OpId = 2;
                    ToCodes += sub.PosSn + ",";
                }
                else
                {
                    edit.IsPurchase = 1;
                }
            }
        }
        db.SaveChanges();
        int Count = Codes.Count / 2;
        db.PosCouponExchangeRecord.Add(new PosCouponExchangeRecord()
        {
            CreateDate = DateTime.Now,
            Note = "通兑资格",
            ToCount = Count,
            SourceCount = Codes.Count,
            ToCoupons = ToCodes.TrimEnd(','),
            SourceCoupons = SnNos,
            UserId = UserId,
            QueryCount = 1,
        });
        db.SaveChanges();
    }
}