using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace MaterialPrint
{
    public partial class ReadTestInfo : Form
    {

        DataHelper dh = new DataHelper();

        string ms_id = "";

        public ReadTestInfo()
        {
            InitializeComponent();
        }

        Dictionary<string, string> TestItem = new Dictionary<string, string>();
        private void ReadTestInfo_Load(object sender, EventArgs e)
        {
            TestItem.Add("SystemInfo", "系统测试");
            TestItem.Add("Keypad", "按键测试");
            TestItem.Add("Battery", "电池测试");
            TestItem.Add("FrontCameraRec", "前摄像头摄像");
            TestItem.Add("FrontCamera", "前摄像头拍照");
            TestItem.Add("Brightness", "背光测试");
            TestItem.Add("Display", "显示屏测试");
            TestItem.Add("ExtDisplay", "外接显示器");
            TestItem.Add("RemovableDevice", "存储设备");
            TestItem.Add("WiFi", "WIFI测试");
            TestItem.Add("Bluetooth", "BT测试");
            TestItem.Add("Speaker", "扬声器和麦克风测试");
            TestItem.Add("Headset", "耳机和麦克风测试");
            TestItem.Add("Touchpad", "触摸板");
            TestItem.Add("Keyboard", "键盘测试");
            TestItem.Add("SerialPort", "COM接口");
            TestItem.Add("RearCamera", "后摄像头拍照");
            TestItem.Add("RearCameraRec", "后摄像头摄像");
            TestItem.Add("Touch", "触摸屏测试");
            TestItem.Add("Pen", "触控笔测试");
            TestItem.Add("LAN", "RJ45接口");
            TestItem.Add("SIM", "3G/4G测试");
            TestItem.Add("Accelerometer", "G Sensor 重力感应测试");
            TestItem.Add("GPS", "GPS测试");
            TestItem.Add("Gyrometer", "陀螺仪测试");
            TestItem.Add("Light", "光感测试");
            TestItem.Add("Compass", "指南针");

        }

        public string exec(string exePath, string parameters)
        {
            Process process = new Process();
            process.StartInfo.FileName = exePath;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            process.Start();
            process.StandardInput.WriteLine(parameters);

            process.StandardInput.Close();   //运行完毕关闭控制台输入
            string add = process.StandardOutput.ReadToEnd(); //读取输出的信息
            Console.WriteLine(add);
            process.Close();
            return add;
        }

        public void GetAgingInfo(string FilePath)
        {
            //C:\Users\callm\Desktop\iNet
            FilePath = @"C:\Users\callm\Desktop\iNet\RunIn.Log";
            StreamReader sr = new StreamReader(FilePath);
            
            string StartTime = "";
            string EndTime = "";
            while (!sr.EndOfStream)
            {
                string str = sr.ReadLine();
                if (str.Contains("Video Start"))
                {
                    StartTime = Regex.Match(str, @"\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}").Value;
                }
                if (str.Contains("Video PASS"))
                {
                    EndTime = Regex.Match(str, @"\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}").Value;
                }
            }
            dh.ExecuteSql("update makeserial set ms_starttime=to_date('" + StartTime + "','dd/mm/yyyy hh24:mi:ss'),ms_endtime=to_date('" + EndTime + "','dd/mm/yyyy hh24:mi:ss') where ms_id='" + ms_id + "'", "select");
        }

        public void GetWriteInfo(string FilePath)
        {
            Dictionary<string, string> Dic = new Dictionary<string, string>();
            StreamReader sr = new StreamReader(FilePath);
            DataTable dt = new DataTable();
            dt.Columns.Add("itemname");
            dt.Columns.Add("testresult");
            dt.Columns.Add("SN");
            dt.Columns.Add("BIOS");
            dt.Columns.Add("PK");
            while (!sr.EndOfStream)
            {
                string str = sr.ReadLine();
                string Value = Regex.Match(str, @"\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}.\d{3}\t\[Info] - (PASS|FAIL)\t\S+").Value;
                if (Value != "")
                {
                    if (Dic.ContainsKey(Value.Split('\t')[2]))
                        Dic.Remove(Value.Split('\t')[2]);
                    Dic.Add(Value.Split('\t')[2], Value);
                }
            }
            string SerialNumber = Regex.Match(exec("cmd.exe", " wmic os get SerialNumber /value"), @"SerialNumber=\S+").Value.Replace("SerialNumber=", "");
            string BIOS = Regex.Match(exec("cmd.exe", " wmic bios get SMBIOSBIOSVersion / value"), @"SMBIOSBIOSVersion=\S+").Value.Replace("SMBIOSBIOSVersion=", "");
            string PK = Regex.Match(exec("CheckupKey.exe", ""), @"The PKID is: \S+").Value.Replace("The PKID is: ", "");
            //判断KEY是否被使用过
            string keysn = dh.getFieldDataByCondition("makeserial", "ms_sncode", "ms_id<>" + ms_id + " and ms_key='" + PK + "'").ToString();
            bool TestOK = true;
            //if (SerialNumber != SN.Text)
            //{
            //    MessageBox.Show("扫描序列号:" + SN.Text + "和本机读取序列号:" + SerialNumber + "不一致");
            //    TestOK = false;
            //}
            if (keysn != "")
            {
                MessageBox.Show("KEY:" + PK + "已被序列号:" + keysn + "使用");
                TestOK = false;
            }
            ResultView.DataSource = dt;
            foreach (var item in Dic)
            {
                string time = item.Value.Split('\t')[0];
                string result = item.Value.Split('\t')[1].Contains("PASS") ? "PASS" : "FAIL";
                string itemname = TestItem.ContainsKey(item.Key) ? TestItem[item.Key] : item.Key;
                DataRow dr = dt.NewRow();
                dr["itemname"] = itemname;
                dr["testresult"] = item.Value;
                dr["SN"] = SerialNumber;
                dr["BIOS"] = BIOS;
                dr["PK"] = PK;
                dt.Rows.Add(dr);
                string sql = "insert into steptestdetail (std_id,std_sn,std_date,std_class,std_testresult,std_itemname)values";
                sql += "(steptestdetail_seq.nextval,'" + SN.Text + "',to_timestamp('" + item.Value.Split('\t')[0] + "',";
                sql += "'yyyy-mm-dd hh24:mi:ss.ff6'),'" + item.Key + "','" + result + "','" + itemname + "')";
                //测试OK才上传数据
                if (TestOK)
                    dh.ExecuteSql(sql, "insert");
            }
            if (TestOK)
            {
                dh.ExecuteSql("update makeserial set ms_key='" + PK + "' where ms_id=" + ms_id, "update");
                MessageBox.Show("测试记录保存成功");
            }
        }

        private void SN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                ms_id = dh.getFieldDataByCondition("makeserial", "max(ms_id)", "ms_sncode='" + SN.Text + "' or ms_firstsn='" + SN.Text + "'").ToString();
                if (ms_id != "")
                {
                    GetAgingInfo("");
                    //GetWriteInfo(@"C:\TEST_TOOL\SFTClassicLog.txt");
                }
                else
                {
                    MessageBox.Show("序列号" + SN.Text + "不存在");
                }
            }
        }

        private void ResultView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0)
            {
                if (ResultView.Columns[e.ColumnIndex].Name == "testresult")
                {
                    if (e.RowIndex >= 0)
                    {
                        if (ResultView.Rows[e.RowIndex].Cells["testresult"].Value != null && (ResultView.Rows[e.RowIndex].Cells["testresult"].Value.ToString().Contains("PASS")))
                        {
                            e.Graphics.FillRectangle(Brushes.ForestGreen, e.CellBounds);
                            Rectangle border = e.CellBounds;
                            border.Width -= 1;
                            e.Graphics.DrawRectangle(Pens.Black, border);
                            e.PaintContent(e.CellBounds);
                            e.Handled = true;
                        }
                        else
                        {
                            e.Graphics.FillRectangle(Brushes.OrangeRed, e.CellBounds);
                            Rectangle border = e.CellBounds;
                            border.Width -= 1;
                            e.Graphics.DrawRectangle(Pens.Black, border);
                            e.PaintContent(e.CellBounds);
                            e.Handled = true;
                        }
                    }
                }
            }
        }
    }
}