namespace MesWork
{
    using DT_YQJF_DC_SLN;
    using System;
    using System.Data;
    using System.Drawing;
    using System.Net;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Newtonsoft.Json;
    using System.Security.Cryptography;
    using ABB.Robotics.Controllers.Configuration;
    using Newtonsoft.Json.Linq;
    using System.Net.Http.Headers;
    using System.Web;
    using System.Collections.Generic;
    using NPOI.SS.Formula.Functions;
    using System.Security.Policy;
    using System.Data.SqlClient;
    using MW_Log;

    public partial class MesWorkForm
    {
        InitServer initServer = null;

        public static int msgCount = 0;
        /// <summary>
        /// 
        /// </summary>
        public MesWorkForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            this.WindowState = FormWindowState.Minimized;
            LoggerHelper.ShowMsg += MyLogHelper_LogCommit;

            // panel_Menu.Visible = true;

        }
        private void MesWorkForm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
           e.Cancel = true;
        }
        private void label_Monitor_Robot_Click(object sender, EventArgs e)
        {
            new F_RobotMonitor().Show(this);
        }
        private void label_Monitor_PLC_Click(object sender, EventArgs e)
        {
            new OpcForm(IsDemoMesServer).Show(this);
        }
        private async void label_ExitSys_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                CloseDeviceConn();
                DisConnect();
                await DisConnectService();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
        }
        private void panel_Btn_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            panel_Menu.Visible = !!!panel_Menu.Visible;
        }

        private void timer_Status_Tick(object sender, EventArgs e)
        {
            timer_Status.Enabled = false;
            Show_OnLineState();
            timer_Status.Enabled = true;
        }

        private void Show_OnLineState()
        {

            OnLineState_C(pb_OnLine_PLC_1, MesWorkForm.OnLine_PLC_1);
            OnLineState_C(pb_OnLine_SQL, MesWorkForm.OnLine_SQL);
            OnLineState_C(pb_OnLine_MQTT, MesWorkForm.OnLine_Mqtt);

        }

        private void OnLineState_C(PictureBox pb, bool onLine)
        {
            pb.Image = onLine ? global::SCADA_JG.Properties.Resources.连接状态
                    : global::SCADA_JG.Properties.Resources.断开状态;
        }

        private void timer_ShowCount_Tick(object sender, EventArgs e)
        {
            timer_ShowCount.Enabled = false;
            label_Count.Text = MesWorkForm.taskSql.Count.ToString();
            timer_ShowCount.Enabled = true;
        }
        public static void getCharDataToken()
        {
            //while (true)
            //{
         
                DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                long timestamp1 = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
                //if (charDataTokenTime < timestamp1)
                //{
                    try
                    {
                        string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                        string newGuid = Guid.NewGuid().ToString("N").Substring(0, 5);
                        long timestamp = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
                        string reqId = "req_AMES001 _" + time + "_" + newGuid;
                        string authKeyStr = GetMd5Hash(SK + salt + timestamp);

                        object reqParams = new { authKey = authKeyStr };
                        //准备请求的数据 反序列化
                        string bodydata = JsonConvert.SerializeObject(reqParams);

                        string retString;
                        string url = Url_WebApi_Char + "/openApi/auth/getAuthToken/";
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                        request.Headers.Add("reqId", reqId);
                        request.Headers.Add("timestamp", timestamp.ToString());
                        request.Headers.Add("appKey", AK);
                        //request.Headers.Add("lmt-auth-token", GetMd5Hash(originalString));

                        request.Method = "POST";
                        byte[] bytes = Encoding.UTF8.GetBytes(bodydata);
                        request.Accept = "*/*";
                        request.ContentType = "application/json";
                        request.ContentLength = bytes.Length;
                        request.Timeout = 10000;
                        // 准备请求体
                        Stream myResponseStream = request.GetRequestStream();
                        myResponseStream.Write(bytes, 0, bytes.Length);
                        //发送webapi请求 等待相应
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                        StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        retString = myStreamReader.ReadToEnd();
                        MW_Log.LoggerHelper.Info("获取_Token", retString);
                        // 序列化响应内容 
                        CharData_Token mrh = JsonConvert.DeserializeObject<CharData_Token>(retString);
                        int statusCode = (int)response.StatusCode;

                        // 对响应内容进行处理 更新数据库标志 
                        if (statusCode == 200)
                        {
                            myStreamReader.Close();
                            myResponseStream.Close();
                            if (response != null)
                            {
                                // 成功
                                if (mrh.code == "0")
                                {
                                    charDataToken = mrh.data.token;
                                    charDataTokenTime = mrh.data.expireTime;
                                    MW_Log.LoggerHelper.Info("获取_Token", charDataToken);
                                }
                                else
                                {
                                    MW_Log.LoggerHelper.Info("error_Token", mrh.errorDetail);
                                }
                                response.Close();
                            }
                            if (request != null)
                            {
                                request.Abort();
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        MW_Log.LoggerHelper.Info("error_Token", "", err);
                    }
                //}
            //    Thread.Sleep(TokenSyncTime);
            //}
        }
        public void getCharData()
        {
            while (true)
            {
                //if (charDataToken == "")
                //{
                //    MyLogHelper_LogCommit("error_charData", "未获取到Token");
                //    MW_Log.LoggerHelper.Info("error_charData", "未获取到Token");
                //    continue;
                //}

                string beginDateStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string endDateStr = DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:mm:ss");
                CharDataSearchPrams charDataSearchPrams = new CharDataSearchPrams();
                charDataSearchPrams.beginDate = beginDateStr;
                charDataSearchPrams.endDate = endDateStr;
                List<TestResult> testResultList = GetCharData_Details(charDataSearchPrams, out string code, out string errorDetail);
                string syncTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                try
                {
                    for (int i = 0; i < testResultList.Count; i++)
                    {
                        string vin = testResultList[i].vin; // deviceId
                        string testCode = testResultList[i].testCode;
                        string testStatus = testResultList[i].testStatus;
                        string testBeginTime = testResultList[i].testBeginTime;
                        string testEndTime = testResultList[i].testEndTime;
                        string faultInfo = testResultList[i].faultInfo;
                        B_DB_Opera.BaseData_tagTable_CharData_Insert(vin, testCode, testStatus, testBeginTime, testEndTime, faultInfo, syncTime, out string errMsg);
                    }
                }
                catch (Exception err)
                {
                    MyLogHelper_LogCommit("error_charData10", err.Message);
                    MW_Log.LoggerHelper.Info("error_charData11", "", err);
                }
                Thread.Sleep(SyncTime);
            }
        }
        static string GetMd5Hash(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.ASCII.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString().ToLower();
            }
        }

        private void MyLogHelper_LogCommit(string type, string msg)
        {
            var log = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " " + type  + " " + msg + "\r\n";

            msgCount++;


            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    if (msgCount > 100)
                    {
                        this.richTextBox1_log.Text = "";
                    }
                    this.richTextBox1_log.AppendText(log);
           
                }));
            }
            else
            {
                if (msgCount > 100)
                {
                    this.richTextBox1_log.Text = "";
                }
                this.richTextBox1_log.AppendText(log);
    
            }

        }

        public static List<TestResult> GetCharData_Details(CharDataSearchPrams charDataSearchPrams, out string code, out string errorDetail)
        {
            List<TestResult> testResultList =  new List<TestResult>();
            code = "0";
            errorDetail = "";
            try
            {
     
      
                //准备请求的数据 反序列化
                string bodydata = JsonConvert.SerializeObject(charDataSearchPrams);

                string retString;
                string url = Url_WebApi_Char + "/openApi/thirdData/selectBatteryTestResult";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                string newGuid = Guid.NewGuid().ToString("N").Substring(0, 5);

                long timestamp = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
                string reqId = "req_AMES001 _" + time + "_" + newGuid;
                string lmt_auth_token = GetMd5Hash(charDataToken + SK + timestamp);

                request.Headers.Add("reqId", reqId);
                request.Headers.Add("timestamp", timestamp.ToString());
                request.Headers.Add("appKey", AK);
                request.Headers.Add("lmt-auth-token", lmt_auth_token);
                MW_Log.LoggerHelper.Info("selectBatteryTestResultHeaders", $"【reqId】{reqId}【timestamp】{timestamp.ToString()}【appKey】{AK}【lmt-auth-token】{lmt_auth_token}");
                request.Timeout = 10000;
                request.Method = "Post";
                byte[] bytes = Encoding.UTF8.GetBytes(bodydata);
                request.ContentType = "application/json;charset=utf-8";
                request.ContentLength = bytes.Length;
                //MW_Log.LoggerHelper.Info("请求参数_charData_reqId", reqId);
                //MW_Log.LoggerHelper.Info("请求参数_charData_timestamp", timestamp.ToString());
                //MW_Log.LoggerHelper.Info("请求参数_charData_appKey", AK);
                //MW_Log.LoggerHelper.Info("请求参数_charData_lmt-auth-token", lmt_auth_token);
                // 准备请求体
                Stream myResponseStream = request.GetRequestStream();
                myResponseStream.Write(bytes, 0, bytes.Length);
                //发送webapi请求 等待相应
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                MW_Log.LoggerHelper.Info("返回参数_charData", retString);
                // 序列化响应内容 
                CharData mrh = JsonConvert.DeserializeObject<CharData>(retString);
                int statusCode = (int)response.StatusCode;

                // 对响应内容进行处理 更新数据库标志 
                if (statusCode == 200)
                {
                    myStreamReader.Close();
                    myResponseStream.Close();
                    if (response != null)
                    {
                        code = mrh.code;
                        errorDetail = mrh.msg + mrh.errorDetail;
                        // 成功
                        if (mrh.code == "0")
                        {
                            try
                            {
                                string syncTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                testResultList = mrh.data;
                            }
                            catch (Exception err)
                            {
                                MW_Log.LoggerHelper.Info("error_charData2", "", err);
                            }
                        }
                        else
                        {
                            if(mrh.code == "603")
                            {
                                getCharDataToken();
                            }

                            MW_Log.LoggerHelper.Info("error_charData3", errorDetail);
                        }

                        response.Close();
                    }
                    if (request != null)
                    {
                        request.Abort();
                    }
                }
            }
            catch (Exception err)
            {
                code = "500";
                errorDetail = err.Message;
                MW_Log.LoggerHelper.Info("error_charData4", "", err);
            }
            return testResultList;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            new TaskFactory().StartNew(delegate ()
            {

                string beginDateStr = dateTimePicker1_start.Text.ToString();
                string endDateStr = dateTimePicker1_end.Text.ToString();
                CharDataSearchPrams charDataSearchPrams = new CharDataSearchPrams();
                charDataSearchPrams.beginDate = beginDateStr;
                charDataSearchPrams.endDate = endDateStr;
                List<TestResult> testResultList = GetCharData_Details(charDataSearchPrams, out string code, out string errorDetail);
                string syncTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                try
                {
                    if (testResultList != null)
                    {
                        for (int i = 0; i < testResultList.Count; i++)
                        {
                            string vin = testResultList[i].vin; //deviceId
                            string testCode = testResultList[i].testCode;
                            string testStatus = testResultList[i].testStatus;
                            string testBeginTime = testResultList[i].testBeginTime;
                            string testEndTime = testResultList[i].testEndTime;
                            string faultInfo = testResultList[i].faultInfo;
                            B_DB_Opera.BaseData_tagTable_CharData_Insert(vin, testCode, testStatus, testBeginTime, testEndTime, faultInfo, syncTime, out string errMsg);
                        }
                    }
                    else
                    {
                        MyLogHelper_LogCommit("error_charData6", "不存在数据！");
                    }
                }
                catch (Exception err)
                {

                    MyLogHelper_LogCommit("error_charData7", err.Message);
                    MW_Log.LoggerHelper.Info("error_charData8", "", err);
                }
            });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.richTextBox1_log.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            getCharDataToken();
        }

        private void panel_Menu_Paint(object sender, PaintEventArgs e)
        {

        }

        private void MesWorkForm_Load(object sender, EventArgs e)
        {

        }
    }
}

