using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Learun.Util;
using Newtonsoft.Json;

namespace DigitalSchoolApi.App_Data
{

    public class LicenseStatus
    {
        public bool Result { get; set; }
        public string Message { get; set; }
        public string ExpirationDate { get; set; }
    }

    public class LicenseChecker
    {
        /// <summary>
        /// license.bjqj文件地址
        /// </summary>
        private static string licensePath = ConfigurationManager.AppSettings["licensePath"];

        public static string GenerateMachineId()
        {
            string cpuid = ""; LicenseManager.GetCPUSerialNumber();
            string hd = LicenseManager.GetHardDriverNumber().TrimEnd();
            string bios = ""; LicenseManager.GetBoisNumber();
            string uid = LicenseManager.GetMachineName().TrimEnd();
            return DESEncrypt.Encrypt(cpuid + hd + bios + uid, "bjquanjiang@2020!");
        }

        public static void WriteLicense(string licensecode)
        {
            try
            {
                string binpath = AppDomain.CurrentDomain.BaseDirectory;
                string fullpath = binpath + "\\bin\\license.bjqj";
                System.IO.File.WriteAllText(fullpath, licensecode);
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        public static LicenseStatus CheckLicense()
        {
            StreamReader sr = null;
            string machineid = string.Empty;
            LicenseStatus ls = new LicenseStatus();
            try
            {
                TimeOutCheckTool tool = new TimeOutCheckTool();
                var checkResult = tool.TimeoutCheckTwo(4000, () => GetMAManagementInfo());
                if (!checkResult)
                {
                    ls.Message = "未授权";
                    return ls;
                }
                machineid = GenerateMachineId();
                //判断有无授权
                string binpath = licensePath;//AppDomain.CurrentDomain.BaseDirectory;
                string fullpath = binpath + "\\license.bjqj";
                if (System.IO.File.Exists(fullpath))
                {
                    sr = new StreamReader(fullpath, Encoding.UTF8);
                    string u7str = sr.ReadToEnd();
                    if (!string.IsNullOrEmpty(u7str))
                    {
                        string desstr = DESEncrypt.Decrypt(u7str, "bjquanjiang@2020!@lckey" + Md5Helper.Encrypt(machineid, 32));
                        
                        if (!string.IsNullOrEmpty(desstr))
                        {
                            string[] codeanddate = desstr.Split('&');
                            if (codeanddate[0] == Md5Helper.Encrypt(machineid, 16))
                            {
                                ls.ExpirationDate = codeanddate[1];
                                if (!string.IsNullOrEmpty(codeanddate[1]))
                                {
                                    ls.Result = LicenseManager.GetNowTime(codeanddate[1]);
                                }
                                else
                                {
                                    ls.Result = true;
                                    ls.ExpirationDate = "永久有效";
                                }

                                ls.Message = ls.Result ? "已授权" : "授权期已过";
                            }
                            else
                            {
                                ls.Message = "未授权";
                            }
                        }
                        else
                        {
                            ls.Message = "未授权";
                        }
                    }
                    else
                    {
                        ls.Message = "未授权";
                    }
                }
                else
                {
                    ls.Message = "未找到授权文件";
                }
                return ls;
            }
            catch (Exception e)
            {
                ls.Result = false;
                ls.Message = "未授权,不正确的授权文件";
                return ls;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Dispose();
                    sr.Close();
                }
            }
        }

        /// <summary>
        /// 网络授权判断
        /// </summary>
        /// <returns></returns>
        public static bool GetMAManagementInfo()
        {
            try
            {
                //查找授权管理信息
                var url = "http://123.57.209.16:8062/management/data";
                var MachineId = LicenseChecker.GenerateMachineId();
                var body = "{\"data\":'{\"code\":\"" + MachineId + "\",\"guid\":\"123\"}'}";

                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";

                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    dynamic res = JsonConvert.DeserializeObject(reader.ReadToEnd());
                    if (res.data == null)
                    {
                        return false;

                    }
                    else
                    {
                        bool Result = res.data;
                        if (Result)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }

                    }
                }
            }
            catch (Exception e)
            {
                return true;
            }

        }
    }
}
