using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using SXLibrary;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SQLite;
using System.Globalization;
using System.IO;
using System.Management;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using WHC.OrderWater.Commons;
using HttpHelper = SufeiUtil.HttpHelper;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Linq;

namespace MOKA_Factory_Tools
{
    class CommonMethod
    {
        [DllImport("kernel32")]
        public static extern bool GetProfileString(string lpApplicationName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize);
        [DllImport("kernel32")]
        public static extern bool WriteProfileString(string lpApplicationName, string lpKeyName, string lpString);

        public static string FactoryName = "Unknown";

        private static string lastOrder = "";
        private static List<string> ListACASSN = new List<string>();

        private static LoginInput loginInput = new LoginInput();

        /// <summary>
        /// 保存登录信息;
        /// </summary>
        /// <param name="strAccount"></param>
        /// <param name="strPssword"></param>
        public static void SaveLoginInfo(string strAccount, string strPssword)
        {
            loginInput.account = strAccount;
            loginInput.password = strPssword;
        }

        /// <summary>
        /// 获取登录账号;
        /// </summary>
        /// <returns></returns>
        public static string GetLoginAccout()
        {
            return loginInput.account;
        }

        public static string ReadProfileString(string lpApplicationName, string lpKeyName, string lpDefault)
        {
            StringBuilder MyString = new StringBuilder(256);
            GetProfileString(lpApplicationName, lpKeyName, lpDefault, MyString, 256);
            if ( MyString.Length > 0)
                return MyString.ToString();

            return lpDefault;
        }

        /// <summary>
        /// 更新G客户抄写状态;
        /// </summary>
        /// <param name="SN">当前SN</param>
        /// <param name="bResult">当前SN的抄写结果，true=pass, false=fail</param>
        public static void UpdateGSNProfile( string SN, bool bResult = false )
        {
            string strLastSN = ReadProfileString("MOKAFactoryTools", "LastGSN", "");
            if (!strLastSN.Equals(SN, StringComparison.OrdinalIgnoreCase))
            {
                WriteProfileString("MOKAFactoryTools", "LastGSN", SN);
                // 清空连续次数值;
                WriteProfileString("MOKAFactoryTools", "GFailCount", "0");
                // 清空上次测试状态;
                WriteProfileString("MOKAFactoryTools", "LastGResult", "0");
            }
            else
            {
                if (bResult == false)
                {
                    int nGSNCount = Convert.ToInt32(ReadProfileString("MOKAFactoryTools", "GFailCount", "0")) + 1;
                    // 更新连续测试中累计失败的次数;
                    WriteProfileString("MOKAFactoryTools", "GFailCount", nGSNCount.ToString());
                }
                // 更新抄写状态;
                WriteProfileString("MOKAFactoryTools", "LastGResult", bResult ? "1" : "0");
            }
        }

