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

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

    private void DoWorks()
    {
        while (true)
        {
            try
            {
                if(DateTime.Now.Day == 1 && DateTime.Now.Hour > 22)
                {
                    DoSomething();
                }
                Thread.Sleep(900000);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "WIFI检查异常");
            }
        }
    }

    public void DoSomething()
    {
        string Month = DateTime.Now.ToString("yyyyMM");
        string chk = function.ReadInstance("/wifi/check" + Month + ".txt");
        if(!string.IsNullOrEmpty(chk))
        {
            return;
        }
        function.WritePage("/wifi/", "check" + Month + ".txt", DateTime.Now.ToString());
        WebCMSEntities db = new WebCMSEntities();
        MySystem.JavaProductModels.WebCMSEntities javadb = new MySystem.JavaProductModels.WebCMSEntities();
        int i = 0;
        var items = javadb.KxsMachineThali;
        foreach(var item in items)
        {
            javadb.KxsMachineThali.Remove(item);
        }
        javadb.SaveChanges();
        List<WifiTradeRecord> trades = db.WifiTradeRecord.Where(m => m.Duration > m.DoMonths).ToList();
        foreach(WifiTradeRecord trade in trades)
        {
            i += 1;
            javadb.KxsMachineThali.Add(new MySystem.JavaProductModels.KxsMachineThali()
            {
                MonthTime = int.Parse(Month),
                PosSn = trade.SnNo,
                BrandId = trade.BrandId,
                CreateTime = DateTime.Now,
            });
            if(i % 200 == 0)
            {
                javadb.SaveChanges();
            }
        }
        javadb.SaveChanges();
        javadb.Dispose();
        db.Dispose();

        string dataContent = "{\"monthTime\":\"" + Month + "\"}";
        string encryptContent = PosPushHelper.Instance.AesEncrypt(dataContent);
        encryptContent = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(encryptContent));
        string content = function.PostWebRequest(ConfigurationManager.AppSettings["JavaGatewayHost"].ToString() + "/v1/kxs/dcmServer/dcm-logout-trade/batchUpdateActNum", encryptContent, "application/json");
    }
}