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 WifiChangeBindHelper
{
    public readonly static WifiChangeBindHelper Instance = new WifiChangeBindHelper();
    private WifiChangeBindHelper()
    {
    }

    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>("kxs_changebindwifi_list");
                if(!string.IsNullOrEmpty(content))
                {
                    DoSomething(content);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "WIFI换绑异常");
            }
        }
    }

    public void DoSomething(string content)
    {
        string[] data = content.Split(new string[] { "#cut#" }, StringSplitOptions.None);
        JsonData jsonObj = JsonMapper.ToObject(data[1]);
        string oldSn = jsonObj["oldSn"].ToString();
        string newSn = jsonObj["newSn"].ToString();
        WebCMSEntities db = new WebCMSEntities();
        WifiTradeRecord edit = db.WifiTradeRecord.FirstOrDefault(m => m.SnNo == oldSn);
        if(edit != null)
        {
            edit.Remark = oldSn;
            edit.SnNo = newSn;
            db.SaveChanges();
        }
        db.Dispose();
    }
}