        //public static string LocalMacAddress = GetMacAddress();
        /// <summary>
        /// 获取活动网卡硬件地址
        /// </summary>
        /// <returns></returns>
        public static string GetMacAddress()
        {
            string mac = "";
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
            {
                ManagementObjectCollection moc = mc.GetInstances();
                int i = 0;
                int j = 0;
                foreach (ManagementObject mo in moc)
                {
                    if (mo["MacAddress"] != null)
                    {
                        if (Convert.ToBoolean(mo["IPEnabled"]))
                        {
                            if (j < 2)
                            {
                                mac = mo["MacAddress"].ToString() + "&" + mac;
                                j++;
                            }

                        }
                        else
                        {
                            if (i < 1)
                            {
                                mac += mo["MacAddress"].ToString() + "&";
                                i++;
                            }
                        }
                    }
                }
            }
            return mac.Replace(":", "-");
            //return "C0-B6-F9-44-D7-BB";

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="runFilePath"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static bool StartProcess(string runFilePath, string args)
        {
            try
            {
                Process process = new Process();//创建进程对象    
                ProcessStartInfo startInfo = new ProcessStartInfo(runFilePath, args);
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                process.StartInfo = startInfo;
                return process.Start();
                //process.WaitForExit();
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog(string.Format("打开进程{0}失败：{1}", runFilePath, ex.Message));
            }
            
            return false;
        }

        public static bool StartProcess(string runFilePath, string args, out string outPutMsg)
        {
            try
            {
                outPutMsg = null;
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo(runFilePath, args);
                startInfo.UseShellExecute = false;
                process.StartInfo = startInfo;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow= true;
                process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "replace_tv_projects";
                process.Start();
                outPutMsg = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }
            catch(Exception ex)
            {
                outPutMsg = null;
                Log.WriteErrorLog(string.Format("打开进程{0}失败：{1}", runFilePath, ex.Message));
                return false;
            }

            Log.WriteInfoLog(string.Format("adb push结果={0}",outPutMsg));

            return true;
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="order"></param>
        /// <param name="pcmac"></param>
        /// <param name="iptvip"></param>
        /// <param name="version"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="mid"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool GetMidInfo(string url, string order, string pcmac, string iptvip, string version, SQLiteConnection sqliteConn, out MidList mid)
        {
            mid = new MidList();
            OrderInput orderInput1 = new OrderInput { bid = order, mac = pcmac, version = "", clientType = "" };//"74-27-EA-6E-DA-9F"
            string jsonorder = JsonConvert.SerializeObject(orderInput1, Newtonsoft.Json.Formatting.Indented);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = jsonorder,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            HttpResult result = http.GetHtml(item);
            stopwatch.Stop();
            string usingtime = stopwatch.ElapsedMilliseconds.ToString();
            stopwatch.Reset();
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nGet MID info\r\nUsing time:" + usingtime + "ms\r\n" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to GetMidInfo:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to GetMidInfo", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                mid.message = jObject["message"].Value<string>();
                mid.code = jObject["code"].Value<string>();
                mid.factoryname = jObject["factoryName"].Value<string>();
                mid.factoryNum = jObject["factoryNum"].Value<string>();
                mid.version = jObject["version"].Value<string>();
                mid.quantity = jObject["quantity"].Value<string>();
                mid.projectid = jObject["projectId"].Value<string>();
                mid.clienttype = jObject["clientType"].Value<string>();
                mid.host = jObject["host"].Value<string>();
                mid.whiteType = jObject["whiteType"].Value<string>();
                object a = jObject["rokuCustomer"];
                if (jObject["rokuCustomer"].ToString().Length > 0)
                    mid.rokuCustomer = new RokuCustomer()
                    {
                        id = JSON_SeleteNode(jObject["rokuCustomer"], "id").Trim(),
                        ordernum = JSON_SeleteNode(jObject["rokuCustomer"], "ordernum").Trim(),
                        brand = JSON_SeleteNode(jObject["rokuCustomer"], "brand").Trim(),
                        region = JSON_SeleteNode(jObject["rokuCustomer"], "region").Trim(),
                        oemmodel = JSON_SeleteNode(jObject["rokuCustomer"], "oemmodel").Trim(),
                        supporturl = JSON_SeleteNode(jObject["rokuCustomer"], "supporturl").Trim(),
                        supportphone = JSON_SeleteNode(jObject["rokuCustomer"], "supportphone").Trim(),
                        productiondate = JSON_SeleteNode(jObject["rokuCustomer"], "productiondate").Trim(),
                        remotetype = JSON_SeleteNode(jObject["rokuCustomer"], "remotetype").Trim(),
                        updatetime = JSON_SeleteNode(jObject["rokuCustomer"], "updatetime").Trim(),
                        createtime = JSON_SeleteNode(jObject["rokuCustomer"], "createtime").Trim(),
                        isdelete = JSON_SeleteNode(jObject["rokuCustomer"], "isdelete").Trim()
                    };

                mid.keytype = new Dictionary<string, string>();
                foreach (var ss in jObject["obj"])  //查找某个字段与值
                {
                    mid.keytype.Add(ss["name"].Value<string>(), ss["type"].Value<string>());
                }
                if (url == Serverurl.Testurl)
                    mid.host = "http://test.idmanage.qhmoka.com/IDManage";
                if (mid.code == "1000")
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse MID info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to parse MID info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                MessageBox.Show("Fail to parse MID info\r\n " + ex.Message);
                return false;
            }

        }

        /// <summary>
        /// 获取预绑定模式下的key包地址
        /// </summary>
        /// <param name="midInfo"></param>
        /// <param name="order"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="midAddress"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool GetMidAddress(MidList midInfo, string order, SQLiteConnection sqliteConn, out MidAddress midAddress)
        {
            midAddress = new MidAddress();
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = midInfo.host + "/getofflinelist.do?",//URL这里都是测试URl   必需项
                Encoding = null,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = ("orderNumber=" + order + "&mac=" + HttpUtility.UrlEncode(TestMode.MAC)),
                KeepAlive = false
            };
            item.ContentType = "application/x-www-form-urlencoded";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {

            }
            else
            {
                Log.WriteErrorLog("\r\nFail to get Mid address:" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to get Mid address", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                midAddress.des = JSON_SeleteNode(jObject, "des");
                midAddress.code = JSON_SeleteNode(jObject, "code");
                midAddress.order = JSON_SeleteNode(jObject, "order_number");
                midAddress.number = JSON_SeleteNode(jObject, "order_quantity");
                midAddress.pid = JSON_SeleteNode(jObject, "project_id");
                midAddress.ctype = JSON_SeleteNode(jObject, "client_type");
                midAddress.purl = JSON_SeleteNode(jObject, "packet_url");
                midAddress.psize = JSON_SeleteNode(jObject, "packet_size");
                midAddress.pmd5 = JSON_SeleteNode(jObject, "packet_md5");
                midAddress.version = JSON_SeleteNode(jObject, "soft_version");
                midAddress.host = midInfo.host;
                Log.WriteGetKeyLog("\r\nGet Mid address success:" + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse MID address," + ex.Message + ":" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to parse MID address", ex.Message + "\r\n" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
                MessageBox.Show("Fail to parse MIDAddress info\r\n " + ex.Message);
                return false;
            }

        }

        /// <summary>
        /// 获取预绑定模式下的key包地址
        /// </summary>
        /// <param name="midInfo"></param>
        /// <param name="order"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="midAddress"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool GetMidAddress2(MidList midInfo, string order, SQLiteConnection sqliteConn, out List<MidAddress> midAddressList)
        {
            midAddressList = new List<MidAddress>();
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = midInfo.host + "/getofflinelist.do?",//URL这里都是测试URl   必需项
                Encoding = null,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = ("orderNumber=" + order + "&mac=" + HttpUtility.UrlEncode(TestMode.MAC)),
                KeepAlive = false
            };
            item.ContentType = "application/x-www-form-urlencoded";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {

            }
            else
            {
                Log.WriteErrorLog("\r\nFail to get Mid address:" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to get Mid address", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                if (jObject["data"] != null)
                {
                    foreach (var data in jObject["data"])
                    {
                        midAddressList.Add(new MidAddress()
                        {
                            des = JSON_SeleteNode(jObject, "des"),
                            code = JSON_SeleteNode(jObject, "code"),
                            order = data["order_number"].ToObject<string>(),
                            number = data["order_quantity"].ToObject<string>(),
                            pid = data["project_id"].ToObject<string>(),
                            ctype = data["client_type"].ToObject<string>(),
                            purl = data["packet_url"].ToObject<string>(),
                            psize = data["packet_size"].ToObject<string>(),
                            pmd5 = data["packet_md5"].ToObject<string>(),
                            version = data["soft_version"].ToObject<string>(),
                            host = midInfo.host
                        });
                    }
                }

                Log.WriteGetKeyLog("\r\nGet Mid address success:" + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse MID address," + ex.Message + ":" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to parse MID address", ex.Message + "\r\n" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
                MessageBox.Show("Fail to parse MIDAddress info\r\n " + ex.Message);
                return false;
            }

        }

        /// <summary>
        /// 解析XML格式的DID
        /// </summary>
        /// <param name="str"></param>
        /// <param name="node"></param>
        /// <param name="node2"></param>
        /// <param name="code"></param>
        /// <param name="desc"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool GetDIDKeyXml(string str, string node, string node2, out string code, out string desc, out string value)
        {
            code = "";
            value = "";
            try
            {
                XmlDocument xml = new XmlDocument();
                //xml.Load(path);
                xml.LoadXml(str);
                code = xml.SelectSingleNode(node).Attributes.GetNamedItem("code").InnerText;
                desc = xml.SelectSingleNode(node).Attributes.GetNamedItem("desc").InnerText;
                if (code == "200")
                {
                    value = xml.SelectSingleNode(node + "//" + node2).Attributes.GetNamedItem("deviceid").InnerText;
                    string CRC32 = xml.SelectSingleNode(node + "//" + node2).Attributes.GetNamedItem("crc32").InnerText;
                    if (CrcUtils.CRC32(value) == Convert.ToUInt32(CRC32))
                    {
                        return true;
                    }
                    else
                    {
                        desc = "CRC32 error";
                        return false;
                    }

                }
                return false;

            }
            catch (Exception ex)
            {
                desc = ex.Message;
                return false;
            }

        }

        /// <summary>
        /// 解析其他keys
        /// </summary>
        /// <param name="url"></param>
        /// <param name="keymessage"></param>
        /// <param name="keytype"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="key"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool GetIDMKeys(string url, string sn, string order, string psn, string firetv_device_code, List<KeyType> key2Write, SQLiteConnection connection, ref KeyInfo keys, out string msg)
        {
            msg = "";
            string code;
            string desc;
            error = "";
            key = "";
            md5 = "";
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                KeepAlive = false
            };

            // 计算函数耗时;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            switch (keymessage)
            {
                case "DeviceID":
                    {
                        item.URL = url + "/getid.do?";
                        item.Postdata = "devicetype=tcl_unknown_model" + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetDeviceID:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetDIDKeyXml(result.Html, "response", "id", out code, out desc, out key))
                            {
                                //
                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse DID", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get DID", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "MAC":
                    {
                        item.URL = url + "/getmac.do?";
                        item.Postdata = "typeString=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetMac:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "mac", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse Mac", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get Mac", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "HDCP_KEY":
                    {
                        item.URL = url + "/gethdcpkey.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetHDCP_KEY:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "key", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse hdcp", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get hdcp", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "CI_PLUS_KEY":
                    {
                        item.URL = url + "/getcikey.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetCI_PLUS_KEY:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "key", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse ciplus", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get ciplus", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "WiDi":
                    {
                        item.URL = url + "/getwidi.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetWiDi:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "key", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse widi", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get widi", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "HDCP2.2_KEY":
                    {
                        item.URL = url + "/gethdcpkey2.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetHDCP2.2_KEY:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "key", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse hdcp22", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get hdcp22", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "NETFILX_ESN":
                    {
                        item.URL = url + "/getnetfilxesn.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetNETFILX_ESN:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "esn", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse esn", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get esn", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "MGK_KEY":
                    {
                        item.URL = url + "/getmgk.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetMGK:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "key", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse MGK", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get MGK", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "Fairplay_KEY":
                    {
                        item.URL = url + "/getfairplay.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetFairplay:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "fairplay", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse Fairplay", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get Fairplay", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "ECP_KEY":
                    {
                        item.URL = url + "/getecp.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetecp:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "ecp", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse ecp", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get ecp", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "LEK":
                    {
                        item.URL = url + "/getlek.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetlek:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "lek", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse lek", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get lek", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "PEK":
                    {
                        item.URL = url + "/getpek.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetpek:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "pek", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse pek", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get pek", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "PlayReady_key":
                    {
                        item.URL = url + "/getplayready.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetplayready:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "playReady", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse playready", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get playready", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "Hashkey":
                    {
                        item.URL = url + "/gethash.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGethash:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "hash", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse hash", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get hash", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "YouTube_KEY":
                    {
                        item.URL = url + "/getYoutubeKey.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGet youtube key:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "youtubeKey", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse youtube key", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get youtube key", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
                case "DAK":
                    {
                        item.URL = url + "/getdak.do?";
                        item.Postdata = "type=" + keytype + "&sn=" + sn;
                        if (sn.Trim().Length > 0)
                            item.Postdata += "&order=" + order;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetDAK:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.GetOthersKeyXml(result.Html, "response", "dak", out code, out desc, out key, out md5))
                            {

                            }
                            else
                            {
                                error = desc;
                                ReportErrormsg("Fail to parse dak", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                                return false;
                            }
                        }
                        else
                        {
                            error = result.StatusDescription;
                            ReportErrormsg("Fail to get dak", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                            return false;
                        }
                        break;
                    }
            }
            watch.Stop();
            Log.WriteInfoLog(string.Format("[GetKeys] order={0},sn={1},keytype={2},keymessage={3}, Elapsed={4}", order,sn,keytype,keymessage,watch.Elapsed.TotalMilliseconds));
            return true;
        }

        public static bool GetWidevineAnAttestationKey(
            string url,
            string sn,
            string keytype,
            SQLiteConnection sqliteConn,
            out bool isAndroidTV,
            out string Widevinekey,
            out string Attestationkey,
            out string error,
            string order,
            out string AttestationMd5)
        {
            string code;
            string desc;
            isAndroidTV = false;
            error = "";
            Widevinekey = "";
            Attestationkey = "";
            AttestationMd5 = "";

            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                KeepAlive = false
            };

            // 计算函数耗时;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            item.URL = url + "/getWidevineAndAttestation.do?";
            item.Postdata = "type=" + keytype + "&order=" + order + "&sn=" + sn;
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nGetWidevine_KEY:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (!Xmlconfig.GetWidevineAndAttestationKeyXml(result.Html, "response", out code, out desc, out isAndroidTV, out Widevinekey, out Attestationkey, out AttestationMd5))
                {
                    error = desc;
                    ReportErrormsg("Fail to parse widevineAndAttestation", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                    return false;
                }
            }
            else
            {
                error = result.StatusDescription;
                ReportErrormsg("Fail to get widevineAndAttestation", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                return false;
            }

            watch.Stop();
            Log.WriteInfoLog(string.Format("[getWidevineAndAttestation] order={0},sn={1},keytype={2},Elapsed={3}", order, sn, keytype, watch.Elapsed.TotalMilliseconds));
            return true;
        }

        public static bool GetAcasKey(string url, string keymessage, string sn, string keytype, SQLiteConnection sqliteConn, string order, out string acaskey_data, out string acaskey_datamd5, out string acaskey_tool, out string acaskey_toolmd5, out string error)
        {
            string code;
            string desc;
            error = "";
            acaskey_data = "";
            acaskey_datamd5 = "";
            acaskey_tool = "";
            acaskey_toolmd5 = "";
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                KeepAlive = false
            };

            // 计算函数耗时;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            item.URL = url + "/getAcasKey.do?";
            item.Postdata = "type=" + keytype + "&sn=" + sn;
            if (sn.Trim().Length > 0)
                item.Postdata += "&order=" + order;
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nGet ACAS key:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (Xmlconfig.Get2KeyInfoFromXml(result.Html, "acasKey_data", "acasKey_tool", out code, out desc, out acaskey_data, out acaskey_datamd5, out acaskey_tool, out acaskey_toolmd5))
                {

                }
                else
                {
                    error = desc;
                    ReportErrormsg("Fail to parse ACAS key", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                    return false;
                }
            }
            else
            {
                error = result.StatusDescription;
                ReportErrormsg("Fail to get ACAS key", error + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html, sqliteConn);
                return false;
            }
            watch.Stop();
            Log.WriteInfoLog(string.Format("[getAcasKey] order={0},sn={1},keytype={2},Elapsed={3}", order, sn, keytype, watch.Elapsed.TotalMilliseconds));
            return true;
        }

        /// <summary>
        /// 异常上报
        /// </summary>
        /// <param name="reportType"></param>
        /// <param name="reportData"></param>
        /// <param name="sqliteConn"></param>
        /// <returns></returns>
        public static bool ReportErrormsg(string reportType, string reportData, SQLiteConnection sqliteConn)
        {
            // 计算函数耗时;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ErrorInfo ErrorInfo1 = new ErrorInfo { reportType = reportType, reportData = reportData.Replace("'", ""), version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), factory = FactoryName, mac = TestMode.MAC, reportTime = System.DateTime.Now.ToString(("yyyy-MM-dd HH:mm:ss")) };
            string jsonError = Newtonsoft.Json.JsonConvert.SerializeObject(ErrorInfo1, Newtonsoft.Json.Formatting.Indented);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = TestMode.errorreportServerurl,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = jsonError,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
            }
            else
            {
                if (HTTPChecker(item.URL))
                    SQLiteHelper.InsertDelayErrorReport(sqliteConn, new object[] { item.URL, item.Postdata });
                Log.WriteErrorLog("\r\nFail to ReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                string message = jObject["message"].Value<string>();
                string code = jObject["code"].Value<string>();
                if (code != "1000")
                {
                    Log.WriteErrorLog("\r\nError report return error:\r\n" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
                    return false;
                }

                watch.Stop();
                Log.WriteInfoLog(string.Format("[ReportErrormsg] Elapsed={0}", watch.Elapsed.TotalMilliseconds));

                return true;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse Error report return info," + ex.Message + ":" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + jsonError);
                return false;
            }
        }

        /// <summary>
        /// 上报预绑定包下载结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="order"></param>
        /// <param name="sqliteConn"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool ReportDownloadStatus(string url, string order, SQLiteConnection sqliteConn)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url + "/getreportofflinesn.do?",//URL这里都是测试URl   必需项
                Encoding = null,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = ("orderNumber =" + order),
                KeepAlive = false
            };
            item.ContentType = "application/x-www-form-urlencoded";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to report download status:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order));
                CommonMethod.ReportErrormsg("Fail to report download status", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order), sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                string des = JSON_SeleteNode(jObject, "des");
                string code = JSON_SeleteNode(jObject, "code");
                string data = JSON_SeleteNode(jObject, "data");
                if (code == "1000")
                    return true;
                else
                {
                    Log.WriteErrorLog("\r\nError report download status,should be 1000:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order));
                    CommonMethod.ReportErrormsg("Error download status code return", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order), sqliteConn);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Log.WriteErrorLog("\r\n" + ex.Message + ":" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order));
                CommonMethod.ReportErrormsg("Error parse download status return", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/getreportofflinesn.do?" + "\r\nPostdata:" + ("orderNumber =" + order), sqliteConn);
                return false;
            }
        }

        /// <summary>
        /// 生成DB格式key json字符串
        /// </summary>
        /// <param name="keyInfo"></param>
        /// <param name="keydata"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool CreateDBkeyString(KeyInfo keyInfo, out string keydata, out string error)
        {
            keydata = "";
            error = "";
            try
            {
                DBKeysStringFormat DBKeysStringFormat1 = new DBKeysStringFormat { cikey = keyInfo.CI_plus == null ? "" : keyInfo.CI_plus, esn = keyInfo.ESN == null ? "" : keyInfo.ESN, hdcp = keyInfo.HDCP == null ? "" : keyInfo.HDCP, widevine = keyInfo.Widevine == null ? "" : keyInfo.Widevine, hdcp22 = keyInfo.HDCP22 == null ? "" : keyInfo.HDCP22, did = keyInfo.DID == null ? "" : keyInfo.DID, mac = keyInfo.Mac == null ? "" : keyInfo.Mac, attestation = keyInfo.Attestation == null ? "" : keyInfo.Attestation, mgk = keyInfo.MGK == null ? "" : keyInfo.MGK };
                keydata = Newtonsoft.Json.JsonConvert.SerializeObject(DBKeysStringFormat1, Newtonsoft.Json.Formatting.Indented);
                return true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 获取相应json子节点的值
        /// </summary>
        /// <param name="childnodelist"></param>
        public static string JSON_SeleteNode(JToken json, string ReName)
        {
            try
            {
                string result = "";
                //这里6.0版块可以用正则匹配
                var node = json.SelectToken("$.." + ReName);
                if (node != null)
                {
                    //判断节点类型
                    if (node.Type == JTokenType.String || node.Type == JTokenType.Integer || node.Type == JTokenType.Float)
                    {
                        //返回string值
                        result = node.Value<object>().ToString();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 确认是否为有效的url（检测开头是否为http://或者https://）
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static bool HTTPChecker(string Value)
        {
            try
            {
                if ((Value.Substring(0, 7) == "http://") || (Value.Substring(0, 8) == "https://"))
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否能正常访问网络
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool CheckUrlConnection(string url)
        {
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "HEAD";               //设置提交方式可以为＂ｇｅｔ＂，＂ｈｅａｄ＂等
                myRequest.Timeout = 10000;              //设置网页响应时间长度
                myRequest.AllowAutoRedirect = false;//是否允许自动重定向
                myRequest.UseDefaultCredentials = true;
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                myRequest.UseDefaultCredentials = true;//权限设置
                return (myResponse.StatusCode == HttpStatusCode.OK);//返回响应的状态
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 指定目录创建文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void CreateDirectory(string path)
        {
            if (!Directory.Exists(path))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        /// 在线下载抄写模式抄写的上报
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool UploadCopyResult(string content, string url, SQLiteConnection sqliteConn, string order, bool repeatupload, string id, int timeout)
        {
            if (timeout < 5000)
                timeout = 5000;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                Timeout = timeout,
                KeepAlive = false
            };
            item.PostEncoding = Encoding.UTF8;
            item.URL = url;
            item.Postdata = content;
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            HttpResult result = http.GetHtml(item);
            stopwatch.Stop();
            string usingtime = stopwatch.ElapsedMilliseconds.ToString();
            stopwatch.Reset();
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                if (Xmlconfig.ReportXml(result.Html, "response", out string code, out string desc))
                {
                    Log.WriteGetKeyLog("\r\nUpload copy status success:\r\nUsing time:" + usingtime + "ms\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                    return true;
                }
                else
                {
                    CommonMethod.ReportErrormsg("Fail to parse copy result return", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, sqliteConn);
                    Log.WriteErrorLog(code + "Error");
                    if (repeatupload)
                    {
                        SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
                    }
                    return false;
                }
            }
            else
            {
                if (repeatupload)
                    return false;
                if (CommonMethod.HTTPChecker(item.URL))
                    SQLiteHelper.InsertDelayCopyReport(sqliteConn, new object[] { order, item.URL, item.Postdata });
                CommonMethod.ReportErrormsg("Fail to upload copy result", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, sqliteConn);
                return true;
            }
        }

        /// <summary>
        /// 本地DB存储的异常重新上报
        /// </summary>
        /// <param name="reportType"></param>
        /// <param name="reportData"></param>
        /// <param name="sqliteConn"></param>
        /// <returns></returns>
        public static bool ReportErrormsg2(string url, string content, out bool mark)
        {
            mark = false;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = content,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                mark = true;
                Log.WriteGetKeyLog("\r\nReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to ReportErrormsg:\r\n" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                string message = jObject["message"].Value<string>();
                string code = jObject["code"].Value<string>();
                if (code == "1000")
                    return true;
                else
                {
                    Log.WriteErrorLog("\r\nError report return error:\r\n" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse Error report return info," + ex.Message + ":" + ParseText + "\r\nAddress:" + TestMode.errorreportServerurl + "\r\nPostdata:" + content);
                return false;
            }
        }

        /// <summary>
        /// 判断目标字符串是否只有数字和字母
        /// </summary>
        /// <param name="value">目标字符串</param>
        /// <returns></returns>
        public static bool IsNumberAndWord(string value)
        {
            if (value is null)
                return false;
            Regex r = new Regex(@"^[a-zA-Z0-9]+$");
            return r.Match(value).Success;
        }

        public static bool InsertJsonConfig(string node, string key, bool value = false)
        {
            JObject jObject;
            using (StreamReader file = new StreamReader(LocalPath.localpath + "\\Config.json"))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jObject = (JObject)JToken.ReadFrom(reader);
                    jObject[node][key] = value;
                }
            }
            using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
            {
                writer.Write(jObject.ToString());
            }
            return true;
        }

        public static bool AddJsonConfig(string key, object value)
        {
            JObject jObject;
            using (StreamReader file = new StreamReader(LocalPath.localpath + "\\Config.json"))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jObject = (JObject)JToken.ReadFrom(reader);
                    jObject.Add(key, (JToken)value);
                }
            }
            using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
            {
                writer.Write(jObject.ToString());
            }
            return false;
        }

        /// <summary>
        /// 预下载模式抄写的上报
        /// </summary>
        /// <param name="copydate">烧录时间</param>
        /// <returns></returns>
        [Obsolete]
        public static bool UploadPreloadCopyResult(string host, string copydate, string SN, SQLiteConnection localDBNow, SQLiteConnection sqliteConn, bool repeatupload, string id, int timeout)
        {
            string ParseText = "";
            bool status;
            try
            {
                List<PostDateClass> postList = new List<PostDateClass>();
                postList.Add(new PostDateClass("sn", SN));
                postList.Add(new PostDateClass("date", copydate));
                ParseText = FormPost.postFileMessage(host + "/reportlist.do?", postList, out status, timeout);
                if (status)
                {
                    JObject jObject = JObject.Parse(ParseText);
                    string des = CommonMethod.JSON_SeleteNode(jObject, "des");
                    string code = CommonMethod.JSON_SeleteNode(jObject, "code");
                    string data = JSON_SeleteNode(jObject, "data");
                    if (code == "1000")
                    {
                        //更新上报内容
                        if (SQLiteHelper.UpdateReportStatus(localDBNow, SN))
                        {
                            //更新成功
                            Log.WriteGetKeyLog("\r\nUpdateReportStatus success:\r\n" + host + "/reportlist.do?\r\n" + "sn=" + SN + "\r\ndate=" + copydate + "\r\n" + ParseText);
                            return true;
                        }
                        else
                        {
                            Log.WriteErrorLog("\r\nFail to UpdateReportStatus: " + SN);
                            return false;
                        }
                    }
                    else
                    {
                        CommonMethod.ReportErrormsg("Fail to UploadPreloadCopyResult", "Address: " + host + "/reportlist.do?" + "\r\nPostdata: " + "sn=" + SN + "\r\ndate=" + copydate + "\r\n" + ParseText, sqliteConn);
                        Log.WriteErrorLog("\r\nUpdateReportStatus code return error,should be 1000 " + "\r\n" + SN + ":" + ParseText + "\r\nAddress:" + host + "/reportlist.do?" + "\r\nPostdata: " + "sn=" + SN + "\r\ndate=" + copydate);
                        if (repeatupload)
                        {
                            SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
                        }
                        return false;
                    }
                }
                else
                {
                    if (repeatupload)
                        return false;
                    if (CommonMethod.HTTPChecker(host))
                        SQLiteHelper.InsertDelayCopyReport(sqliteConn, new object[] { "preload_mode", host, SN + "@" + copydate });
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse UpdateReportStatus return: " + ex.Message + "\r\n" + SN + ":" + ParseText);
                return false;
            }
        }

        /// <summary>
        /// 预下载模式抄写的批量上报
        /// </summary>
        /// <param name="host"></param>
        /// <param name="postList"></param>
        /// <param name="localDBNow"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="repeatupload"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [Obsolete]
        public static bool UploadPreloadCopyResultList(string host, List<PostDateClass> postList, SQLiteConnection localDBNow, SQLiteConnection sqliteConn, bool repeatupload, string id)
        {
            string ParseText = "";
            bool status;
            try
            {
                ParseText = FormPost.postFileMessage(host + "/reportlist.do?", postList, out status, 30000);
                if (status)
                {
                    JObject jObject = JObject.Parse(ParseText);
                    string des = CommonMethod.JSON_SeleteNode(jObject, "des");
                    string code = CommonMethod.JSON_SeleteNode(jObject, "code");
                    string data = JSON_SeleteNode(jObject, "data");
                    if (code == "1000")
                    {
                        Log.WriteGetKeyLog("UploadPreloadCopyResult successful\r\nAddress: " + host + "/reportlist.do?" + ParseText);
                        return true;
                    }
                    else
                    {
                        CommonMethod.ReportErrormsg("Fail to UploadPreloadCopyResult", "Address: " + host + "/reportlist.do?" + ParseText, sqliteConn);
                        Log.WriteErrorLog("\r\nUpdateReportStatus code return error,should be 1000 " + "\r\n" + ParseText + "\r\nAddress:" + host + "/reportlist.do?");
                        if (repeatupload)
                        {
                            SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
                        }
                        return false;
                    }
                }
                else
                {
                    Log.WriteErrorLog("Fail to UploadPreloadCopyResult\r\nAddress: " + host + "/reportlist.do?" + ParseText);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse UpdateReportStatus return: " + ex.Message + "\r\n" + ParseText);
                return false;
            }
        }

        /// <summary>
        /// byte[]数组到int转换
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int BytelisttoInt(byte[] value)
        {
            Array.Reverse(value);
            int result = 0;
            for (int i = 0; i < value.Length; i++)
            {
                result += value[i] << i * 8;
            }
            return result;
        }

        /// <summary>
        /// int类型到byte[]数组转换
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] InttoBytelist(int value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            if (value == 0)
                return bytes;
            List<byte> list = new List<byte>();
            list.AddRange(bytes);
            while (true)
            {
                if (list[0] != 0)
                    break;
                else
                    list.RemoveAt(0);
            }
            bytes = list.ToArray();
            return bytes;
        }

        /// <summary>
        /// 升级检查
        /// </summary>
        /// <param name="url"></param>
        /// <param name="FactoryNum"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="upmid"></param>
        /// <returns></returns>
        public static bool UpgradeCheck(string url, string FactoryNum, SQLiteConnection sqliteConn, out UpgradeMsgList upmid)
        {
            upmid = new UpgradeMsgList();
            UpgradeCheckInput UpgradeCheckInput1 = new UpgradeCheckInput { appid = "SCBC_Factory_Tools", devicemodel = "SCBC_Factory_Tools", dnum = FactoryNum, ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), type = "pc" };//System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
            string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(UpgradeCheckInput1, Newtonsoft.Json.Formatting.Indented);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = jsonorder,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                       | SecurityProtocolType.Tls
                                       | SecurityProtocolType.Tls11//(SecurityProtocolType)0x300 //Tls11
                                       | SecurityProtocolType.Tls12;//(SecurityProtocolType)0xC00; //Tls12
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nUpgrade check," + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to upgrade check:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to upgrade check", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                upmid.servertime = jObject["servertime"].Value<string>();
                upmid.callid = jObject["callid"].Value<string>();
                upmid.state = jObject["state"].Value<string>();
                upmid.note = jObject["note"].Value<string>();
                upmid.language = jObject["language"].Value<string>();
                upmid.apiversion = jObject["apiversion"].Value<string>();
                upmid.upgrade = new UpgradeMsgList2()
                {
                    type = JSON_SeleteNode(jObject, "type"),
                    appid = JSON_SeleteNode(jObject, "appid"),
                    apptype = JSON_SeleteNode(jObject, "apptype"),
                    version = JSON_SeleteNode(jObject, "version"),
                    verid = JSON_SeleteNode(jObject, "verid"),
                    md5 = JSON_SeleteNode(jObject, "md5"),
                    size = JSON_SeleteNode(jObject, "size"),
                    minicon = JSON_SeleteNode(jObject, "minicon"),
                    midicon = JSON_SeleteNode(jObject, "midicon"),
                    fileurl = JSON_SeleteNode(jObject, "fileurl"),
                    increment = JSON_SeleteNode(jObject, "increment"),
                    appendver = JSON_SeleteNode(jObject, "appendver"),
                    updatetime = JSON_SeleteNode(jObject, "updatetime")
                };
                if (upmid.state == "0000")
                    return true;
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse upgrade check info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to parse upgrade check info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                MessageBox.Show("Fail to parse upgrade check info\r\n " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 升级上报
        /// </summary>
        /// <param name="url"></param>
        /// <param name="FactoryNum"></param>
        /// <param name="Result"></param>
        /// <param name="sqliteConn"></param>
        /// <returns></returns>
        public static bool UpgradeReport(string url, string FactoryNum, string Result, SQLiteConnection sqliteConn)
        {
            UpgradeReportInput UpgradeCheckInput1 = new UpgradeReportInput { appid = "SCBC_Factory_Tools", devmodel = "SCBC_Factory_Tools", dnum = FactoryNum, ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), type = "pc", result = Result };
            string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(UpgradeCheckInput1, Newtonsoft.Json.Formatting.Indented);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = jsonorder,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                       | SecurityProtocolType.Tls
                                       | (SecurityProtocolType)0x300 //Tls11
                                       | (SecurityProtocolType)0xC00; //Tls12
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nUpgrade report," + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to upgrade report:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to upgrade report", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse upgrade report info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to parse upgrade report info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                MessageBox.Show("Fail to parse upgrade report info\r\n " + ex.Message);
                return false;
            }

        }

        /// <summary>
        /// 比较本地文件的MD5值
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="filetype"></param>
        /// <param name="filemd5"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool CompareLocalkey(string filename, string filetype, string filemd5, out string error, out string filefullname)
        {
            error = "";
            filefullname = "";
            try
            {
                string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\" + filename + "\\" + filetype;
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                DirectoryInfo Getkeyfile = new DirectoryInfo(filepath);
                foreach (FileInfo keyfile in Getkeyfile.GetFiles())
                {
                    string FileMD5 = GetMD5.GetMD5HashFromFile(keyfile.Name);
                    if (FileMD5 == filemd5)
                    {
                        Log.WriteGetKeyLog("Check md5file success,file md5:" + FileMD5 + "\r\nfile:" + keyfile.FullName);
                        filefullname = keyfile.FullName;
                        return true;
                    }
                    else
                    {
                        Log.WriteErrorLog("Check md5file error,delete file:" + keyfile.FullName + "\r\nfile md5" + FileMD5);
                        File.Delete(keyfile.FullName);
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 数据MD5核对。当数据头为"MD5="时，key内容比对改为key内容MD5比对
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="md5"></param>
        /// <returns></returns>
        public static bool CompareMD5(byte[] key, byte[] data)
        {
            string strdata = Encoding.ASCII.GetString(data);
            Console.WriteLine(strdata);
            if (strdata.StartsWith("MD5="))
            {
                string md5 = GetMD5.GetMD5Hash(key);
                Console.WriteLine(md5);
                return strdata.Remove(0, 4).Equals(md5);
            }
            return false;
        }

        /// <summary>
        /// 将16进制字符串转为对应字节流写入生成key文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool GetCreateHexkey(string path, string data, out string error)
        {
            error = "";
            try
            {
                string filepath = path + ".bin";
                byte[] bytedata = SerialInit.HexToByte(data);
                //创建一个文件流
                FileStream fs = new FileStream(filepath, FileMode.Create);
                fs.Write(bytedata, 0, bytedata.Length);
                fs.Close();
                Log.WriteGetKeyLog("save key:" + filepath);
                return true;

            }
            catch (Exception ex)
            {
                error = ex.Message;
                Log.WriteErrorLog("save key error:" + error);
                return false;
            }
        }

        /// <summary>
        /// 读取key文件内容转换为16进制字符串
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="data"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool ReadHexFile(string filepath, out string data, out string error)
        {
            data = "";
            error = "";
            try
            {
                using FileStream fskey = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None);
                {
                    using BinaryReader brkey = new BinaryReader(fskey);
                    {
                        data = SerialInit.ByteToHex(brkey.ReadBytes((int)fskey.Length));
                        data = data.Replace(" ", "");
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 账号登录
        /// </summary>
        /// <param name="url"></param>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="pcmac"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="loginOutput1"></param>
        /// <returns></returns>
        public static bool UserLogin(string url, string account, string password, string pcmac, SQLiteConnection sqliteConn, out LoginOutput loginOutput1)
        {
            loginOutput1 = new LoginOutput();
            LoginInput LoginInput1 = new LoginInput { account = account, password = password, mac = pcmac };
            string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(LoginInput1, Newtonsoft.Json.Formatting.Indented);

            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = jsonorder,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;//
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nLogin," + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to login:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to login", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                loginOutput1.msg = jObject["msg"].Value<string>();
                loginOutput1.code = jObject["code"].Value<string>();
                loginOutput1.factoryname = JSON_SeleteNode(jObject, "factoryName");
                loginOutput1.factorynum = JSON_SeleteNode(jObject, "factoryNum");
                if (loginOutput1.code == "1000")
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to login," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to login", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                MessageBox.Show("Fail to parse login return\r\n " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取指定日期，在为一年中为第几周
        /// </summary>
        /// <param name="dt">指定时间</param>
        /// <reutrn>返回第几周</reutrn>
        public static int GetWeekOfYear(DateTime dt)
        {
            GregorianCalendar gc = new GregorianCalendar();
            int weekOfYear = gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            return weekOfYear;
        }

        /// <summary>
        /// 版本号比较：new_version>=old_version
        /// </summary>
        /// <param name="new_version">8.4.0</param>
        /// <param name="old_version">8.3.10</param>
        /// <returns></returns>
        public static bool CompareVersion(string new_version, string old_version)
        {
            try
            {
                if (string.IsNullOrEmpty(new_version) || string.IsNullOrEmpty(old_version))
                    return false;

                Version v_new = new Version(new_version);
                Version v_old = new Version(old_version);
                if (v_new >= v_old)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取白平衡信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="order"></param>
        /// <param name="pcmac"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="WBList"></param>
        /// <returns></returns>
        public static bool GetWhiteBalanceInfo(string url, string order, string pcmac, SQLiteConnection sqliteConn, out WhiteBalanceList WBList)
        {
            WBList = new WhiteBalanceList();
            WhiteBalanceInput WBInput1 = new WhiteBalanceInput { bid = order, mac = pcmac };//"74-27-EA-6E-DA-9F"
            string jsonorder = Newtonsoft.Json.JsonConvert.SerializeObject(WBInput1, Newtonsoft.Json.Formatting.Indented);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl   必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                                         //Encoding = Encoding.Default,
                Method = "post",//URL     可选项 默认为Get
                Postdata = jsonorder,
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.ContentType = "application/json;charset=utf-8";
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            HttpResult result = http.GetHtml(item);
            stopwatch.Stop();
            string usingtime = stopwatch.ElapsedMilliseconds.ToString();
            stopwatch.Reset();
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nGet WB info\r\nUsing time:" + usingtime + "ms\r\n" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to WBinfo:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to WBinfo", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                return false;
            }
            try
            {
                JObject jObject = JObject.Parse(ParseText);
                WBList.message = jObject["message"].Value<string>();
                WBList.code = jObject["code"].Value<string>();
                object a = jObject["obj"];
                if (jObject["obj"].ToString().Length > 0)
                    WBList.whiteBalanceInfo = new WhiteBalanceInfo()
                    {
                        id = JSON_SeleteNode(jObject["obj"], "id"),
                        ordernum = JSON_SeleteNode(jObject["obj"], "ordernum"),
                        hdmirgain = JSON_SeleteNode(jObject["obj"], "hdmirgain"),
                        hdmiggain = JSON_SeleteNode(jObject["obj"], "hdmiggain"),
                        hdmibgain = JSON_SeleteNode(jObject["obj"], "hdmibgain"),
                        nrgain = JSON_SeleteNode(jObject["obj"], "nrgain"),
                        nggain = JSON_SeleteNode(jObject["obj"], "nggain"),
                        nbgain = JSON_SeleteNode(jObject["obj"], "nbgain"),
                        lrgain = JSON_SeleteNode(jObject["obj"], "lrgain"),
                        lggain = JSON_SeleteNode(jObject["obj"], "lggain"),
                        lbgain = JSON_SeleteNode(jObject["obj"], "lbgain"),
                        updatetime = JSON_SeleteNode(jObject["obj"], "updatetime"),
                        createtime = JSON_SeleteNode(jObject["obj"], "createtime"),
                        isdelete = JSON_SeleteNode(jObject["obj"], "isdelete"),
                        isExemption = JSON_SeleteNode(jObject["obj"], "isExemption")
                    };
                if (WBList.code == "1000")
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse WB info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder);
                ReportErrormsg("Fail to parse WB info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + jsonorder, sqliteConn);
                MessageBox.Show("Fail to parse WB info\r\n " + ex.Message);
                return false;
            }
        }

        private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static bool AutoGetKey(string url, string order, string key, string keytype, SQLiteConnection errorDBNow)
        {
            string code;
            string desc;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                KeepAlive = false
            };
            url += "/autogetkey.do?";
            item.URL = url;
            item.Postdata = string.Format("order={0}&key={1}&keytype={2}&mac={3}", order, key, keytype, HttpUtility.UrlEncode(TestMode.MAC));
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nAutoquestKey :\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (Xmlconfig.AutoKeyStatusXml(result.Html, "response", out code, out desc))
                {
                    return true;
                }
                else
                {
                    CommonMethod.ReportErrormsg("Auto get key error", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                    return false;
                }
            }
            else
            {
                CommonMethod.ReportErrormsg("Auto get key error", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                return false;
            }
        }

        public static bool AutoGetKeyStatus(string url, string key, string keytype, SQLiteConnection errorDBNow)
        {
            string code;
            string desc;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                KeepAlive = false
            };
            url += "/autogetkeystatus.do?";
            item.URL = url;
            item.Postdata = string.Format("key={0}&keytype={1}", key, keytype);
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nAutoGetKeyStatus :\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (Xmlconfig.AutoKeyStatusXml(result.Html, "response", out code, out desc))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                CommonMethod.ReportErrormsg("Auto get key status error", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                return false;
            }
        }

        public static bool GetFireTVDsn(string url, string ordernum, string deviceCode, string FSN, string PSN, out string dsn, out string error, SQLiteConnection errorDBNow)
        {
            // 计算函数耗时;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            dsn = "";
            error = "";
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = null,        // 编码格式（utf-8,gb2312,gbk）可选项 默认类会自动识别Encoding = Encoding.Default,
                Method = "GET",         // URL 可选项 默认为Get
                KeepAlive = false
            };

            item.URL = string.Format("{0}/getFiretvDsn.do?ordernum={1}&fsn={2}&psn={3}&deviceCode={4}&mac={5}", url, ordernum, FSN, PSN, deviceCode, HttpUtility.UrlEncode(TestMode.MAC));
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string code;
                string desc;
                Log.WriteGetKeyLog("\r\nGetFireTVDsn :\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (Xmlconfig.GetDSNXml(result.Html, "response", out code, out desc, out dsn))
                {
                    Log.WriteGetKeyLog(string.Format("\r\nDSN= {0}\r\nHttp Get Dsn Elapsed = {1}", dsn, watch.Elapsed.TotalMilliseconds));
                    return true;
                }
                else
                {
                    error = desc;
                    CommonMethod.ReportErrormsg("GetFireTVDsn error", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL, errorDBNow);
                    return false;
                }
            }
            else
            {
                error = "Communication with server failed";
                CommonMethod.ReportErrormsg("GetFireTVDsn error", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL, errorDBNow);
                return false;
            }
        }

        /// <summary>
        /// 导出日本的SN与ACASID到文本中;
        /// </summary>
        /// <param name="ordernum"></param>
        /// <param name="sn"></param>
        /// <param name="acasid"></param>
        public static void ExportSNACASID(string ordernum, string sn, string acasid)
        {
            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\SN-ACAS";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (!lastOrder.Equals(ordernum))
            {
                lastOrder = ordernum;
                ListACASSN.Clear();
            }

            string msg = string.Format("{0};{1}", sn, acasid);
            if (ListACASSN.Contains(msg))
            {
                return;
            }

            ListACASSN.Add(msg);
            string fileName = path + "\\" + ordernum + ".txt";
            var stream = new StreamWriter(fileName, true);
            stream.WriteLine(msg);
            stream.Close();
            stream.Dispose();
        }

        /// <summary>
        /// 是否抄写EDID;
        /// </summary>
        /// <param name="midInfo"></param>
        /// <returns></returns>
        public static bool IsEDIDCopy(MidList midInfo)
        {
            if (midInfo == null || midInfo.keytype == null)
                return false;

            if (!midInfo.keytype.ContainsKey("edid_pid") && !midInfo.keytype.ContainsKey("edid_model_name"))
                return false;

            return true;
        }

        #region 小米FireTV功能模块相关接口;
        public static bool GetMIKey(string url, string sn, out MIKey mikey, out string msg)
        {
            msg = "";
            mikey = new MIKey();
            string strPost = String.Format("{{\"TVSN\":\"{0}\"}}", sn);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                ContentType = "application/json",
                KeepAlive = false
            };

            item.URL = url;
            item.Postdata = strPost;
            HttpResult hResult = http.GetHtml(item);
            if (hResult.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    using (JsonTextReader reader = new JsonTextReader(new StringReader(hResult.Html)))
                    {
                        JObject jObject = (JObject)JToken.ReadFrom(reader);
                        reader.Close();

                        bool bResult = jObject["Result"].Value<bool>();
                        msg = jObject["Error"].Value<string>();
                        JArray jAry = (JArray)JsonConvert.DeserializeObject(jObject["Data"].ToString());
                        if (jAry == null)
                        {
                            Log.WriteErrorLog("GetMIKey Json-null:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                            return false;
                        }

                        if ( jAry.Count > 0 )
                        {
                            mikey = JsonConvert.DeserializeObject<MIKey>(jAry[0].ToString());
                        }

                        if (bResult)
                        {
                            Log.WriteInfoLog("GetMIKey Info:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                            return true;
                        }

                        Log.WriteInfoLog("GetMIKey error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                    }
                }
                catch (Exception e)
                {
                    msg = e.Message;
                    Log.WriteErrorLog("GetMIKey Json-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                }
            }
            else
            {
                msg = hResult.StatusDescription;
                Log.WriteInfoLog("GetMIKey Http-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
            }

            return false;
        }

        public static bool ReportMIKey(string url, ReportMIKey mikey, out string msg)
        {
            msg = "";
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                ContentType = "application/json",
                KeepAlive = false
            };

            item.URL = url;
            item.Postdata = JsonConvert.SerializeObject(mikey); ;
            HttpResult hResult = http.GetHtml(item);
            if (hResult.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    using (JsonTextReader reader = new JsonTextReader(new StringReader(hResult.Html)))
                    {
                        JObject jObject = (JObject)JToken.ReadFrom(reader);
                        reader.Close();

                        bool bResult = jObject["Result"].Value<bool>();
                        msg = jObject["Error"].Value<string>();
                        string data = jObject["Data"].ToString();

                        if (bResult)
                        {
                            Log.WriteInfoLog("ReportMIKey info:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                            return true;
                        }

                        Log.WriteInfoLog("ReportMIKey error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                    }
                }
                catch (Exception e)
                {
                    msg = e.Message;
                    Log.WriteErrorLog("ReportMIKey Json-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                }
            }
            else
            {
                msg = hResult.StatusDescription;
                Log.WriteInfoLog("ReportMIKey Http-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
            }

            return false;
        }
        #endregion
    }

    /// <summary>
    /// CRC32
    /// </summary>
    class CRC32
    {
        //生成CRC32码表
        static uint[] Crc32Table;
        public static void GetCRC32Table()
        {
            uint Crc;
            Crc32Table = new uint[256];
            int i, j;
            for (i = 0; i < 256; i++)
            {
                Crc = (uint)i;
                for (j = 8; j > 0; j--)
                {
                    if ((Crc & 1) == 1)
                        Crc = (Crc >> 1) ^ 0xEDB88320;
                    else
                        Crc >>= 1;
                }
                Crc32Table[i] = Crc;
            }
        }

        public static uint GetCRC32(byte[] bytes)
        {
            GetCRC32Table();
            uint value = 0xffffffff;
            int len = bytes.Length;
            for (int i = 0; i < len; i++)
            {
                value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ bytes[i]];
            }
            return value ^ 0xffffffff;
        }
    }

    /// <summary>
    /// 本地抄写模式方法
    /// </summary>
    public class GetLocalKeyCount
    {
        static string LocalKeyPath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\";
        public static bool GetLocalDidCount(string order, out int num, ref MidList localmidList, SQLiteConnection errorDBNow)
        {
            num = 0;
            try
            {
                string DIDpath = LocalKeyPath + order + "\\DeviceID";
                if (Directory.Exists(DIDpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetDIDfile = new DirectoryInfo(DIDpath);
                    foreach (FileInfo keyfile in GetDIDfile.GetFiles())
                    {
                        string filename = keyfile.FullName;
                        if (keyfile.Name.Contains("Online"))
                        {
                            if (localmidList.host == null)
                            {
                                if (CommonMethod.GetMidInfo(TestMode.serverurl, order, TestMode.MAC, "", "", errorDBNow, out localmidList))
                                {
                                    ;
                                }
                                else
                                {
                                    num = -1;
                                    return true;
                                }
                            }
                            HttpHelper http = new HttpHelper();
                            HttpItem item = new HttpItem()
                            {
                                Encoding = Encoding.Default,
                                Method = "post",
                                ContentType = "application/x-www-form-urlencoded"
                            };
                            string url1 = localmidList.host + "/statdeviceid.do?";
                            item.URL = url1;
                            item.Postdata = "devicetype=tcl_unknown_model";
                            HttpResult result = http.GetHtml(item);
                            if (result.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                Log.WriteGetKeyLog("\r\nGetDeviceID count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                                if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out string code, out string desc, out string count))
                                {
                                    num = Convert.ToInt32(count.Replace(",", ""));
                                    return true;
                                }
                                else
                                {
                                    num = -1;
                                    return true;
                                }
                            }
                            else
                            {
                                num = -1;
                                return true;
                            }
                        }
                        else
                        {
                            num = GetDIDfile.GetFiles().Length;
                            return true;
                        }
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }

        public static bool GetLocalMacCount(string order, out int num, ref MidList localmidList, SQLiteConnection errorDBNow)
        {
            num = 0;
            try
            {
                string MACpath = LocalKeyPath + order + "\\MAC";
                if (Directory.Exists(MACpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetMACfile = new DirectoryInfo(MACpath);
                    foreach (FileInfo keyfile in GetMACfile.GetFiles())
                    {
                        string filename = keyfile.FullName;
                        if (keyfile.Name.Contains("Online"))
                        {
                            if (localmidList.host == null)
                            {
                                if (CommonMethod.GetMidInfo(TestMode.serverurl, order, TestMode.MAC, "", "", errorDBNow, out localmidList))
                                {
                                    ;
                                }
                                else
                                {
                                    num = -1;
                                    return true;
                                }
                            }
                            HttpHelper http = new HttpHelper();
                            HttpItem item = new HttpItem()
                            {
                                Encoding = Encoding.Default,
                                Method = "post",
                                ContentType = "application/x-www-form-urlencoded"
                            };
                            string url1 = localmidList.host + "/statmac.do?";
                            item.URL = url1;
                            item.Postdata = "typeString=" + localmidList.keytype["MAC"];
                            HttpResult result = http.GetHtml(item);
                            if (result.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                Log.WriteGetKeyLog("\r\nGetMac count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                                if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out string code, out string desc, out string count))
                                {
                                    num = Convert.ToInt32(count.Replace(",", ""));
                                    return true;
                                }
                                else
                                {
                                    num = -1;
                                    return true;
                                }
                            }
                            else
                            {
                                num = -1;
                                return true;
                            }

                        }
                        else
                        {
                            num = GetMACfile.GetFiles().Length;
                            return true;
                        }
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalHDCPKEYCount(string order, out int num)
        {
            num = 0;
            try
            {
                string HDCPKEYpath = LocalKeyPath + order + "\\HDCPKEY";
                if (Directory.Exists(HDCPKEYpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetHDCPKEYfile = new DirectoryInfo(HDCPKEYpath);
                    num = GetHDCPKEYfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalHDCPKEY22Count(string order, out int num)
        {
            num = 0;
            try
            {
                string HDCPKEY22path = LocalKeyPath + order + "\\HDCPKEY22";
                if (Directory.Exists(HDCPKEY22path) == false)
                    return false;
                else
                {
                    DirectoryInfo GetHDCPKEY22file = new DirectoryInfo(HDCPKEY22path);
                    num = GetHDCPKEY22file.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalWiDiCount(string order, out int num)
        {
            num = 0;
            try
            {
                string WiDipath = LocalKeyPath + order + "\\WiDi";
                if (Directory.Exists(WiDipath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetWiDifile = new DirectoryInfo(WiDipath);
                    num = GetWiDifile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }

        public static bool GetLocalWidevineCount(string order, out int num)
        {
            num = 0;
            try
            {
                string Widevinepath = LocalKeyPath + order + "\\Widevine";
                if (Directory.Exists(Widevinepath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetWidevinefile = new DirectoryInfo(Widevinepath);
                    num = GetWidevinefile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }

        public static bool GetLocalESNCount(string order, out int num)
        {
            num = 0;
            try
            {
                string ESNpath = LocalKeyPath + order + "\\ESN";
                if (Directory.Exists(ESNpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetESNfile = new DirectoryInfo(ESNpath);
                    num = GetESNfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalMGKCount(string order, out int num)
        {
            num = 0;
            try
            {
                string MGKpath = LocalKeyPath + order + "\\MGK";
                if (Directory.Exists(MGKpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetMGKfile = new DirectoryInfo(MGKpath);
                    num = GetMGKfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalFairplayCount(string order, out int num)
        {
            num = 0;
            try
            {
                string Fairplaypath = LocalKeyPath + order + "\\Fairplay";
                if (Directory.Exists(Fairplaypath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetFairplayfile = new DirectoryInfo(Fairplaypath);
                    num = GetFairplayfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalFolderKeyCount(string order, string keyname, out int num)
        {
            num = 0;
            try
            {
                string Fairplaypath = LocalKeyPath + order + "\\" + keyname;
                if (Directory.Exists(Fairplaypath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetFairplayfile = new DirectoryInfo(Fairplaypath);
                    num = GetFairplayfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }

        public static bool GetLocalAttestationCount(string order, out int num)
        {
            num = 0;
            try
            {
                string Attestationpath = LocalKeyPath + order + "\\Attestation";
                if (Directory.Exists(Attestationpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetAttestationfile = new DirectoryInfo(Attestationpath);
                    num = GetAttestationfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }

        public static bool GetLocalCIKEYCount(string order, out int num)
        {
            num = 0;
            try
            {
                string CIKEYpath = LocalKeyPath + order + "\\CIKEY";
                if (Directory.Exists(CIKEYpath) == false)
                    return false;
                else
                {
                    DirectoryInfo GetCIKEYfile = new DirectoryInfo(CIKEYpath);
                    num = GetCIKEYfile.GetFiles().Length;
                    return true;
                }
            }
            catch (Exception ex)
            {
                num = -1;
                return true;
            }
        }
        public static bool GetLocalStringKeys(string order, string keytype, int filesize, out FileStream fskey, out StreamReader brkey, out string data, out string filename, out string error, SQLiteConnection errorDBNow, ref MidList localmidList, string SN)
        {
            data = "";
            filename = "";
            error = "";
            brkey = null;
            fskey = null;
            try
            {
                string keypath = LocalKeyPath + order + "\\" + keytype;
                if (Directory.Exists(keypath) == false)
                {
                    error = "File not exist";
                    return false;
                }
                else
                {
                    DirectoryInfo Getkeyfile = new DirectoryInfo(keypath);
                    foreach (FileInfo keyfile in Getkeyfile.GetFiles())
                    {
                        filename = keyfile.FullName;
                        if (keyfile.Name.Contains("Online"))
                        {
                            try
                            {
                                if (localmidList.host == null)
                                {
                                    if (CommonMethod.GetMidInfo(TestMode.serverurl, order, TestMode.MAC, "", "", errorDBNow, out localmidList))
                                    {
                                        ;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                                if (keytype == "DeviceID")
                                    localmidList.keytype["DeviceID"] = "devicetype=tcl_unknown_model";
                                else if (keytype == "MAC")
                                    keytype = "MAC";
                                else if (keytype == "HDCPKEY")
                                    keytype = "HDCP_KEY";
                                else if (keytype == "HDCPKEY22")
                                    keytype = "HDCP2.2_KEY";
                                else if (keytype == "ESN")
                                    keytype = "NETFILX_ESN";
                                else if (keytype == "Widevine")
                                    keytype = "Widevine_KEY";
                                else if (keytype == "WiDi")
                                    keytype = "WiDi";
                                else if (keytype == "CIKEY")
                                    keytype = "CI_PLUS_KEY";
                                if (CommonMethod.GetKeys(localmidList.host, keytype, SN, localmidList.keytype[keytype], errorDBNow, out string did, out error, order, out string md5))
                                {
                                    data = did;
                                    Log.WriteGetKeyLog("\r\n" + keytype + "= " + data);
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                                return false;
                            }
                        }
                        else
                        {
                            try
                            {
                                fskey = new FileStream(keyfile.FullName.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                                {
                                    brkey = new StreamReader(fskey);
                                    {
                                        if (fskey.Length == filesize || filesize == -1)
                                        {
                                            data = brkey.ReadToEnd();
                                            return true;
                                        }
                                        else
                                        {
                                            error = "File size error.\r\nFilename:" + keyfile.Name + "\r\nFilesize:" + fskey.Length.ToString();
                                            return false;
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                ;
                            }
                        }
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }
        public static bool GetLocalHexKeys(string order, string keytype, int filesize, out FileStream fskey, out BinaryReader brkey, out string data, out string filename, out string error, SQLiteConnection errorDBNow, ref MidList localmidList, string SN)
        {
            data = "";
            filename = "";
            error = "";
            brkey = null;
            fskey = null;
            try
            {
                string keypath = LocalKeyPath + order + "\\" + keytype;
                if (Directory.Exists(keypath) == false)
                {
                    error = "File not exist";
                    return false;
                }
                else
                {
                    DirectoryInfo Getkeyfile = new DirectoryInfo(keypath);
                    foreach (FileInfo keyfile in Getkeyfile.GetFiles())
                    {
                        filename = keyfile.FullName;
                        if (keyfile.Name.Contains("Online"))
                        {
                            try
                            {
                                if (localmidList.host == null)
                                {
                                    if (CommonMethod.GetMidInfo(TestMode.serverurl, order, TestMode.MAC, "", "", errorDBNow, out localmidList))
                                    {
                                        ;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                                if (keytype == "DeviceID")
                                    localmidList.keytype["DeviceID"] = "devicetype=tcl_unknown_model";
                                else if (keytype == "MAC")
                                    keytype = "MAC";
                                else if (keytype == "HDCPKEY")
                                    keytype = "HDCP_KEY";
                                else if (keytype == "HDCPKEY22")
                                    keytype = "HDCP2.2_KEY";
                                else if (keytype == "ESN")
                                    keytype = "NETFILX_ESN";
                                else if (keytype == "Widevine")
                                    keytype = "Widevine_KEY";
                                else if (keytype == "WiDi")
                                    keytype = "WiDi";
                                else if (keytype == "CIKEY")
                                    keytype = "CI_PLUS_KEY";
                                else if (keytype == "MGK")
                                    keytype = "MGK_KEY";
                                else if (keytype == "Attestation")
                                    keytype = "Attestation";
                                else if (keytype == "Fairplay")
                                    keytype = "Fairplay_KEY";
                                if (CommonMethod.GetKeys(localmidList.host, keytype, SN, localmidList.keytype[keytype], errorDBNow, out string did, out error, order, out string md5))
                                {
                                    data = did;
                                    Log.WriteGetKeyLog("\r\n" + keytype + "= " + data);
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                                return false;
                            }
                        }
                        else
                        {
                            try
                            {
                                fskey = new FileStream(keyfile.FullName.ToString(), FileMode.Open, FileAccess.Read, FileShare.None);
                                {
                                    brkey = new BinaryReader(fskey);
                                    {
                                        if (fskey.Length == filesize || filesize == -1)
                                        {
                                            data = SerialInit.ByteToHex(brkey.ReadBytes((int)fskey.Length));
                                            data = data.Replace(" ", "");
                                            return true;
                                        }
                                        else
                                        {
                                            error = "File size error.\r\nFilename: " + keyfile.Name + "\r\nFilesize: " + fskey.Length.ToString();
                                            return false;
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                ;
                            }
                        }
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }
        public static bool DeleteLocalKeys(ArrayList filelist, ArrayList Stream, ArrayList Reader)
        {
            try
            {
                if (filelist.Count == Reader.Count)
                {
                    for (int i = 0; i < filelist.Count; i++)
                    {
                        if (filelist[i].ToString().Contains("DeviceID"))
                            ((StreamReader)Reader[i]).Dispose();
                        else
                            ((BinaryReader)Reader[i]).Dispose();
                        ((FileStream)Stream[i]).Dispose();
                        File.Delete(filelist[i].ToString());
                    }
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                for (int i = 0; i < Reader.Count; i++)
                {
                    if (filelist[i].ToString().Contains("DeviceID"))
                        ((StreamReader)Reader[i]).Dispose();
                    else
                        ((BinaryReader)Reader[i]).Dispose();
                    ((FileStream)Stream[i]).Dispose();
                }
                return false;
            }
        }

        public static bool UnlockLocalKeys(ArrayList filelist, ArrayList Stream, ArrayList Reader)
        {
            for (int i = 0; i < Reader.Count; i++)
            {
                if (filelist[i].ToString().Contains("DeviceID"))
                    ((StreamReader)Reader[i]).Dispose();
                else
                    ((BinaryReader)Reader[i]).Dispose();
                ((FileStream)Stream[i]).Dispose();
            }
            return true;
        }
    }

    /// <summary>
    /// 本地缓存记录
    /// </summary>
    public class LocalTxtRecord
    {
        public static bool LocalRecord(string record, string name)
        {
            try
            {
                string order = name + ".txt";
                if (File.Exists(@order))
                {
                    FileStream fs = new FileStream(@order, FileMode.Append);
                    byte[] data = System.Text.Encoding.Default.GetBytes("\r\n" + record);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Close();
                }
                else
                {
                    FileStream fs = new FileStream(@order, FileMode.Create);
                    byte[] data = System.Text.Encoding.Default.GetBytes(record);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
