using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using SXLibrary;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MOKA_Factory_Tools
{
    internal class GMethod
    {
        private static Dictionary<string, string> LastKaylaOrderInfo = new Dictionary<string, string>();

        public static bool GetMaInfo(string sn, out MaInfo maInfo, SQLiteConnection errorDBNow)
        {
            string desc;
            maInfo = null;
            string strPost = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                            "<soap:Body>" +
                            "<GetMaInfo xmlns=\"http://tempuri.org/\">" +
                            "<sn>" + sn + "</sn>" +
                            "</GetMaInfo>" +
                            "</soap:Body>" +
                            "</soap:Envelope>";

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

            item.URL = "http://smes-prd-app01.tclking.com:9002/SAPService.asmx";
            item.Postdata = strPost;
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nGetMaInfo :\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (!Xmlconfig.GetMaInfoXml(result.Html, out maInfo, out desc))
                {
                    Log.WriteGetKeyLog("GetMaInfo error:" + desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                    return false;
                }
            }
            else
            {
                Log.WriteGetKeyLog("GetMaInfo error:" + result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 上报数据抄写结果到MES系统中;
        /// </summary>
        /// <param name="fsn"></param>
        /// <param name="dsn"></param>
        /// <param name="dateTime">抄写时间</param>
        /// <param name="result">抄写结果</param>
        /// <param name="msg">如果上报失败，此参数为失败的描述信息</param>
        /// <returns></returns>
        public static bool ReportDataBurningResultToMES(string fsn, string dsn, string result, string dateTime, SQLiteConnection errorDBNow, out string msg, out string returnObject)
        {
            msg = "";
            returnObject = "";
            string strPost = string.Format("{{\"FSN\":\"{0}\",\"DSN\":\"{1}\",\"DataCopy\":\"{2}\",\"UPDATETIME\":\"{3}\"}}", fsn, dsn, result, dateTime);
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                ContentType = "application/json",
                KeepAlive = false
            };

            // 测试地址;
            item.URL = "http://smes-app-prod.tclking.com/FireTVApi/api/SMES/RecordKey";
            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["EroMsg"].Value<string>();
                        if (jObject["returnObject"] != null)
                            returnObject = jObject["returnObject"].ToString();
                        Log.WriteInfoLog("nReportDataBurningResultToMES:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                        return bResult;
                    }
                }
                catch (Exception e)
                {
                    msg = e.Message;
                    Log.WriteErrorLog("ReportDataBurningResultToMES Json-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                }
            }
            else
            {
                msg = hResult.StatusDescription;
                Log.WriteInfoLog("ReportDataBurningResultToMES Http-error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
            }

            // 没有进行数据库查重:惹数据已添加过,同一次FSN抄写多次失败后导致多条记录。
            SQLiteHelper.InsertDelayErrorReport(errorDBNow, new object[] { item.URL, item.Postdata });

            return false;
        }

        /// <summary>
        /// 上传本地数据库失败的日志，重新上传;
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strPost"></param>
        /// <param name="mark"></param>
        /// <returns></returns>
        public static bool ReportDataBurningResultToMES(string url, string strPost, out bool mark)
        {
            // 表示是否上传成功;
            mark = false;
            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();

                        mark = jObject["Result"].Value<bool>();
                        Log.WriteInfoLog("nReportDataBurningResultToMES:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                        return true;
                    }
                }
                catch (Exception)
                {
                    Log.WriteErrorLog("ReportDataBurningResultToMES error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
                    throw;
                }
            }
            else
            {
                Log.WriteInfoLog("ReportDataBurningResultToMES error:" + hResult.StatusDescription + "\r\n" + hResult.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata);
            }

            return false;
        }

        /// <summary>
        /// 通过SN获取订单类型
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        public static bool GetOrderTypeFromSN(string sn, out string result, out string msg)
        {
            msg = "";
            result = "";
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.UTF8,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                KeepAlive = false
            };

            // 测试地址;
            item.URL = "http://smes-app-prod.tclking.com/FireTVApi/api/SMES/getOrderProductStatus?sn=" + sn;
            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["EroMsg"].Value<string>();
                        string returnObject = jObject["returnObject"].ToString();

                        if (bResult)
                        {
                            if (returnObject.Contains("量产"))
                                result = "量产";
                            else if (returnObject.Contains("试产"))
                                result = "试产";
                            else
                                result = "错误返回";
                            Log.WriteInfoLog("\r\nIsCuringBOM :\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + hResult.Html);
                            return true;
                        }

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

            return false;
        }

        /// <summary>
        // Section1：本机信息;
        // Section2：SMES信息;
        // Section3：实际抄写Key信息;
        /// </summary>
        /// <param name="Line"></param>
        /// <param name="Station"></param>
        /// <param name="order"></param>
        /// <param name="sn"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndOfTime"></param>
        /// <param name="returnObject"></param>
        /// <param name="key"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static bool GeneratKaylaData(string Line, string Station, string order, string sn, DateTime StartTime, DateTime EndOfTime, string returnObject, KeyInfo key, bool result)
        {
            Dictionary<string, string> localInfo = new Dictionary<string, string>();
            // 本机信息;
            localInfo.Add("Item", "Value");
            localInfo.Add("factory_id_I", "TCL");
            localInfo.Add("operator_I", Line);
            localInfo.Add("station_I", Station);
            localInfo.Add("fixture_id_I", "1_1");
            localInfo.Add("gui_ver_I", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
            localInfo.Add("route_check_I", "1");

            // SMES信息;
            string strLastOrder = CommonMethod.ReadProfileString("MOKAFactoryTools", "LastOrder", "");
            if (!strLastOrder.Equals(order, StringComparison.OrdinalIgnoreCase))
            {
                // 请求新的订单信息;
                MaInfo maInfo;
                if (!GetMaInfo(sn, out maInfo, null))
                {
                    Log.WriteErrorLog("Kayla GetMaInfo失败");
                    return false;
                }

                LastKaylaOrderInfo = new Dictionary<string, string>();
                if (maInfo != null)
                {
                    LastKaylaOrderInfo.Add("project_name_I", maInfo.project_name_I);
                    LastKaylaOrderInfo.Add("build_I", maInfo.build_I);
                    LastKaylaOrderInfo.Add("build_config_I", maInfo.build_config_I);
                    LastKaylaOrderInfo.Add("diag_ver_I", maInfo.diag_ver_I);
                    LastKaylaOrderInfo.Add("image_name_ver_I", maInfo.image_name_ver_I);
                    LastKaylaOrderInfo.Add("soc_type", maInfo.soc_type);
                    LastKaylaOrderInfo.Add("speaker_vender", maInfo.speaker_vender);
                    LastKaylaOrderInfo.Add("mic_vender", maInfo.mic_vender);
                }
            }
            Dictionary<string, string> dic = localInfo.Union(LastKaylaOrderInfo).ToDictionary(k => k.Key, v => v.Value);

            dic.Add("start_time_I", StartTime.ToString());
            dic.Add("serial_id_I", key != null ? key.DSN : "");   // DSN;
            dic.Add("FSN", sn);

            // 耐压值;
            if (returnObject != null && returnObject.Length > 0 && returnObject.Contains("Hightpot"))
            {
                Log.WriteInfoLog(String.Format("returnObjec={0}", returnObject));
                // 删除头尾[];
                returnObject = returnObject.Remove(0, 1);
                returnObject = returnObject.Remove(returnObject.Length - 1, 1);

                JObject jObject = JObject.Parse(returnObject);
                string hightpot = CommonMethod.JSON_SeleteNode(jObject, "Hightpot");
                int pos = hightpot.LastIndexOf('/');
                if (pos != -1)
                {
                    hightpot = hightpot.Substring(pos + 1);
                    pos = hightpot.IndexOf("mA");
                    // 使用正规去除数字+小数点以外的字符;
                    string AC = hightpot.Substring(0, pos + 2);
                    string DC = hightpot.Substring(pos + 2);
                    AC = System.Text.RegularExpressions.Regex.Replace(AC, @"[^\d.]*", "");
                    DC = System.Text.RegularExpressions.Regex.Replace(DC, @"[^\d.]*", "");
                    dic.Add("AC_I", AC);
                    dic.Add("DC_R", DC);
                }
                else
                {
                    dic.Add("AC_I", "");
                    dic.Add("DC_R", "");
                }
            }
            else
            {
                dic.Add("AC_I", "");
                dic.Add("DC_R", "");
                Log.WriteErrorLog("获取耐压值结果为空");
            }

            if (key != null)
            {
                if (key.DID.enable)
                {
                    dic.Add("DID", key.DID); // 本身就是字符串;
                    dic.Add("DID_check", key.DID.result ? "PASS" : "FAIL");
                }

                if (key.Mac.enable)
                {
                    dic.Add("Mac", key.Mac);//keyInfo.Mac.data.Replace("-", ":");
                    dic.Add("Mac_check", key.Mac.result ? "PASS" : "FAIL");
                }

                if (key.HDCP.enable)
                {
                    dic.Add("HDCP", key.HDCP);
                    dic.Add("HDCP_check", key.HDCP.result ? "PASS" : "FAIL");
                }

                if (key.HDCP22.enable)
                {
                    dic.Add("HDCP22", key.HDCP22);
                    dic.Add("HDCP22_check", key.HDCP22.result ? "PASS" : "FAIL");
                }

                if (key.ESN.enable)
                {
                    dic.Add("ESN", key.ESN);
                    dic.Add("ESN_check", key.ESN.result ? "PASS" : "FAIL");
                }

                if (key.Widevine.enable)
                {
                    dic.Add("Widevine", key.Widevine);
                    dic.Add("Widevine_check", key.Widevine.result ? "PASS" : "FAIL");
                }

                if (key.CI_plus.enable)
                {
                    dic.Add("CI_plus", key.CI_plus);
                    dic.Add("CI_plus_check", key.CI_plus.result ? "PASS" : "FAIL");
                }

                if (key.Attestation.enable)
                {
                    dic.Add("Attestation", key.Attestation);
                    dic.Add("Attestation_check", key.Attestation.result ? "PASS" : "FAIL");
                }

                if (key.MGK.enable)
                {
                    dic.Add("MGK", key.MGK);
                    dic.Add("MGK_check", key.MGK.result ? "PASS" : "FAIL");
                }

                if (key.Fairplay.enable)
                {
                    dic.Add("Fairplay", key.Fairplay);
                    dic.Add("Fairplay_check", key.Fairplay.result ? "PASS" : "FAIL");
                }

                if (key.DSN.enable)
                {
                    dic.Add("DSN", key.DSN);
                    dic.Add("DSN_check", key.DSN.result ? "PASS" : "FAIL");
                }

                if (key.WiFi_MAC.enable)
                {
                    dic.Add("WiFi_MAC", key.WiFi_MAC);
                    dic.Add("WiFi_MAC_check", key.WiFi_MAC.result ? "PASS" : "FAIL");
                }

                if (key.BT_MAC.enable)
                {
                    dic.Add("BT_MAC", key.BT_MAC);
                    dic.Add("BT_MAC_check", key.BT_MAC.result ? "PASS" : "FAIL");
                }

                if (key.LEK.enable)
                {
                    dic.Add("LEK", key.LEK);
                    dic.Add("LEK_check", key.LEK.result ? "PASS" : "FAIL");
                }

                if (key.PEK.enable)
                {
                    dic.Add("PEK", key.PEK);
                    dic.Add("PEK_check", key.PEK.result ? "PASS" : "FAIL");
                }

                if (key.Playready.enable)
                {
                    dic.Add("Playready", key.Playready);
                    dic.Add("Playready_check", key.Playready.result ? "PASS" : "FAIL");
                }

                if (key.Hashkey.enable)
                {
                    dic.Add("Hashkey", key.Hashkey);
                    dic.Add("Hashkey_check", key.Hashkey.result ? "PASS" : "FAIL");
                }

                if (key.ECP.enable)
                {
                    dic.Add("ECP", key.ECP);
                    dic.Add("ECP_check", key.ECP.result ? "PASS" : "FAIL");
                }

                if (key.YouTube_KEY.enable)
                {
                    dic.Add("YouTube_KEY", key.YouTube_KEY);
                    dic.Add("YouTube_KEY_check", key.YouTube_KEY.result ? "PASS" : "FAIL");
                }
            }

            dic.Add("cycle_time_I", EndOfTime.Subtract(StartTime).Seconds.ToString());
            dic.Add("test_result_I", result ? "PASS" : "FAIL");

            try
            {
                // 以DSN命名文件;
                if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Kayla"))
                {
                    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Kayla");
                }
                string savefile = string.Format("{0}Kayla\\{1}.csv", AppDomain.CurrentDomain.BaseDirectory, sn);
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(savefile, false))
                {
                    foreach (KeyValuePair<string, string> kvp in dic)
                    {
                        file.WriteLine(string.Format("{0},{1}", kvp.Key, kvp.Value));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLog(string.Format("保存csv文件失败：{0}", ex.ToString()));
                return false;
            }

            CommonMethod.StartProcess(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "tcp_send.exe", sn);

            return true;
        }

    }
}
