using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using SXLibrary;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using HttpHelper = SufeiUtil.HttpHelper;

namespace MOKA_Factory_Tools
{
    internal class V2Method
    {
#if DEBUG
        public static void Test()
        {
            MidList mid;
            bool bRet = GetMidInfo("http://test.scbc.qhmoka.com/scbc-server/clientType/getMessage.do", "TEST_WJF", "04-D4-C4-EE-6B-CD", null, out mid);
            if (bRet)
            {
                List<KeyType> key2Write;
                string msg;
                KeyInfo keys = new KeyInfo();
                bRet = GetMidKey(mid.host, "SN0321-test9999", "TEST_WJF", "20220321APSN9999", "BBB", null, null, ref keys, out msg);

                List<MidAddress> midlist; 
                GetOfflineData(mid.host, "TEST_WJF", null, out midlist);

                if (bRet)
                {
                    Action<KeyData> SetEnable = (keydata) =>
                    {
                        if (keydata != null && keydata.data.Length > 0)
                            keydata.enable = true;
                    };

                    SetEnable(keys.Mac);
                    SetEnable(keys.HDCP);
                    SetEnable(keys.DID);
                    SetEnable(keys.HDCP22);
                    SetEnable(keys.CI_plus);
                    SetEnable(keys.Playready);

                    ReportOnlineData(mid.host, "TEST_WJF", GetReportJson("TEST_WJF", "SN0321-test9999", false, ref keys), null, false, "", 1000);

                    ReportOfflineData(mid.host, "2022-07-18 14:40:42", "SN0321-test9999", null, null, false, "");
                }
            }
        }
#endif

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="order"></param>
        /// <param name="pcmac"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="mid"></param>
        /// <returns></returns>
        public static bool GetMidInfo(string url, string order, string pcmac, SQLiteConnection sqliteConn, out MidList mid)
        {
            mid = new MidList();
            string postData = string.Format("{{\"bid\":\"{0}\",\"mac\":\"{1}\"}}", order, pcmac);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL这里都是测试URl必需项
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）可选项 默认类会自动识别//Encoding = Encoding.Default,
                Method = "post",
                Postdata = postData,
                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:" + postData);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to GetMidInfo:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + postData);
                CommonMethod.ReportErrormsg("Fail to GetMidInfo", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + postData, 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 = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "id").Trim(),
                        ordernum = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "ordernum").Trim(),
                        brand = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "brand").Trim(),
                        region = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "region").Trim(),
                        oemmodel = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "oemmodel").Trim(),
                        supporturl = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "supporturl").Trim(),
                        supportphone = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "supportphone").Trim(),
                        productiondate = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "productiondate").Trim(),
                        remotetype = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "remotetype").Trim(),
                        updatetime = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "updatetime").Trim(),
                        createtime = CommonMethod.JSON_SeleteNode(jObject["rokuCustomer"], "createtime").Trim(),
                        isdelete = CommonMethod.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 (mid.code == "1000")
                    return true;
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to parse MID info," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + postData);
                CommonMethod.ReportErrormsg("Fail to parse MID info", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + postData, sqliteConn);
                MessageBox.Show("Fail to parse MID info\r\n " + ex.Message);
            }

            return false;
        }

        public static bool GetMidKey(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;
            bool result = false;

            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                ContentType = "application/json",
                KeepAlive = false
            };

            // 计算函数耗时;
            Stopwatch watch = new Stopwatch();
            watch.Start();

            item.URL = url + "/bind/order";
            item.Postdata = string.Format("{{\"orderNum\":\"{0}\",\"sn\":\"{1}\",\"psn\":\"{2}\",\"orderCode\":\"{3}\",\"skipKey\":{4}}}", order, sn, psn, firetv_device_code, key2Write == null ? "[]" : JsonConvert.SerializeObject(key2Write).ToString());
            HttpResult httpResult = http.GetHtml(item);
            if (httpResult.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    JObject jObject = JObject.Parse(httpResult.Html);
                    msg = CommonMethod.JSON_SeleteNode(jObject, "msg");
                    code = CommonMethod.JSON_SeleteNode(jObject, "code");
                    if (code == "0")
                    {
                        Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jObject["data"].ToString());
                        if (data != null)
                        {
                            Func<string, string, bool> CheckMD5 = (data, md5) =>
                            {
                                if (data == null)
                                    return true;

                                if (!GetMD5.GetStrMd5(data).Equals(md5, StringComparison.OrdinalIgnoreCase))
                                    return false;

                                return true;
                            };

                            if (data.ContainsKey("mac") && data.ContainsKey("mac_md5"))
                            {
                                keys.Mac.data = data["mac"];
                                keys.Mac.md5 = data["mac_md5"];

                                if (!CheckMD5(keys.Mac.data, keys.Mac.md5))
                                {
                                    msg = string.Format("Mac Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Mac.data, keys.Mac.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("btMac") && data.ContainsKey("btMac_md5"))
                            {
                                keys.BT_MAC.data = data["btMac"];
                                keys.BT_MAC.md5 = data["btMac_md5"];

                                if (!CheckMD5(keys.BT_MAC.data, keys.BT_MAC.md5))
                                {
                                    msg = string.Format("BT_MAC Key Value md5 Is Incorrect: data={0}, md5={1}", keys.BT_MAC.data, keys.BT_MAC.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("wifiMac") && data.ContainsKey("wifiMac_md5"))
                            {
                                keys.WiFi_MAC.data = data["wifiMac"];
                                keys.WiFi_MAC.md5 = data["wifiMac_md5"];

                                if (!CheckMD5(keys.WiFi_MAC.data, keys.WiFi_MAC.md5))
                                {
                                    msg = string.Format("WiFi_MAC Key Value md5 Is Incorrect: data={0}, md5={1}", keys.WiFi_MAC.data, keys.WiFi_MAC.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("deviceid") && data.ContainsKey("deviceid_md5"))
                            {
                                keys.DID.data = data["deviceid"];
                                keys.DID.md5 = data["deviceid_md5"];

                                if (!CheckMD5(keys.DID.data, keys.DID.md5))
                                {
                                    msg = string.Format("DID Key Value md5 Is Incorrect: data={0}, md5={1}", keys.DID.data, keys.DID.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("hdcp") && data.ContainsKey("hdcp_md5"))
                            {
                                keys.HDCP.data = data["hdcp"];
                                keys.HDCP.md5 = data["hdcp_md5"];

                                if (!CheckMD5(keys.HDCP.data, keys.HDCP.md5))
                                {
                                    msg = string.Format("HDCP Key Value md5 Is Incorrect: data={0}, md5={1}", keys.HDCP.data, keys.HDCP.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("hdcp2") && data.ContainsKey("hdcp2_md5"))
                            {
                                keys.HDCP22.data = data["hdcp2"];
                                keys.HDCP22.md5 = data["hdcp2_md5"];

                                if (!CheckMD5(keys.HDCP22.data, keys.HDCP22.md5))
                                {
                                    msg = string.Format("HDCP22 Key Value md5 Is Incorrect: data={0}, md5={1}", keys.HDCP22.data, keys.HDCP22.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("ci") && data.ContainsKey("ci_md5"))
                            {
                                keys.CI_plus.data = data["ci"];
                                keys.CI_plus.md5 = data["ci_md5"];

                                if (!CheckMD5(keys.CI_plus.data, keys.CI_plus.md5))
                                {
                                    msg = string.Format("CI_plus Key Value md5 Is Incorrect: data={0}, md5={1}", keys.CI_plus.data, keys.CI_plus.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("ecp") && data.ContainsKey("ecp_md5"))
                            {
                                keys.ECP.data = data["ecp"];
                                keys.ECP.md5 = data["ecp_md5"];

                                if (!CheckMD5(keys.ECP.data, keys.ECP.md5))
                                {
                                    msg = string.Format("ECP Key Value md5 Is Incorrect: data={0}, md5={1}", keys.ECP.data, keys.ECP.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("acas") && data.ContainsKey("acas_md5"))
                            {
                                keys.ACASKey_Data.data = data["acas"];
                                keys.ACASKey_Data.md5 = data["acas_md5"];

                                if (!CheckMD5(keys.ACASKey_Data.data, keys.ACASKey_Data.md5))
                                {
                                    msg = string.Format("ACASKey_Data Key Value md5 Is Incorrect: data={0}, md5={1}", keys.ACASKey_Data.data, keys.ACASKey_Data.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("lek") && data.ContainsKey("lek_md5"))
                            {
                                keys.LEK.data = data["lek"];
                                keys.LEK.md5 = data["lek_md5"];

                                if (!CheckMD5(keys.LEK.data, keys.LEK.md5))
                                {
                                    msg = string.Format("LEK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.LEK.data, keys.LEK.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("pek") && data.ContainsKey("pek_md5"))
                            {
                                keys.PEK.data = data["pek"];
                                keys.PEK.md5 = data["pek_md5"];

                                if (!CheckMD5(keys.PEK.data, keys.PEK.md5))
                                {
                                    msg = string.Format("PEK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.PEK.data, keys.PEK.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("playready") && data.ContainsKey("playready_md5"))
                            {
                                keys.Playready.data = data["playready"];
                                keys.Playready.md5 = data["playready_md5"];

                                if (!CheckMD5(keys.Playready.data, keys.Playready.md5))
                                {
                                    msg = string.Format("Playready Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Playready.data, keys.Playready.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("netfilx") && data.ContainsKey("netfilx_md5"))
                            {
                                keys.ESN.data = data["netfilx"];
                                keys.ESN.md5 = data["netfilx_md5"];

                                if (!CheckMD5(keys.ESN.data, keys.ESN.md5))
                                {
                                    msg = string.Format("ESN Key Value md5 Is Incorrect: data={0}, md5={1}", keys.ESN.data, keys.ESN.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("hash") && data.ContainsKey("hash_md5"))
                            {
                                keys.Hashkey.data = data["hash"];
                                keys.Hashkey.md5 = data["hash_md5"];

                                if (!CheckMD5(keys.Hashkey.data, keys.Hashkey.md5))
                                {
                                    msg = string.Format("Hashkey Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Hashkey.data, keys.Hashkey.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("mgk") && data.ContainsKey("mgk_md5"))
                            {
                                keys.MGK.data = data["mgk"];
                                keys.MGK.md5 = data["mgk_md5"];

                                if (!CheckMD5(keys.MGK.data, keys.MGK.md5))
                                {
                                    msg = string.Format("MGK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.MGK.data, keys.MGK.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("youtube") && data.ContainsKey("youtube_md5"))
                            {
                                keys.YouTube_KEY.data = data["youtube"];
                                keys.YouTube_KEY.md5 = data["youtube_md5"];

                                if (!CheckMD5(keys.YouTube_KEY.data, keys.YouTube_KEY.md5))
                                {
                                    msg = string.Format("YouTube_KEY Key Value md5 Is Incorrect: data={0}, md5={1}", keys.YouTube_KEY.data, keys.YouTube_KEY.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("fairplay") && data.ContainsKey("fairplay_md5"))
                            {
                                keys.Fairplay.data = data["fairplay"];
                                keys.Fairplay.md5 = data["fairplay_md5"];

                                if (!CheckMD5(keys.Fairplay.data, keys.Fairplay.md5))
                                {
                                    msg = string.Format("Fairplay Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Fairplay.data, keys.Fairplay.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("widevine") && data.ContainsKey("widevine_md5"))
                            {
                                keys.Widevine.data = data["widevine"];
                                keys.Widevine.md5 = data["widevine_md5"];

                                if (!CheckMD5(keys.Widevine.data, keys.Widevine.md5))
                                {
                                    msg = string.Format("Widevine Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Widevine.data, keys.Widevine.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("attention") && data.ContainsKey("attention_md5"))
                            {
                                keys.Attestation.data = data["attention"];
                                keys.Attestation.md5 = data["attention_md5"];

                                if (!CheckMD5(keys.Attestation.data, keys.Attestation.md5))
                                {
                                    msg = string.Format("Attestation Key Value md5 Is Incorrect: data={0}, md5={1}", keys.Attestation.data, keys.Attestation.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("dsn") && data.ContainsKey("dsn_md5"))
                            {
                                keys.DSN.data = data["dsn"];
                                keys.DSN.md5 = data["dsn_md5"];

                                if (!CheckMD5(keys.DSN.data, keys.DSN.md5))
                                {
                                    msg = string.Format("DSN Key Value md5 Is Incorrect: data={0}, md5={1}", keys.DSN.data, keys.DSN.md5);
                                    goto end;
                                }
                            }

                            if (data.ContainsKey("dak") && data.ContainsKey("dak_md5"))
                            {
                                keys.DAK.data = data["dak"];
                                keys.DAK.md5 = data["dak_md5"];

                                if (!CheckMD5(keys.DAK.data, keys.DAK.md5))
                                {
                                    msg = string.Format("DAK Key Value md5 Is Incorrect: data={0}, md5={1}", keys.DAK.data, keys.DAK.md5);
                                    goto end;
                                }
                            }

                            result = true;
                        }
                    }
                }
                catch
                {
                    msg = "解析Json失败";
                }
            }

        end:
            watch.Stop();
            Log.WriteInfoLog(string.Format("[GetIDMKeys] order={0},sn={1},Elapsed={2} GetKeys={3}", order, sn, watch.Elapsed.TotalMilliseconds, result ? "成功" : "失败"));

            if (!result)
                CommonMethod.ReportErrormsg("Fail to GetIDMKeys ", msg + "\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + httpResult.Html, connection);

            return result;
        }

        public static string GetReportJson(string order, string sn, bool isNodid, ref KeyInfo keyinfo)
        {
            Func<string, string, JObject, bool> AddJsonItem = (name, value, jobj) =>
            {
                if (name == null || name.Length == 0)
                    return false;

                if (value == null || value.Length == 0)
                    return false;

                if (jobj == null)
                    return false;

                jobj.Add(name, (JToken)value);

                return true;
            };

            Func<KeyData, JObject, bool> AddKeyJson = (keydata, jobj) =>
            {
                if (keydata == null || jobj == null || keydata.data == null)
                    return false;

                if (keydata.keyfrom == KEY_FROM.FROM_IDM && keydata.enable)
                {
                    jobj.Add(keydata.name, (JToken)keydata.data);
                }

                return true;
            };

            try
            {
                JObject postJson = new JObject();
                AddJsonItem("ordernum", order, postJson);
                AddJsonItem("sn", sn, postJson);
                AddJsonItem("nodid", isNodid.ToString(), postJson);

                if (keyinfo != null)
                {
                    AddKeyJson(keyinfo.MGK, postJson);
                    AddKeyJson(keyinfo.Mac, postJson);
                    AddKeyJson(keyinfo.HDCP, postJson);
                    AddKeyJson(keyinfo.HDCP22, postJson);
                    AddKeyJson(keyinfo.ESN, postJson);
                    //AddKeyJson(keyinfo.WiDi, postJson);
                    AddKeyJson(keyinfo.Widevine, postJson);
                    AddKeyJson(keyinfo.CI_plus, postJson);
                    AddKeyJson(keyinfo.Attestation, postJson);
                    AddKeyJson(keyinfo.MGK, postJson);
                    AddKeyJson(keyinfo.Fairplay, postJson);
                    AddKeyJson(keyinfo.DSN, postJson);
                    AddKeyJson(keyinfo.WiFi_MAC, postJson);
                    AddKeyJson(keyinfo.BT_MAC, postJson);
                    AddKeyJson(keyinfo.LEK, postJson);
                    AddKeyJson(keyinfo.PEK, postJson);
                    AddKeyJson(keyinfo.Playready, postJson);
                    AddKeyJson(keyinfo.Hashkey, postJson);
                    AddKeyJson(keyinfo.ECP, postJson);
                    AddKeyJson(keyinfo.YouTube_KEY, postJson);
                    AddKeyJson(keyinfo.EDIDPid, postJson);
                    AddKeyJson(keyinfo.EDIDModelName, postJson);
                    AddKeyJson(keyinfo.ACASKey_Data, postJson);
                    //AddKeyJson(keyinfo.ACASKey_Tool, postJson);//内置
                    AddKeyJson(keyinfo.DAK, postJson);
                    //AddKeyJson(keyinfo.FVP, postJson);
                }

                return postJson.ToString();
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to GetReportJson," + ex.Message + ":" + "\r\nOrder:" + order + "\r\nSN:" + sn);
            }

            return "";
        }

        /// <summary>
        /// 在线抄写完成上报 Key
        /// </summary>
        /// <param name="url"></param>
        /// <param name="order"></param>
        /// <param name="sn"></param>
        /// <param name="isNodid"></param>
        /// <param name="keyinfo"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool ReportOnlineData(string url, string order, string postData, SQLiteConnection sqliteConn, bool repeatupload, string id, int timeout)
        {
            if (timeout < 5000)
                timeout = 5000;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,//编码格式（utf-8,gb2312,gbk）可选项 默认类会自动识别//Encoding = Encoding.Default,
                Method = "post",
                Postdata = postData,
                PostEncoding = Encoding.UTF8,
                Timeout = timeout,
                KeepAlive = false
            };
            item.URL = url + "/reportData/report";
            item.ContentType = "application/json;charset=utf-8";
            Stopwatch stopwatch = new 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\nReportOnlineData info\r\nUsing time:" + usingtime + "ms\r\n" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata);
                try
                {
                    JObject jObject = JObject.Parse(ParseText);
                    string msg = jObject["message"].Value<string>();
                    string code = jObject["code"].Value<string>();

                    if (code == "0")
                        return true;                   
                }
                catch (Exception ex)
                {
                    Log.WriteErrorLog("\r\nFail to ReportOnlineData," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata);
                    CommonMethod.ReportErrormsg("Fail to ReportOnlineData", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata, sqliteConn);
                }

                if (repeatupload)
                {// 删除记录;
                    SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
                }
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to ReportOnlineData:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata);
                if (!repeatupload)
                {
                    if (CommonMethod.HTTPChecker(item.URL))
                        SQLiteHelper.InsertDelayCopyReport(sqliteConn, new object[] { order, item.URL, item.Postdata });
                }
                CommonMethod.ReportErrormsg("Fail to ReportOnlineData", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata, sqliteConn);
            }            

            return false;
        }

        //reportData/reportList
        /// <summary>
        /// 离线抄写上报
        /// </summary>
        /// <param name="url"></param>
        /// <param name="copydate"></param>
        /// <param name="SN"></param>
        /// <param name="localDBNow"></param>
        /// <param name="sqliteConn"></param>
        /// <param name="repeatupload"></param>
        /// <param name="id"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static bool ReportOfflineData(string url, string copydate, string SN, SQLiteConnection localDBNow, SQLiteConnection sqliteConn, bool repeatupload, string id)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                Postdata = string.Format("{{\"sn\":\"{0}\",\"date\":\"{1}\"}}", SN, copydate),
                PostEncoding = Encoding.UTF8,
                KeepAlive = false
            };
            item.URL = url + "/reportData/reportList";
            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\nReportOfflineData info\r\nUsing time:" + usingtime + "ms\r\n" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata);
            }
            else
            {
                Log.WriteErrorLog("\r\nFail to ReportOfflineData:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to ReportOfflineData", result.StatusDescription + result.Html + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata, sqliteConn);

                if (repeatupload)
                    return false;

                if (CommonMethod.HTTPChecker(url))
                    SQLiteHelper.InsertDelayCopyReport(sqliteConn, new object[] { "preload_mode", url, SN + "@" + copydate });

                return false;
            }

            try
            {
                JObject jObject = JObject.Parse(ParseText);
                string msg = jObject["msg"].Value<string>();
                string code = jObject["code"].Value<string>();

                if (code == "0")
                {
                    //更新上报内容
                    if (SQLiteHelper.UpdateReportStatus(localDBNow, SN))
                    {
                        //更新成功
                        Log.WriteGetKeyLog("\r\nUpdateReportStatus success:\r\n" + url + "/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: " + url + "/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:" + url + "/reportlist.do?" + "\r\nPostdata: " + "sn=" + SN + "\r\ndate=" + copydate);
                    if (repeatupload)
                    {
                        SQLiteHelper.DeleteDelayCopyReport(sqliteConn, id);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to ReportOfflineData," + ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to ReportOfflineData", ex.Message + ":" + ParseText + "\r\nAddress:" + url + "\r\nPostdata:" + item.Postdata, sqliteConn);
            }

            return false;
        }

        public static bool GetOfflineData(string url, string order, SQLiteConnection sqliteConn, out List<MidAddress> midAddressList)
        {
            midAddressList = new List<MidAddress>();
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                Postdata = string.Format("{{\"ordernum\":\"{0}\",\"mac\":\"{1}\"}}", order, HttpUtility.UrlEncode(TestMode.MAC)),
                KeepAlive = false
            };

            item.URL = url + "/offline/getofflinelist";
            item.ContentType = "application/json;charset=utf-8";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {

            }
            else
            {
                Log.WriteErrorLog("\r\nFail to GetOfflineData:" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to GetOfflineData", 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 = CommonMethod.JSON_SeleteNode(jObject, "des"),
                            code = CommonMethod.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 = url
                        });
                    }

                    Log.WriteGetKeyLog("\r\nGet GetOfflineData success:" + "\r\n" + result.Html + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                    return true;
                }

                Log.WriteErrorLog("\r\nFail to GetOfflineData," + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog("\r\nFail to GetOfflineData," + ex.Message + ":" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata);
                CommonMethod.ReportErrormsg("Fail to GetOfflineData", ex.Message + "\r\n" + ParseText + "\r\nAddress:" + item.URL + "\r\nPostdata:" + item.Postdata, sqliteConn);
                MessageBox.Show("Fail to GetOfflineData info\r\n " + ex.Message);
                return false;
            }

            return false;
        }

        public static bool ReportDownloadStatus(string url, string order, SQLiteConnection sqliteConn)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = null,
                Method = "post",
                Postdata = string.Format("{{\"ordernum\":\"{0}\"}}", order),
                KeepAlive = false
            };

            item.URL = url += "/offline/getreportofflinesn";
            item.ContentType = "application/json;charset=utf-8";
            HttpResult result = http.GetHtml(item);
            string ParseText = result.Html;
            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Log.WriteErrorLog("\r\nFail to report download status:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/offline/getreportofflinesn" + "\r\nPostdata:" + ("ordernum=" + order));
                CommonMethod.ReportErrormsg("Fail to report download status", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/offline/getreportofflinesn" + "\r\nPostdata:" + ("ordernum=" + order), sqliteConn);
                return false;
            }

            try
            {
                JObject jObject = JObject.Parse(ParseText);
                string msg = CommonMethod.JSON_SeleteNode(jObject, "msg");
                string code = CommonMethod.JSON_SeleteNode(jObject, "code");
  
                if (code != "0")
                {
                    Log.WriteErrorLog("\r\nError report download status,should be 1000:" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/offline/getreportofflinesn" + "\r\nPostdata:" + ("ordernum=" + order));
                    CommonMethod.ReportErrormsg("Error download status code return", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/offline/getreportofflinesn" + "\r\nPostdata:" + ("ordernum=" + order), sqliteConn);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Log.WriteErrorLog("\r\n" + ex.Message + ":" + result.StatusDescription + result.Html + "\r\nAddress:" + url + "/offline/getreportofflinesn" + "\r\nPostdata:" + ("ordernum=" + order));
                CommonMethod.ReportErrormsg("Error parse download status return", result.StatusDescription + result.Html + "\r\nAddress:" + url + "/offline/getreportofflinesn" + "\r\nPostdata:" + ("ordernum=" + order), sqliteConn);
                return false;
            }

            return true;
        }
    };
};
