using CCWin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using SXLibrary;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MOKA_Factory_Tools
{
    public delegate void MoveHandler(Point XY, ArrayList formlocationmsg, int num);
    public delegate void KeyDownHandler(ArrayList formlocationmsg, IntPtr intPtr);
    public partial class Main : Skin_Color
    {
        MidList midList1 = new MidList();
        UpgradeMsgList UpgradeMsgList1 = new UpgradeMsgList();
        MidAddress midAddress1 = new MidAddress();
        ReadCheck ReadCheck1 = new ReadCheck();
        WriteCheck WriteCheck1 = new WriteCheck();
        WriteDone WriteDone1 = new WriteDone();
        FunctionSetting functionSetting1 = new FunctionSetting();
        SQLiteConnection LocalDB = null;
        SQLiteConnection ErrorDB = null;

        Dictionary<string, string> ChannelMapList = new Dictionary<string, string>();
        Dictionary<string, string> LanguageMapList = new Dictionary<string, string>();
        string Custom_ProjectID = "";
        ArrayList formlocationmsg = new ArrayList();
        string ErrorDBPath = AppDomain.CurrentDomain.BaseDirectory + "\\Error.db";
        Thread uploadbackground;

        bool LocalWrite = false;//离线抄写开关
        bool LocationMark = true;//操作窗体换行点
        int LocationNum = 0;//一行操作窗体数
        public event KeyDownHandler KeyDownEvent;
        public event MoveHandler MoveEvent;

        public Main(int enable)
        {
            InitializeComponent();
            LockSettingFunction(enable == 0 || enable == 3);
            CreateKeyManually.Visible = enable == 1;
            LocalWrite = enable == 3;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            uploadbackground = new Thread(UploadBackGround);
            uploadbackground.IsBackground = true;
            TVCOM.Items.AddRange(SerialPort.GetPortNames());
            LoadJsonConfig();
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(0, 0);
            this.Text = CommonMethod.FactoryName + " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            if (!File.Exists(ErrorDBPath))
            {
                if (SQLiteHelper.NewDbFile(ErrorDBPath))
                {
                    SQLiteHelper.NewTable(ErrorDBPath, "ErrorReport", "(ID INTEGER PRIMARY KEY AUTOINCREMENT,url varchar,content varvhar,gener_date DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')),report_date DATETIME)");
                    SQLiteHelper.NewTable(ErrorDBPath, "CopyDelayReport", "(ID INTEGER PRIMARY KEY AUTOINCREMENT,bid varchar,url varchar,content varvhar,copy_date DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')),report_date DATETIME)");
                    SQLiteHelper.NewTable(ErrorDBPath, "ProductionCount", "(bid varchar,count varchar)");
                }
            }
            if (ErrorDB == null)
            {
                ErrorDB = new SQLiteConnection("data source=" + ErrorDBPath);
                ErrorDB.Open();

            }
        }

        private void SetDSNLimit()
        {
            // 如果抄写PSN,不自动赋值条码限制;
            if (BarcodeWrite.Checked)
                return;

            // 设置条码限制默认打上勾;
            if (midList1.keytype != null && midList1.keytype.ContainsKey("DSN"))
            {
                BarcodeLimit.Checked = true;
                BarCodeKeyCodeText.Text = OrderText.Text;
            }
        }

        private void OrderSubmit_Click(object sender, EventArgs e)
        {
            SQLiteHelper.DeleteOldData(ErrorDB);//删除30天以前已经上报的数据
            if (TestMode.serverurl == Serverurl.Testurl)
            {
                MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                DialogResult dr = MessageBox.Show(LResource.TestServerUsingError, LResource.Error, messButton);
                if (dr == DialogResult.Yes)
                {
                    //                 
                }
                else
                {
                    return;
                }
            }
            if (TVCOM.SelectedItem == null)
            {
                MessageBox.Show(LResource.TVCOMNullError, LResource.Error);
                return;
            }
            if (OrderText.Text.Trim().Length == 0)
            {
                MessageBox.Show(LResource.OrderNullError, LResource.Error);
                return;
            }
            if (!SQLiteHelper.CheckProductionNum(ErrorDB, OrderText.Text.Trim()))
            {
                MessageBox.Show(LResource.CheckProductionNumError, LResource.Error);
                return;
            }
            if (timer1.Enabled == false)
                timer1.Start();
            OrderSubmit.Text = LResource.Waiting;
            SaveJsonConfig("LastOrder", OrderText.Text.ToString());
            functionSetting1.TVCOM = TVCOM.SelectedItem.ToString();
            functionSetting1.TVBaud = TVBaud.SelectedItem.ToString();
            functionSetting1.ChannelList = ChannelList.SelectedItem.ToString();
            functionSetting1.WriteChannel = WriteChannel.Checked;
            functionSetting1.WriteOSD = WriteOSD.Checked;
            functionSetting1.OSDList = OSDList.SelectedItem.ToString();
            functionSetting1.WriteSHOP = WriteSHOP.Checked;
            functionSetting1.SHOPList = SHOPList.SelectedItem.ToString();
            functionSetting1.WriteWB = WriteWB.Checked;
            functionSetting1.WBInit = WBInit.Checked;
            functionSetting1.WBPath = WBPath.Text;

            if (!LocalWrite)
            {
                if (Preload.Checked)
                {
                    string dbPath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\" + OrderText.Text.Trim() + ".db";
                    if (File.Exists(dbPath))
                    {
                        if (LocalDB == null)
                        {
                            LocalDB = new SQLiteConnection("data source=" + dbPath);
                            LocalDB.Open();
                        }
                        if (SQLiteHelper.WholeCheckDownloadStatus(LocalDB, OrderText.Text.Trim()))
                        {
                            try
                            {
                                if (SQLiteHelper.GetDBMidInfo(LocalDB, OrderText.Text.Trim(), out midAddress1))
                                {
                                    if (UsinglocalIDCheck.Checked)
                                    {
                                        midAddress1.pid = Custom_ProjectID;
                                        MessageBox.Show(LResource.WilluseLocalPID, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    }
                                    else if (midAddress1.pid != Custom_ProjectID && Custom_ProjectID.Trim().Length > 0)
                                    {

                                        if (midAddress1.pid != null)
                                            if (midAddress1.pid.Trim().Length > 0)
                                                PID_Num.Value = Convert.ToDecimal(midAddress1.pid);
                                        MessageBox.Show(LResource.WilluseOnlinePID, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }

                                    if (SQLiteHelper.GetrokuCustomer(LocalDB, OrderText.Text, out RokuCustomer rokuCustomer_1))
                                    {
                                        midList1.rokuCustomer = rokuCustomer_1;
                                    };
                                    if (SQLiteHelper.Getdsn(LocalDB, OrderText.Text, out string firetvdsn))
                                    {
                                        midList1.keytype = new Dictionary<string, string>();
                                        midList1.keytype.Add("DSN", firetvdsn);
                                    };
                                    if (SQLiteHelper.Getwhitebalance(LocalDB, OrderText.Text, out WhiteBalanceInfo whiteBalanceInfo_1))
                                    {
                                        functionSetting1.WBPath = dbPath;
                                        functionSetting1.WriteWB = true;
                                        functionSetting1.NormalRGB = new byte[3];
                                        functionSetting1.CoolRGB = new byte[3];
                                        functionSetting1.WarmRGB = new byte[3];
                                        functionSetting1.NormalRGB[0] = (byte)Convert.ToDouble(whiteBalanceInfo_1.hdmirgain);
                                        functionSetting1.NormalRGB[1] = (byte)Convert.ToDouble(whiteBalanceInfo_1.hdmiggain);
                                        functionSetting1.NormalRGB[2] = (byte)Convert.ToDouble(whiteBalanceInfo_1.hdmibgain);

                                        functionSetting1.CoolRGB[0] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.lrgain) + 256);
                                        functionSetting1.CoolRGB[1] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.lggain) + 256);
                                        functionSetting1.CoolRGB[2] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.lbgain) + 256);

                                        functionSetting1.WarmRGB[0] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.nrgain) + 256);
                                        functionSetting1.WarmRGB[1] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.nggain) + 256);
                                        functionSetting1.WarmRGB[2] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.nbgain) + 256);

                                    };

                                    OperationPanel operationPanel1 = new OperationPanel(this, LocalDB, ErrorDB, midAddress1, functionSetting1, WriteCheck1, ReadCheck1, WriteDone1, Preload.Checked, midList1, OrderText.Text.Trim());
                                    operationPanel1.StartPosition = FormStartPosition.Manual;
                                    if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width && LocationMark)
                                    {
                                        LocationMark = false;
                                        LocationNum = formlocationmsg.Count;
                                    }
                                    if (formlocationmsg.Count == 0)
                                        operationPanel1.Location = (Point)new Size(this.Right, this.Top);
                                    else if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width)
                                    {
                                        Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                                        operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * (formlocationmsg.Count - LocationNum), this.Top + operationPanel1.Size.Height);
                                    }
                                    else
                                    {
                                        Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                                        operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * formlocationmsg.Count, this.Top);
                                    }
                                    operationPanel1.DeleteIntptr += new OperationPanel.DisplayUpdateDelegate(DeleteIntptr);
                                    operationPanel1.SNKeyDownEven += new OperationPanel.SNKeyDown(SNKeyDownEven);
                                    operationPanel1.AutoKeyRequire += new OperationPanel.AutoKeyRequireDelegate(AutoKeyRequire);
                                    IntPtr intPtr = operationPanel1.Handle;
                                    Dictionary<IntPtr, Point> part1 = new Dictionary<IntPtr, Point>();
                                    part1.Add(intPtr, (Point)new Size(operationPanel1.Right, operationPanel1.Top));
                                    formlocationmsg.Add(part1);
                                    operationPanel1.Show();
                                }
                                else
                                {
                                    MessageBox.Show("Read LocalDB error,please delete old db file and download a new one");
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.WriteErrorLog(ex.Message);
                            }

                            // 是否有dsn要抄写;
                            SetDSNLimit();
                        }
                    }
                    else
                    {
                        if (CommonMethod.GetMidInfo(TestMode.serverurl, OrderText.Text.Trim(), TestMode.MAC, "", "", ErrorDB, out midList1))
                        {
                            if (CommonMethod.GetMidAddress2(midList1, OrderText.Text.Trim(), ErrorDB, out List<MidAddress> midAddress2))
                            {
                                WhiteBalanceList WhiteBalanceListNow;
                                // 如果是抄写EDID,则不获取白平衡数据;
                                if (CommonMethod.IsEDIDCopy(midList1))
                                    midList1.whiteType = "-1";
                                switch (midList1.whiteType)//订单白平衡预置状态
                                {
                                    case "0"://旧订单,默认值
                                        {
                                            CommonMethod.GetWhiteBalanceInfo(TestMode.getWhiteBalanceInfoUrl, OrderText.Text.Trim(), TestMode.MAC, ErrorDB, out WhiteBalanceListNow);
                                            break;
                                        }
                                    case "1"://未预置或预置LR数据
                                        {
                                            CommonMethod.GetWhiteBalanceInfo(TestMode.getWhiteBalanceInfoUrl, OrderText.Text.Trim(), TestMode.MAC, ErrorDB, out WhiteBalanceListNow);
                                            if (WhiteBalanceListNow.whiteBalanceInfo == null)
                                            {
                                                MessageBox.Show("White balance info error, please contact factory engineer!");
                                                return;
                                            }
                                            break;
                                        }
                                    case "2"://已预置PR数据
                                        {
                                            CommonMethod.GetWhiteBalanceInfo(TestMode.getWhiteBalanceInfoUrl, OrderText.Text.Trim(), TestMode.MAC, ErrorDB, out WhiteBalanceListNow);
                                            break;
                                        }
                                    default:
                                        {
                                            WhiteBalanceListNow = null;
                                            break;
                                        }
                                }
                                foreach (var midAddress1 in midAddress2)
                                {
                                    string KeyPath = AppDomain.CurrentDomain.BaseDirectory + "\\download\\" + midAddress1.order + ".json";
                                    if (System.IO.File.Exists(KeyPath))
                                    {
                                        if (GetMD5.GetMD5HashFromFile(KeyPath) == midAddress1.pmd5)
                                        {
                                            if (SQLiteHelper.NewDbFile(dbPath))
                                            {
                                                SQLiteHelper.NewTable(dbPath, "keys", "(sn varchar,keys varvhar,copy_date DATETIME,report_date DATETIME)");
                                                SQLiteHelper.NewTable(dbPath, "mid", "(bid varchar,number varchar, pid varchar,ctype varvhar,version varvhar,host varchar,purl varvhar,psize varvhar,pmd5 varvhar,status varvhar,start_date DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')),finish_date DATETIME,desc varvhar)");
                                                SQLiteHelper.NewTable(dbPath, "report", "(url varchar,content varchar,gener_date DATETIME,report_date DATETIME)");
                                                SQLiteHelper.NewTable(dbPath, "rokuCustomer", "(ordernum varchar,region varchar,brand varchar,oemmodel varchar,supporturl varchar,supportphone varchar,productiondate varchar,remotetype varchar)");
                                                SQLiteHelper.NewTable(dbPath, "whitebalance", "(ordernum varchar,hdmirgain varchar,hdmiggain varchar,hdmibgain varchar,nrgain varchar,nggain varchar,nbgain varchar,lrgain varchar,lggain varchar,lbgain varchar,updatetime DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')))");
                                                SQLiteHelper.NewTable(dbPath, "dsn", "(ordernum varchar,dsn varchar,updatetime DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')))");
                                                SQLiteHelper.AddOneLine(dbPath, new object[] { midAddress1.order, midAddress1.number, midAddress1.pid, midAddress1.ctype, midAddress1.version, midList1.host, midAddress1.purl, midAddress1.psize, midAddress1.pmd5, "1" });
                                                if (midList1.rokuCustomer != null)
                                                    SQLiteHelper.AddRokuOneLine(dbPath, new object[] { midList1.rokuCustomer.ordernum, midList1.rokuCustomer.region, midList1.rokuCustomer.brand, midList1.rokuCustomer.oemmodel, midList1.rokuCustomer.supporturl, midList1.rokuCustomer.supportphone, midList1.rokuCustomer.productiondate, midList1.rokuCustomer.remotetype });
                                                if (WhiteBalanceListNow != null)
                                                    if (WhiteBalanceListNow.whiteBalanceInfo != null)
                                                        SQLiteHelper.AddwbOneLine(dbPath, new object[] { WhiteBalanceListNow.whiteBalanceInfo.ordernum,
                                                        WhiteBalanceListNow.whiteBalanceInfo.hdmirgain, WhiteBalanceListNow.whiteBalanceInfo.hdmiggain, WhiteBalanceListNow.whiteBalanceInfo.hdmibgain,
                                                        WhiteBalanceListNow.whiteBalanceInfo.nrgain, WhiteBalanceListNow.whiteBalanceInfo.nggain, WhiteBalanceListNow.whiteBalanceInfo.nbgain,
                                                        WhiteBalanceListNow.whiteBalanceInfo.lrgain, WhiteBalanceListNow.whiteBalanceInfo.lggain, WhiteBalanceListNow.whiteBalanceInfo.lbgain });
                                                if (midList1.keytype.ContainsKey("DSN"))
                                                {
                                                    SQLiteHelper.AdddsnOneLine(dbPath, new object[] { midAddress1.order, midList1.keytype["DSN"] });
                                                }
                                                SQLiteHelper.UpdateTime(dbPath, midAddress1.order);
                                            }
                                            if (File.Exists(dbPath))
                                            {
                                                List<object[]> keyDatas = new List<object[]>();
                                                using (System.IO.StreamReader file = System.IO.File.OpenText(KeyPath))
                                                {
                                                    using (JsonTextReader reader = new JsonTextReader(file))
                                                    {
                                                        JArray o = (JArray)JToken.ReadFrom(reader);
                                                        foreach (var ss in o)  //查找某个字段与值
                                                        {
                                                            var sn = ((JObject)ss)["sn"];
                                                            var data = ((JObject)ss)["key"];
                                                            keyDatas.Add(new object[] { sn, data });
                                                        }
                                                    }
                                                }
                                                SQLiteHelper.InsertKeys(dbPath, keyDatas);
                                            }
                                            try
                                            {
                                                if (LocalDB == null)
                                                {
                                                    LocalDB = new SQLiteConnection("data source=" + dbPath);
                                                    LocalDB.Open();
                                                }
                                                OperationPanel operationPanel1 = new OperationPanel(this, LocalDB, ErrorDB, midAddress1, functionSetting1, WriteCheck1, ReadCheck1, WriteDone1, Preload.Checked, midList1, OrderText.Text.Trim());
                                                operationPanel1.StartPosition = FormStartPosition.Manual;
                                                if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width && LocationMark)
                                                {
                                                    LocationMark = false;
                                                    LocationNum = formlocationmsg.Count;
                                                }
                                                if (formlocationmsg.Count == 0)
                                                    operationPanel1.Location = (Point)new Size(this.Right, this.Top);
                                                else if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width)
                                                {
                                                    Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                                                    operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * (formlocationmsg.Count - LocationNum), this.Top + operationPanel1.Size.Height);
                                                }
                                                else
                                                {
                                                    Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                                                    operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * formlocationmsg.Count, this.Top);
                                                }
                                                operationPanel1.DeleteIntptr += new OperationPanel.DisplayUpdateDelegate(DeleteIntptr);
                                                operationPanel1.SNKeyDownEven += new OperationPanel.SNKeyDown(SNKeyDownEven);
                                                operationPanel1.AutoKeyRequire += new OperationPanel.AutoKeyRequireDelegate(AutoKeyRequire);
                                                IntPtr intPtr = operationPanel1.Handle;
                                                Dictionary<IntPtr, Point> part1 = new Dictionary<IntPtr, Point>();
                                                part1.Add(intPtr, (Point)new Size(operationPanel1.Right, operationPanel1.Top));
                                                formlocationmsg.Add(part1);
                                                operationPanel1.Show();

                                            }
                                            catch (Exception ex)
                                            {
                                                Log.WriteErrorLog(ex.Message);
                                            }
                                        }
                                        else
                                        {
                                            Download DownloadPage = new Download(ErrorDB, midAddress1, -1, midList1, WhiteBalanceListNow);
                                            DownloadPage.ShowDialog();
                                            int gid = GC.GetGeneration(DownloadPage);
                                            DownloadPage = null;
                                            GC.Collect(gid);
                                        }
                                    }
                                    else
                                    {
                                        Download DownloadPage = new Download(ErrorDB, midAddress1, -1, midList1, WhiteBalanceListNow);
                                        DownloadPage.ShowDialog();
                                        int gid = GC.GetGeneration(DownloadPage);
                                        DownloadPage = null;
                                        GC.Collect(gid);
                                    }
                                }
                                if (File.Exists(dbPath))
                                {
                                    if (LocalDB == null)
                                    {
                                        LocalDB = new SQLiteConnection("data source=" + dbPath);
                                        LocalDB.Open();
                                    }
                                    if (SQLiteHelper.WholeCheckDownloadStatus(LocalDB, OrderText.Text.Trim()))
                                    {
                                        if (CommonMethod.ReportDownloadStatus(midList1.host, OrderText.Text.Trim(), ErrorDB))
                                            MessageBox.Show(LResource.DownloadSuccess);
                                        else
                                            MessageBox.Show(LResource.DownloadReportFail);
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show(LResource.GetMidAdresserror);
                            }
                        }
                        else
                        {
                            MessageBox.Show(LResource.GetMidInfoerror);
                        }

                        // 是否有dsn要抄写;
                        SetDSNLimit();
                    }
                }
                else
                {
                    if (CommonMethod.GetMidInfo(TestMode.serverurl, OrderText.Text.Trim(), TestMode.MAC, "", "", ErrorDB, out midList1))
                    {
                        //CommonMethod.UpgradeCheck(UpgradeUrl.Officialurl, midList1.factoryNum, ErrorDB, out UpgradeMsgList1);
                        if (UsinglocalIDCheck.Checked)
                        {
                            midList1.projectid = Custom_ProjectID;
                            MessageBox.Show(LResource.WilluseLocalPID, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (midList1.projectid != Custom_ProjectID && Custom_ProjectID.Trim().Length > 0)
                        {
                            if (midList1.projectid != null)
                                if (midList1.projectid.Trim().Length > 0)
                                    PID_Num.Value = Convert.ToDecimal(midList1.projectid);
                            MessageBox.Show(LResource.WilluseOnlinePID, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        try
                        {
                            OperationPanel operationPanel1 = new OperationPanel(this, LocalDB, ErrorDB, midAddress1, functionSetting1, WriteCheck1, ReadCheck1, WriteDone1, Preload.Checked, midList1, OrderText.Text.Trim());
                            operationPanel1.StartPosition = FormStartPosition.Manual;
                            if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width && LocationMark)
                            {
                                LocationMark = false;
                                LocationNum = formlocationmsg.Count;
                            }
                            if (formlocationmsg.Count == 0)
                                operationPanel1.Location = (Point)new Size(this.Right, this.Top);
                            else if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width)
                            {
                                Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                                operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * (formlocationmsg.Count - LocationNum), this.Top + operationPanel1.Size.Height);
                            }
                            else
                            {
                                Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                                operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * formlocationmsg.Count, this.Top);
                            }
                            operationPanel1.DeleteIntptr += new OperationPanel.DisplayUpdateDelegate(DeleteIntptr);
                            operationPanel1.SNKeyDownEven += new OperationPanel.SNKeyDown(SNKeyDownEven);
                            operationPanel1.AutoKeyRequire += new OperationPanel.AutoKeyRequireDelegate(AutoKeyRequire);
                            IntPtr intPtr = operationPanel1.Handle;
                            Dictionary<IntPtr, Point> part1 = new Dictionary<IntPtr, Point>();
                            part1.Add(intPtr, (Point)new Size(operationPanel1.Right, operationPanel1.Top));
                            formlocationmsg.Add(part1);
                            operationPanel1.Show();
                        }
                        catch (Exception ex)
                        {
                            Log.WriteErrorLog(ex.Message);
                        }

                        // 是否有dsn要抄写;
                        SetDSNLimit();
                    }
                    else
                    {
                        MessageBox.Show(LResource.GetMidInfoerror);
                    }
                }
            }
            else
            {
                MessageBox.Show(LResource.LocalKeyMode);

                try
                {
                    if (Preload.Checked)
                    {
                        string dbPath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\" + OrderText.Text.Trim() + ".db";
                        if (File.Exists(dbPath))
                        {
                            if (LocalDB == null)
                            {
                                LocalDB = new SQLiteConnection("data source=" + dbPath);
                                LocalDB.Open();
                            }
                            if (SQLiteHelper.WholeCheckDownloadStatus(LocalDB, OrderText.Text.Trim()))
                            {

                                if (SQLiteHelper.GetDBMidInfo(LocalDB, OrderText.Text.Trim(), out midAddress1))
                                {
                                    if (UsinglocalIDCheck.Checked)
                                    {
                                        midAddress1.pid = Custom_ProjectID;
                                        MessageBox.Show(LResource.WilluseLocalPID, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    }
                                    else if (midAddress1.pid != Custom_ProjectID && Custom_ProjectID.Trim().Length > 0)
                                    {
                                        if (midAddress1.pid != null)
                                            if (midAddress1.pid.Trim().Length > 0)
                                                PID_Num.Value = Convert.ToDecimal(midAddress1.pid);
                                        MessageBox.Show(LResource.WilluseOnlinePID, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                    midList1 = new MidList()
                                    {
                                        keytype = new Dictionary<string, string>(),
                                        clienttype = midAddress1.ctype,
                                        version = midAddress1.version,
                                        projectid = midAddress1.pid,
                                        host = "LocalPC"
                                    };
                                    if (SQLiteHelper.GetrokuCustomer(LocalDB, OrderText.Text, out RokuCustomer rokuCustomer_1))
                                    {
                                        midList1.rokuCustomer = rokuCustomer_1;
                                    };
                                    if (SQLiteHelper.Getdsn(LocalDB, OrderText.Text, out string firetvdsn))
                                    {
                                        midList1.keytype = new Dictionary<string, string>();
                                        midList1.keytype.Add("DSN", firetvdsn);
                                    };
                                    if (SQLiteHelper.Getwhitebalance(LocalDB, OrderText.Text, out WhiteBalanceInfo whiteBalanceInfo_1))
                                    {
                                        functionSetting1.WBPath = dbPath;
                                        functionSetting1.WriteWB = true;
                                        functionSetting1.NormalRGB = new byte[3];
                                        functionSetting1.CoolRGB = new byte[3];
                                        functionSetting1.WarmRGB = new byte[3];
                                        functionSetting1.NormalRGB[0] = (byte)Convert.ToDouble(whiteBalanceInfo_1.hdmirgain);
                                        functionSetting1.NormalRGB[1] = (byte)Convert.ToDouble(whiteBalanceInfo_1.hdmiggain);
                                        functionSetting1.NormalRGB[2] = (byte)Convert.ToDouble(whiteBalanceInfo_1.hdmibgain);

                                        functionSetting1.CoolRGB[0] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.lrgain) + 256);
                                        functionSetting1.CoolRGB[1] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.lggain) + 256);
                                        functionSetting1.CoolRGB[2] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.lbgain) + 256);

                                        functionSetting1.WarmRGB[0] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.nrgain) + 256);
                                        functionSetting1.WarmRGB[1] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.nggain) + 256);
                                        functionSetting1.WarmRGB[2] = (byte)(Convert.ToDouble(whiteBalanceInfo_1.nbgain) + 256);
                                    };
                                }
                                else
                                {
                                    MessageBox.Show(LResource.FailtoReadLocalDB);
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show(LResource.LocalDBIncomplete);
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show(LResource.NofoundLocalDB);
                            return;
                        }
                    }
                    else
                    {
                        midList1 = new MidList()
                        {
                            keytype = new Dictionary<string, string>(),
                            projectid = Custom_ProjectID,
                            host = "LocalPC"
                        };
                    }

                    OperationPanel operationPanel1 = new OperationPanel(this, LocalDB, ErrorDB, null, functionSetting1, WriteCheck1, ReadCheck1, WriteDone1, Preload.Checked, midList1, OrderText.Text.Trim());
                    operationPanel1.StartPosition = FormStartPosition.Manual;
                    if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width && LocationMark)
                    {
                        LocationMark = false;
                        LocationNum = formlocationmsg.Count;
                    }
                    if (formlocationmsg.Count == 0)
                        operationPanel1.Location = (Point)new Size(this.Right, this.Top);
                    else if ((this.Right + operationPanel1.Size.Width * formlocationmsg.Count) > Screen.PrimaryScreen.Bounds.Width)
                    {
                        Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                        operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * (formlocationmsg.Count - LocationNum), this.Top + operationPanel1.Size.Height);
                    }
                    else
                    {
                        Point point = ((Dictionary<IntPtr, Point>)formlocationmsg[formlocationmsg.Count - 1]).Last().Value;
                        operationPanel1.Location = (Point)new Size(this.Right + operationPanel1.Size.Width * formlocationmsg.Count, this.Top);
                    }
                    operationPanel1.DeleteIntptr += new OperationPanel.DisplayUpdateDelegate(DeleteIntptr);
                    operationPanel1.SNKeyDownEven += new OperationPanel.SNKeyDown(SNKeyDownEven);
                    operationPanel1.AutoKeyRequire += new OperationPanel.AutoKeyRequireDelegate(AutoKeyRequire);
                    IntPtr intPtr = operationPanel1.Handle;
                    Dictionary<IntPtr, Point> part1 = new Dictionary<IntPtr, Point>();
                    part1.Add(intPtr, (Point)new Size(operationPanel1.Right, operationPanel1.Top));
                    formlocationmsg.Add(part1);
                    operationPanel1.Show();
                }
                catch
                {
                    //
                }
            }

            OrderSubmit.Text = LResource.submitbutton;
#if DEBUG

#else
            LockSettingFunction(false);
#endif
            if (!LocalWrite)
            {
                if (!uploadbackground.IsAlive)
                    if (!Preload.Checked || LocalDB != null)
                        uploadbackground.Start();
            }

        }

        /// <summary>
        /// 加载配置
        /// </summary>
        public void LoadJsonConfig()
        {
            StreamReader file = File.OpenText(LocalPath.localpath + "\\Config.json");
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                JObject jObject = (JObject)JToken.ReadFrom(reader);
                reader.Close();
                var COM = jObject["COM"].Value<string>();
                var Baudrate = jObject["Baudrate"].Value<string>();
                var WriteChannelConfig = jObject["WriteChannel"].Value<string>();
                var ChannelSelect = jObject["ChannelSelect"].Value<string>();
                var WriteOSDLanguageConfig = jObject["WriteOSDLanguage"].Value<string>();
                var OSDLanguageSelect = jObject["OSDLanguageSelect"].Value<string>();
                var WriteSHOPLanguageConfig = jObject["WriteSHOPLanguage"].Value<string>();
                var SHOPLanguageSelect = jObject["SHOPLanguageSelect"].Value<string>();
                var WriteWhiteBalanceConfig = jObject["WriteWhiteBalance"].Value<string>();
                var WhiteBalanceInitConfig = jObject["WhiteBalanceInit"].Value<string>();
                var WhiteBalancePath = jObject["WhiteBalancePath"].Value<string>();
                var LastOrder = jObject["LastOrder"].Value<string>();
                var Preloadmode = jObject["Preload"].Value<string>();
                var UsingLocalPID = jObject["UsingLocalPID"].Value<string>();
                Custom_ProjectID = jObject["Custom_ProjectID"].Value<string>();
                functionSetting1.Wait_after_completion = jObject["Wait_after_completion"].Value<int>();
                functionSetting1.EnterFactoryRetry = jObject["EnterFactoryRetry"].Value<int>();
                functionSetting1.AllowNoScanning = jObject["AllowNoScanning"].Value<bool>();
                functionSetting1.ReportTimeOut = jObject["ReportTimeOut"].Value<int>();


                //本地离线抄写时key长度设置获取
                functionSetting1.LocalDidSize = jObject["LocalSize"]["DID"].Value<int>();
                functionSetting1.LocalMacSize = jObject["LocalSize"]["MAC"].Value<int>();
                functionSetting1.LocalHdcpSize = jObject["LocalSize"]["HDCP"].Value<int>();
                functionSetting1.LocalWidiSize = jObject["LocalSize"]["WIDI"].Value<int>();
                functionSetting1.LocalHdcp22Size = jObject["LocalSize"]["HDCP22"].Value<int>();
                functionSetting1.LocalEsnSize = jObject["LocalSize"]["ESN"].Value<int>();
                functionSetting1.LocalWidevineSize = jObject["LocalSize"]["WIDEVINE"].Value<int>();
                functionSetting1.LocalCiSize = jObject["LocalSize"]["CI"].Value<int>();
                functionSetting1.LocalMGKSize = jObject["LocalSize"]["MGK"].Value<int>();
                functionSetting1.LocalFairplaySize = jObject["LocalSize"]["Fairplay"] == null ? (CommonMethod.InsertJsonConfig("LocalSize", "Fairplay") ? -1 : 0) : jObject["LocalSize"]["Fairplay"].Value<int>();
                functionSetting1.LocalECPSize = jObject["LocalSize"]["ECP"] == null ? (CommonMethod.InsertJsonConfig("LocalSize", "ECP") ? -1 : 0) : jObject["LocalSize"]["ECP"].Value<int>();
                functionSetting1.LocalWifiMacSize = jObject["LocalSize"]["WifiMac"] == null ? (CommonMethod.InsertJsonConfig("LocalSize", "WifiMac") ? -1 : 0) : jObject["LocalSize"]["WifiMac"].Value<int>();
                functionSetting1.LocalBTMacSize = jObject["LocalSize"]["BTMac"] == null ? (CommonMethod.InsertJsonConfig("LocalSize", "BTMac") ? -1 : 0) : jObject["LocalSize"]["BTMac"].Value<int>();

                //本地DB离线抄写时是否不允许重复抄写
                functionSetting1.NoDoublewrite = jObject["NodoubleWrite"].Value<bool>();

                //条码限制
                functionSetting1.BarcodeLimit = jObject["BarcodeLimit"].Value<bool>();
                functionSetting1.BarcodeWrite = jObject["BarcodeWrite"] == null ? CommonMethod.AddJsonConfig("BarcodeWrite", false) : jObject["BarcodeWrite"].Value<bool>();
                functionSetting1.BarcodeLength = jObject["BarcodeLength"].Value<int>();
                functionSetting1.BarcodeKeyword = jObject["BarcodeKeyword"].Value<string>();

                //串口延迟
                //functionSetting1.SerailDelay = jObject["SerailDelay"].Value<int>();     // 名字不易理解,使用NextCommandWaitTime代替;
                //SerialCMD.SerialTimeout = jObject["SerialTimeout"].Value<int>();        // 名字不易理解,目前不再使用;

                // G客户防呆措施;
                functionSetting1.UsingGFoolProofing = jObject["UsingGFoolProofing"] == null ? false : jObject["UsingGFoolProofing"].Value<bool>();
                functionSetting1.GFoolProofingCount = jObject["GFoolProofingCount"] == null ? 2 : jObject["GFoolProofingCount"].Value<int>();

                // 导出日规acas与sn;
                if (jObject["ExportSNACASID"] == null)
                {
                    SaveJsonConfig("ExportSNACASID", functionSetting1.ExportSNACASID);
                }
                else
                {
                    functionSetting1.ExportSNACASID = jObject["ExportSNACASID"].Value<bool>();
                }

                // 获取ReadTimeout值;
                if (jObject["ReadTimeout"] == null)
                {
                    SaveJsonConfig("ReadTimeout", SerialCMD.ReadTimeout);
                }
                else
                {
                    functionSetting1.ReadTimeout = SerialCMD.ReadTimeout = jObject["ReadTimeout"].Value<int>();
                }

                // 获取NextCommandWaitTime值;
                if (jObject["NextCommandWaitTime"] == null)
                {
                    SaveJsonConfig("NextCommandWaitTime", SerialCMD.NextCommandWaitTime);
                }
                else
                {
                    functionSetting1.NextCommandWaitTime = SerialCMD.NextCommandWaitTime = jObject["NextCommandWaitTime"].Value<int>();
                }

                #region G客户NTF功能;
                if ( jObject["NTF"] != null )
                {
                    functionSetting1.NTF = jObject["NTF"].Value<bool>();
                }
                else
                {
                    SaveJsonConfig("NTF", false);
                }

                if (jObject["Line"] != null)
                {
                    functionSetting1.Line = jObject["Line"].Value<string>();
                }
                else
                {
                    SaveJsonConfig("Line", "");
                }

                if (jObject["Station"] != null)
                {
                    functionSetting1.Station = jObject["Station"].Value<string>();
                }
                #endregion

                foreach (var ss in jObject["Channel"])  //遍历Channel
                {
                    Dictionary<string, string> ChannelValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(ss.ToString());
                    foreach (string key in ChannelValues.Keys)
                    {
                        ChannelMapList.Add(key, ChannelValues[key]);
                        ChannelList.Items.Add(key);
                    }

                }
                foreach (var ss in jObject["Language"])  //遍历Language
                {
                    Dictionary<string, string> LanguageValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(ss.ToString());
                    foreach (string key in LanguageValues.Keys)
                    {
                        OSDList.Items.Add(key);
                        SHOPList.Items.Add(key);
                        LanguageMapList.Add(key, LanguageValues[key]);
                    }
                }
                foreach (var ss in jObject["CustomCMD"])  //遍历自定义命令表
                {
                    functionSetting1.CustomCMD = JsonConvert.DeserializeObject<Dictionary<string, string>>(ss.ToString());
                }

                //ReadCheck配置读取
                ReadCheck1.PIDReadcheck = jObject["ReadCheck"]["PID"].Value<bool>();
                ReadCheck1.OSDReadcheck = jObject["ReadCheck"]["OSD"].Value<bool>();
                ReadCheck1.SHOPReadcheck = jObject["ReadCheck"]["SHOP"].Value<bool>();
                ReadCheck1.DIDReadcheck = jObject["ReadCheck"]["DID"].Value<bool>();
                ReadCheck1.MacReadcheck = jObject["ReadCheck"]["MAC"].Value<bool>();
                ReadCheck1.HDCPReadcheck = jObject["ReadCheck"]["HDCP"].Value<bool>();
                ReadCheck1.HDCP22Readcheck = jObject["ReadCheck"]["HDCP22"].Value<bool>();
                ReadCheck1.WiDiReadcheck = jObject["ReadCheck"]["WIDI"].Value<bool>();
                ReadCheck1.WidevineReadcheck = jObject["ReadCheck"]["WIDEVINE"].Value<bool>();
                ReadCheck1.ESNReadcheck = jObject["ReadCheck"]["ESN"].Value<bool>();
                ReadCheck1.CI_plusReadcheck = jObject["ReadCheck"]["CI"].Value<bool>();
                ReadCheck1.AttestationReadcheck = jObject["ReadCheck"]["Attestation"].Value<bool>();
                ReadCheck1.MGKReadcheck = jObject["ReadCheck"]["MGK"].Value<bool>();
                ReadCheck1.FairplayReadcheck = jObject["ReadCheck"]["Fairplay"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Fairplay") : jObject["ReadCheck"]["Fairplay"].Value<bool>();
                ReadCheck1.ECPReadcheck = jObject["ReadCheck"]["ECP"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "ECP") : jObject["ReadCheck"]["ECP"].Value<bool>();
                ReadCheck1.WifiMacReadcheck = jObject["ReadCheck"]["WifiMac"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "WifiMac") : jObject["ReadCheck"]["WifiMac"].Value<bool>();
                ReadCheck1.BTMacReadcheck = jObject["ReadCheck"]["BTMac"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "BTMac") : jObject["ReadCheck"]["BTMac"].Value<bool>();
                ReadCheck1.LEKReadcheck = jObject["ReadCheck"]["LEK"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "LEK") : jObject["ReadCheck"]["LEK"].Value<bool>();
                ReadCheck1.PEKReadcheck = jObject["ReadCheck"]["PEK"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "PEK") : jObject["ReadCheck"]["PEK"].Value<bool>();
                ReadCheck1.PlayreadyReadcheck = jObject["ReadCheck"]["Playready"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Playready") : jObject["ReadCheck"]["Playready"].Value<bool>();
                ReadCheck1.HashReadcheck = jObject["ReadCheck"]["Hash"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Hash") : jObject["ReadCheck"]["Hash"].Value<bool>();
                ReadCheck1.DSNReadcheck = jObject["ReadCheck"]["DSN"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "DSN") : jObject["ReadCheck"]["DSN"].Value<bool>();
                ReadCheck1.YouTubeReadcheck = jObject["ReadCheck"]["YouTube"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "YouTube") : jObject["ReadCheck"]["YouTube"].Value<bool>();
                ReadCheck1.EDIDPIDReadcheck = jObject["ReadCheck"]["EDIDPID"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "EDIDPID") : jObject["ReadCheck"]["EDIDPID"].Value<bool>();
                ReadCheck1.EDIDModeNameReadcheck = jObject["ReadCheck"]["EDIDModeName"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "EDIDModeName") : jObject["ReadCheck"]["EDIDModeName"].Value<bool>();
                ReadCheck1.ACASKeyReadcheck = jObject["ReadCheck"]["ACASKey"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "ACASKey") : jObject["ReadCheck"]["ACASKey"].Value<bool>();
                //WriteCheck配置读取
                WriteCheck1.DIDCheckcheck = jObject["WriteCheck"]["DID"].Value<bool>();
                WriteCheck1.MacCheckcheck = jObject["WriteCheck"]["MAC"].Value<bool>();
                WriteCheck1.HDCPCheckcheck = jObject["WriteCheck"]["HDCP"].Value<bool>();
                WriteCheck1.HDCP22Checkcheck = jObject["WriteCheck"]["HDCP22"].Value<bool>();
                WriteCheck1.WiDiCheckcheck = jObject["WriteCheck"]["WIDI"].Value<bool>();
                WriteCheck1.WidevineCheckcheck = jObject["WriteCheck"]["WIDEVINE"].Value<bool>();
                WriteCheck1.ESNCheckcheck = jObject["WriteCheck"]["ESN"].Value<bool>();
                WriteCheck1.CI_plusCheckcheck = jObject["WriteCheck"]["CI"].Value<bool>();
                WriteCheck1.AttestationCheckcheck = jObject["WriteCheck"]["Attestation"].Value<bool>();
                WriteCheck1.MGKCheckcheck = jObject["WriteCheck"]["MGK"].Value<bool>();
                WriteCheck1.FairplayCheckcheck = jObject["WriteCheck"]["Fairplay"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Fairplay") : jObject["WriteCheck"]["Fairplay"].Value<bool>();
                WriteCheck1.ECPCheckcheck = jObject["WriteCheck"]["ECP"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "ECP") : jObject["WriteCheck"]["ECP"].Value<bool>();
                WriteCheck1.WifiMacCheckcheck = jObject["WriteCheck"]["WifiMac"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "WifiMac") : jObject["WriteCheck"]["WifiMac"].Value<bool>();
                WriteCheck1.BTMacCheckcheck = jObject["WriteCheck"]["BTMac"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "BTMac") : jObject["WriteCheck"]["BTMac"].Value<bool>();
                WriteCheck1.LEKCheckcheck = jObject["WriteCheck"]["LEK"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "LEK") : jObject["WriteCheck"]["LEK"].Value<bool>();
                WriteCheck1.PEKCheckcheck = jObject["WriteCheck"]["PEK"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "PEK") : jObject["WriteCheck"]["PEK"].Value<bool>();
                WriteCheck1.PlayreadyCheckcheck = jObject["WriteCheck"]["Playready"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Playready") : jObject["WriteCheck"]["Playready"].Value<bool>();
                WriteCheck1.HashCheckcheck = jObject["WriteCheck"]["Hash"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Hash") : jObject["WriteCheck"]["Hash"].Value<bool>();
                WriteCheck1.DSNCheckcheck = jObject["WriteCheck"]["DSN"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "DSN") : jObject["WriteCheck"]["DSN"].Value<bool>();
                WriteCheck1.YouTubeCheckcheck = jObject["WriteCheck"]["YouTube"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "YouTube") : jObject["WriteCheck"]["YouTube"].Value<bool>();
                WriteCheck1.ACASKeyCheckcheck = jObject["WriteCheck"]["ACASKey"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "ACASKey") : jObject["WriteCheck"]["ACASKey"].Value<bool>();
                //WriteDone配置读取
                WriteDone1.PIDWrite_YesNo = jObject["WriteDone"]["PID"].Value<bool>();
                WriteDone1.PIDWriteDelay = jObject["WriteDone"]["PIDWirteDelay"].Value<int>();
                WriteDone1.ClientTypeCheck_YesNo = jObject["WriteDone"]["ClientType"].Value<bool>();
                WriteDone1.SoftwareVersionCheck_YesNo = jObject["WriteDone"]["SoftwareVersion"].Value<bool>();
                WriteDone1.DIDWrite_YesNo = jObject["WriteDone"]["DID"].Value<bool>();
                WriteDone1.MacWrite_YesNo = jObject["WriteDone"]["MAC"].Value<bool>();
                WriteDone1.HDCPWrite_YesNo = jObject["WriteDone"]["HDCP"].Value<bool>();
                WriteDone1.HDCP22Write_YesNo = jObject["WriteDone"]["HDCP22"].Value<bool>();
                WriteDone1.WiDiWrite_YesNo = jObject["WriteDone"]["WIDI"].Value<bool>();
                WriteDone1.WidevineWrite_YesNo = jObject["WriteDone"]["WIDEVINE"].Value<bool>();
                WriteDone1.ESNWrite_YesNo = jObject["WriteDone"]["ESN"].Value<bool>();
                WriteDone1.CI_plusWrite_YesNo = jObject["WriteDone"]["CI"].Value<bool>();
                WriteDone1.AttestationWrite_YesNo = jObject["WriteDone"]["Attestation"].Value<bool>();
                WriteDone1.MGKWrite_YesNo = jObject["WriteDone"]["MGK"].Value<bool>();
                WriteDone1.FairplayWrite_YesNo = jObject["WriteDone"]["Fairplay"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Fairplay") : jObject["WriteDone"]["Fairplay"].Value<bool>();
                WriteDone1.ECPWrite_YesNo = jObject["WriteDone"]["ECP"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "ECP") : jObject["WriteDone"]["ECP"].Value<bool>();
                WriteDone1.WifiMacWrite_YesNo = jObject["WriteDone"]["WifiMac"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "WifiMac") : jObject["WriteDone"]["WifiMac"].Value<bool>();
                WriteDone1.BTMacWrite_YesNo = jObject["WriteDone"]["BTMac"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "BTMac") : jObject["WriteDone"]["BTMac"].Value<bool>();
                WriteDone1.LEKWrite_YesNo = jObject["WriteDone"]["LEK"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "LEK") : jObject["WriteDone"]["LEK"].Value<bool>();
                WriteDone1.PEKWrite_YesNo = jObject["WriteDone"]["PEK"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "PEK") : jObject["WriteDone"]["PEK"].Value<bool>();
                WriteDone1.PlayreadyWrite_YesNo = jObject["WriteDone"]["Playready"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Playready") : jObject["WriteDone"]["Playready"].Value<bool>();
                WriteDone1.HashWrite_YesNo = jObject["WriteDone"]["Hash"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Hash") : jObject["WriteDone"]["Hash"].Value<bool>();
                WriteDone1.DSNWrite_YesNo = jObject["WriteDone"]["DSN"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "DSN") : jObject["WriteDone"]["DSN"].Value<bool>();
                WriteDone1.AutoWhiteBalance = jObject["WriteDone"]["AutoWhiteBalance"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "AutoWhiteBalance") : jObject["WriteDone"]["AutoWhiteBalance"].Value<bool>();
                WriteDone1.YouTubeWrite_YesNo = jObject["WriteDone"]["YouTube"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "YouTube") : jObject["WriteDone"]["YouTube"].Value<bool>();
                WriteDone1.EDIDPIDWrite_YesNo = jObject["WriteDone"]["EDIDPID"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "EDIDPID") : jObject["WriteDone"]["EDIDPID"].Value<bool>();
                WriteDone1.EDIDModeNameWrite_YesNo = jObject["WriteDone"]["EDIDModeName"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "EDIDModeName") : jObject["WriteDone"]["EDIDModeName"].Value<bool>();
                WriteDone1.ACASKeyWrite_YesNo = jObject["WriteDone"]["ACASKey"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "ACASKey") : jObject["WriteDone"]["ACASKey"].Value<bool>();
                file.Close();
                if (Custom_ProjectID != null)
                    if (Custom_ProjectID.Trim().Length > 0)
                        PID_Num.Value = Convert.ToDecimal(Custom_ProjectID);
                if (TVCOM.Items.Contains(COM))
                    TVCOM.SelectedItem = COM;
                if (TVBaud.Items.Contains(Baudrate))
                    TVBaud.SelectedItem = Baudrate;
                if (ChannelList.Items.Contains(ChannelSelect))
                {
                    ChannelList.SelectedItem = ChannelSelect;
                    functionSetting1.ChannelCode = SerialInit.HexToByte(ChannelMapList[ChannelSelect]);
                }
                if (OSDList.Items.Contains(OSDLanguageSelect))
                {
                    OSDList.SelectedItem = OSDLanguageSelect;
                    functionSetting1.OSDLCode = SerialInit.HexToByte(LanguageMapList[OSDLanguageSelect]);
                }
                if (SHOPList.Items.Contains(SHOPLanguageSelect))
                {
                    SHOPList.SelectedItem = SHOPLanguageSelect;
                    functionSetting1.ShopLCode = SerialInit.HexToByte(LanguageMapList[SHOPLanguageSelect]);
                }

                BarcodeLimit.Checked = functionSetting1.BarcodeLimit;
                BarcodeWrite.Checked = functionSetting1.BarcodeWrite;
                BarCodeKeyCodeText.Text = functionSetting1.BarcodeKeyword;
                BarCodeLengthText.Value = functionSetting1.BarcodeLength;
                Preload.Checked = Preloadmode == "True";
                WriteChannel.Checked = WriteChannelConfig == "True";
                WriteOSD.Checked = WriteOSDLanguageConfig == "True";
                WriteSHOP.Checked = WriteSHOPLanguageConfig == "True";
                WBInit.Checked = WhiteBalanceInitConfig == "True";
                UsinglocalIDCheck.Checked = UsingLocalPID == "True";
                OrderText.Text = LastOrder;
                if (File.Exists(WhiteBalancePath))
                {
                    if (!LoadWBConfig(WhiteBalancePath))
                    {
                        MessageBox.Show(LResource.ReadWBError);
                        WriteWB.Checked = false;
                    }
                    else
                    {
                        WBPath.Text = WhiteBalancePath;
                        WriteWB.Checked = WriteWhiteBalanceConfig == "True";
                    }
                }
                else
                    WriteWB.Checked = false;
            }
        }

        /// <summary>
        /// 加载本地白平衡配置
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public bool LoadWBConfig(string filepath)
        {
            try
            {
                functionSetting1.NormalRGB = new byte[3];
                functionSetting1.CoolRGB = new byte[3];
                functionSetting1.WarmRGB = new byte[3];
                functionSetting1.NormalRGB[0] = (byte)Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "HDMI white R:", null, filepath));
                functionSetting1.NormalRGB[1] = (byte)Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "HDMI white G:", null, filepath));
                functionSetting1.NormalRGB[2] = (byte)Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "HDMI white B:", null, filepath));

                functionSetting1.CoolRGB[0] = (byte)(Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "Cool white R:", null, filepath)) + 256);
                functionSetting1.CoolRGB[1] = (byte)(Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "Cool white G:", null, filepath)) + 256);
                functionSetting1.CoolRGB[2] = (byte)(Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "Cool white B:", null, filepath)) + 256);

                functionSetting1.WarmRGB[0] = (byte)(Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "Warm white R:", null, filepath)) + 256);
                functionSetting1.WarmRGB[1] = (byte)(Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "Warm white G:", null, filepath)) + 256);
                functionSetting1.WarmRGB[2] = (byte)(Convert.ToDouble(Iniconfig.OperateIniFile.ReadIniData("WBA value:", "Warm white B:", null, filepath)) + 256);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        private void ChannelList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string ChannelSelect = ChannelList.SelectedItem.ToString();
            string channelcode = ChannelMapList[ChannelSelect];
            functionSetting1.ChannelCode = SerialInit.HexToByte(channelcode);
            SaveJsonConfig("ChannelSelect", ChannelSelect);
            Log.WriteInfoLog("\r\nSet channel setting to " + ChannelSelect + "\r\nchannel code is " + channelcode);
        }

        private void OSDList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string OSDLanguageSelect = OSDList.SelectedItem.ToString();
            string OSDLcode = LanguageMapList[OSDLanguageSelect];
            functionSetting1.OSDLCode = SerialInit.HexToByte(OSDLcode);
            SaveJsonConfig("OSDLanguageSelect", OSDLanguageSelect);
            Log.WriteInfoLog("\r\nSet channel setting to " + OSDLanguageSelect + "\r\nchannel code is " + OSDLcode);
        }

        private void SHOPList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string SHOPLanguageSelect = SHOPList.SelectedItem.ToString();
            string SHOPLcode = LanguageMapList[SHOPLanguageSelect];
            functionSetting1.ShopLCode = SerialInit.HexToByte(SHOPLcode);
            SaveJsonConfig("SHOPLanguageSelect", SHOPLanguageSelect);
            Log.WriteInfoLog("\r\nSet channel setting to " + SHOPLanguageSelect + "\r\nchannel code is " + SHOPLcode);
        }

        private void skinButton1_Click(object sender, EventArgs e)
        {
            SaveJsonConfig("COM", "COM3");
            string strFileName = null;
            openFileDialog1.Filter = "WBConfig file|*.wba";
            openFileDialog1.FileName = "";
            openFileDialog1.Title = "Please select the WB config file";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                strFileName = System.IO.Path.GetFullPath(openFileDialog1.FileName);
                WBPath.Text = strFileName;
                if (LoadWBConfig(strFileName))
                {
                    functionSetting1.WBFileName = Path.GetFileName(openFileDialog1.FileName);
                    SaveJsonConfig("WhiteBalancePath", strFileName);
                    MessageBox.Show(LResource.LoadWBsuccess);
                }
            }
        }

        private void WriteWB_CheckedChanged(object sender, EventArgs e)
        {
            if (WriteWB.Checked == true)
            {
                if (WBPath.Text.Trim().Length > 0)
                {
                    LoadWBConfig(WBPath.Text.Trim());
                    SaveJsonConfig("WriteWhiteBalance", true);
                }
                else
                {
                    MessageBox.Show(LResource.SelectWBfirst);
                    WriteWB.Checked = false;
                }
            }
            else
            {
                SaveJsonConfig("WriteWhiteBalance", false);
            }
        }

        public void SaveJsonConfig(string node, object value)
        {
            StreamReader file = File.OpenText(LocalPath.localpath + "\\Config.json");
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                JObject jObject = (JObject)JToken.ReadFrom(reader);
                jObject[node] = value.ToString();
                file.Close();
                using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
                {
                    writer.Write(jObject.ToString());    //将JToken.ReadFrom(reader)的数据写入文件,这样的数据有空行。
                }
            }
        }

        private void WBInit_CheckedChanged(object sender, EventArgs e)
        {
            if (WBInit.Checked)
            {
                SaveJsonConfig("WhiteBalanceInit", true);
            }
            else
                SaveJsonConfig("WhiteBalanceInit", false);
        }

        private void WriteChannel_CheckedChanged(object sender, EventArgs e)
        {
            if (WriteChannel.Checked)
            {
                SaveJsonConfig("WriteChannel", true);
            }
            else
                SaveJsonConfig("WriteChannel", false);
        }

        private void WriteOSD_CheckedChanged(object sender, EventArgs e)
        {
            if (WriteOSD.Checked)
            {
                SaveJsonConfig("WriteOSDLanguage", true);
            }
            else
                SaveJsonConfig("WriteOSDLanguage", false);
        }

        private void WriteSHOP_CheckedChanged(object sender, EventArgs e)
        {
            if (WriteSHOP.Checked)
            {
                SaveJsonConfig("WriteSHOPLanguage", true);
            }
            else
                SaveJsonConfig("WriteSHOPLanguage", false);
        }

        private void TVCOM_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveJsonConfig("COM", TVCOM.SelectedItem.ToString());
        }

        private void TVBaud_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveJsonConfig("Baudrate", TVBaud.SelectedItem.ToString());
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        public void LockSettingFunction(bool locksetting)
        {
            ChannelList.Enabled = locksetting;
            WriteOSD.Enabled = locksetting;
            WriteSHOP.Enabled = locksetting;
            WriteChannel.Enabled = locksetting;
            OSDList.Enabled = locksetting;
            SHOPList.Enabled = locksetting;
            skinButton1.Enabled = locksetting;
            WriteOSD.Enabled = locksetting;
            WBInit.Enabled = locksetting;
            WriteWB.Enabled = locksetting;
            OrderText.Enabled = locksetting;
            Preload.Enabled = locksetting;
            PID_Num.Enabled = locksetting;
            BarcodeLimit.Enabled = locksetting;
            BarCodeLengthText.Enabled = locksetting;
            BarCodeKeyCodeText.Enabled = locksetting;
        }

        private void TVCOM_MouseClick(object sender, MouseEventArgs e)
        {
            TVCOM.Items.Clear();
            TVCOM.Items.AddRange(SerialPort.GetPortNames());
        }

        private void CreateKeyManually_Click(object sender, EventArgs e)
        {
            CreateDBManually CreateDBManually1 = new CreateDBManually(TestMode.serverurl, ErrorDB);
            CreateDBManually1.ShowDialog();
        }

        private void Preload_CheckedChanged(object sender, EventArgs e)
        {
            SaveJsonConfig("Preload", Preload.Checked.ToString());
        }

        private void Form1_Move(object sender, EventArgs e)
        {
            if (this.MoveEvent != null)
            {
                Point XY = this.Location;
                XY.X = this.Right;
                XY.Y = this.Top;
                this.MoveEvent(XY, formlocationmsg, LocationNum);
            }
        }

        private void DeleteIntptr(IntPtr intPtr)
        {
            foreach (Dictionary<IntPtr, Point> pairs in formlocationmsg)
            {
                if (pairs.ContainsKey(intPtr))
                {
                    formlocationmsg.Remove(pairs);
                    if (this.MoveEvent != null)
                    {
                        Point XY = this.Location;
                        XY.X = this.Right;
                        XY.Y = this.Top;
                        this.MoveEvent(XY, formlocationmsg, LocationNum);
                    }
                    break;
                }
            }
        }

        private void AutoKeyRequire(IntPtr intPtr, string key, string keytype)
        {
            Task.Run(() =>
            {
                var a = ((Dictionary<IntPtr, Point>)formlocationmsg[0]).First();
                if (a.Key == intPtr)
                {
                    ;//start autokey require
                    if (CommonMethod.AutoGetKeyStatus(midList1.host, key, keytype, ErrorDB))
                    {
                        CommonMethod.AutoGetKey(midList1.host, OrderText.Text.Trim(), key, keytype, ErrorDB);
                    }
                }
            });
        }

        private void SNKeyDownEven(IntPtr intPtr)
        {
            this.KeyDownEvent(formlocationmsg, intPtr);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string count = SQLiteHelper.GetProductionNum(ErrorDB, OrderText.Text.Trim());
            UpdateCountLabel(ProductionNum_Text, count);
        }

        /// <summary>
        /// 刷新订单数量
        /// </summary>
        /// <param name="label"></param>
        /// <param name="str"></param>
        public void UpdateCountLabel(Label label, string str)
        {
            if (label.InvokeRequired)
            {
                BeginInvoke(new Action<string>(x => { label.Text = x.ToString(); }), str);
            }
            else
            {
                label.Text = str;
            }
        }

        /// <summary>
        /// 后台上报
        /// </summary>
        public void UploadBackGround()
        {
            while (true)
            {
                if (CommonMethod.HTTPChecker(StructList.CheckServerConnectionUrl))
                {
                    try
                    {
                        string url;
                        string content;
                        string id;
                        if (SQLiteHelper.GetDelayReportData(ErrorDB, out url, out content, out id))
                            if (content.Contains("@"))
                            {
                                string[] data = content.Split('@');
                                if (CommonMethod.UploadPreloadCopyResult(url, data[1], data[0], LocalDB, ErrorDB, true, id, 30000))
                                {
                                    SQLiteHelper.UpdateReportData(ErrorDB, "CopyDelayReport", "ID", id);
                                }
                            }
                            else
                                if (CommonMethod.UploadCopyResult(content, url, ErrorDB, OrderText.Text.Trim(), true, id, functionSetting1.ReportTimeOut))
                            {
                                SQLiteHelper.UpdateReportData(ErrorDB, "CopyDelayReport", "ID", id);
                            }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteErrorLog(ex.Message);
                    }

                    try
                    {
                        string url;
                        string content;
                        string id;
                        if (SQLiteHelper.GetErrorReportData(ErrorDB, out url, out content, out id))
                        {
                            CommonMethod.ReportErrormsg2(url, content, out bool mark);
                            if (mark)
                            {
                                SQLiteHelper.UpdateReportData(ErrorDB, "ErrorReport", "ID", id);
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        Log.WriteErrorLog(ex.Message);
                    }
                    Thread.Sleep(5000);
                }
                else
                    Thread.Sleep(20000);
            }
        }

        private void PID_Num_ValueChanged(object sender, EventArgs e)
        {
            Custom_ProjectID = PID_Num.Value.ToString();
            SaveJsonConfig("Custom_ProjectID", Custom_ProjectID);
        }

        private void BarCodeLengthText_ValueChanged(object sender, EventArgs e)
        {
            functionSetting1.BarcodeLength = Convert.ToInt32(BarCodeLengthText.Value);
            SaveJsonConfig("BarcodeLength", functionSetting1.BarcodeLength);
        }

        private void BarcodeLimit_CheckedChanged(object sender, EventArgs e)
        {
            functionSetting1.BarcodeLimit = BarcodeLimit.Checked;
            SaveJsonConfig("BarcodeLimit", BarcodeLimit.Checked);
        }

        private void BarCodeKeyCodeText_TextChanged(object sender, EventArgs e)
        {
            functionSetting1.BarcodeKeyword = BarCodeKeyCodeText.Text;
            SaveJsonConfig("BarcodeKeyword", BarCodeKeyCodeText.Text);
        }

        private void UsinglocalIDCheck_CheckedChanged(object sender, EventArgs e)
        {
            SaveJsonConfig("UsingLocalPID", UsinglocalIDCheck.Checked);
        }

        private void BarcodeWrite_CheckedChanged(object sender, EventArgs e)
        {
            functionSetting1.BarcodeWrite = BarcodeWrite.Checked;
            SaveJsonConfig("BarcodeWrite", BarcodeWrite.Checked);
        }
    }
}