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();
        Config_ReadCheck cfg_readcheck = new Config_ReadCheck();
        Config_WriteCheck cfg_writecheck = new Config_WriteCheck();
        Config_WriteDone cfg_writedone = new Config_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()
        {
            #region 试产订单，不需要自动限制条码;
            string strValue = CommonMethod.ReadProfileString("MOKAFactoryTools", "OrderType", "");
            if (strValue.Equals("TR", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            #endregion
            // 如果抄写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, cfg_writecheck, cfg_readcheck, cfg_writedone, 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
                    {
                        // 预绑定模式下：没有db数据库时需要下载json包;
                        if (V2Method.GetMidInfo(TestMode.serverurl, OrderText.Text.Trim(), TestMode.MAC, ErrorDB, out midList1))
                        {
                            if (V2Method.GetOfflineData(midList1.host, 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, cfg_writecheck, cfg_readcheck, cfg_writedone, 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 (V2Method.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 (V2Method.GetMidInfo(TestMode.serverurl, OrderText.Text.Trim(), TestMode.MAC, ErrorDB, out midList1))
                    {
                        CommonMethod.CheckKeyType(midList1.keytype, cfg_writedone, out key2Write);
                        OperationPanel.key2Write = key2Write;

                        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, cfg_writecheck, cfg_readcheck, cfg_writedone, 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"
                        };

                        #region EDID离线模式;
                        if (functionSetting1.edid_offline)
                        {
                            midList1.keytype.Add("edid_pid", functionSetting1.edid_pid);
                            midList1.keytype.Add("edid_model_name", functionSetting1.edid_model_name);
                        }
                        #endregion
                    }

                    OperationPanel operationPanel1 = new OperationPanel(this, LocalDB, ErrorDB, null, functionSetting1, cfg_writecheck, cfg_readcheck, cfg_writedone, 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>();
                if (jObject["Parity"] == null)
                    SaveJsonConfig("Parity", functionSetting1.TVParity);
                functionSetting1.TVParity = jObject["Parity"] != null ? jObject["Parity"].Value<int>() : 0;

                //本地离线抄写时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>();

                functionSetting1.LeaveFactory = jObject["LeaveFactory"] == null ? false : jObject["LeaveFactory"].Value<bool>();
                functionSetting1.SNDoubleTips = jObject["SNDoubleTips"] == null ? false : jObject["SNDoubleTips"].Value<bool>();

                // 导出日规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 EDID离线模式,使用offline账号登录;
                if (jObject["edid_offline"] == null)
                {
                    SaveJsonConfig("edid_offline", functionSetting1.edid_offline);
                }
                else
                {
                    functionSetting1.edid_offline = jObject["edid_offline"].Value<bool>();
                }

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

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

                #region 波兰工厂DHA解决方案
                if (jObject["CheckDHAWaitTime"] == null)
                {
                    SaveJsonConfig("CheckDHAWaitTime", functionSetting1.CheckDHAWaitTime);
                }
                else
                {
                    functionSetting1.CheckDHAWaitTime = jObject["CheckDHAWaitTime"].Value<int>();
                }

                if (jObject["DHA"] == null)
                {
                    SaveJsonConfig("DHA", functionSetting1.DHA);
                }
                else
                {
                    functionSetting1.DHA = jObject["DHA"].Value<bool>();
                }
                #endregion

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

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

                #region 小米FireTV功能模块启用;
                if (jObject["MITVEnable"] != null)
                {
                    functionSetting1.MITVEnable = jObject["MITVEnable"].Value<bool>();
                }
                else
                {
                    SaveJsonConfig("MITVEnable", false);
                }

                // 获取key的url;
                if (jObject["MIKeyUrl"] != null)
                {
                    functionSetting1.MIKeyUrl = jObject["MIKeyUrl"].Value<string>();
                }
                else
                {
                    SaveJsonConfig("MIKeyUrl", functionSetting1.MIKeyUrl);
                }

                // 上报key的url;
                if (jObject["MIKeyReportUrl"] != null)
                {
                    functionSetting1.MIKeyReportUrl = jObject["MIKeyReportUrl"].Value<string>();
                }
                else
                {
                    SaveJsonConfig("MIKeyReportUrl", functionSetting1.MIKeyReportUrl);
                }
                #endregion

                #region 串口重试机制;
                if (jObject["EnableRetry"] != null)
                {
                    functionSetting1.EnableRetry = jObject["EnableRetry"].Value<bool>();
                }
                else
                {
                    SaveJsonConfig("EnableRetry", false);
                }

                if (jObject["RetryCount"] != null)
                {
                    functionSetting1.RetryCount = jObject["RetryCount"].Value<int>();
                }
                else
                {
                    SaveJsonConfig("RetryCount", 3);
                }
                #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());
                }

                #region ReadCheck配置读取
                cfg_readcheck.PIDReadcheck = jObject["ReadCheck"]["PID"].Value<bool>();
                cfg_readcheck.OSDReadcheck = jObject["ReadCheck"]["OSD"].Value<bool>();
                cfg_readcheck.SHOPReadcheck = jObject["ReadCheck"]["SHOP"].Value<bool>();
                cfg_readcheck.DIDReadcheck = jObject["ReadCheck"]["DID"].Value<bool>();
                cfg_readcheck.MacReadcheck = jObject["ReadCheck"]["MAC"].Value<bool>();
                cfg_readcheck.HDCPReadcheck = jObject["ReadCheck"]["HDCP"].Value<bool>();
                cfg_readcheck.HDCP22Readcheck = jObject["ReadCheck"]["HDCP22"].Value<bool>();
                cfg_readcheck.WidevineReadcheck = jObject["ReadCheck"]["WIDEVINE"].Value<bool>();
                cfg_readcheck.ESNReadcheck = jObject["ReadCheck"]["ESN"].Value<bool>();
                cfg_readcheck.CI_plusReadcheck = jObject["ReadCheck"]["CI"].Value<bool>();
                cfg_readcheck.AttestationReadcheck = jObject["ReadCheck"]["Attestation"].Value<bool>();
                cfg_readcheck.MGKReadcheck = jObject["ReadCheck"]["MGK"].Value<bool>();
                cfg_readcheck.FairplayReadcheck = jObject["ReadCheck"]["Fairplay"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Fairplay") : jObject["ReadCheck"]["Fairplay"].Value<bool>();
                cfg_readcheck.ECPReadcheck = jObject["ReadCheck"]["ECP"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "ECP") : jObject["ReadCheck"]["ECP"].Value<bool>();
                cfg_readcheck.WifiMacReadcheck = jObject["ReadCheck"]["WifiMac"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "WifiMac") : jObject["ReadCheck"]["WifiMac"].Value<bool>();
                cfg_readcheck.BTMacReadcheck = jObject["ReadCheck"]["BTMac"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "BTMac") : jObject["ReadCheck"]["BTMac"].Value<bool>();
                cfg_readcheck.LEKReadcheck = jObject["ReadCheck"]["LEK"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "LEK") : jObject["ReadCheck"]["LEK"].Value<bool>();
                cfg_readcheck.PEKReadcheck = jObject["ReadCheck"]["PEK"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "PEK") : jObject["ReadCheck"]["PEK"].Value<bool>();
                cfg_readcheck.PlayreadyReadcheck = jObject["ReadCheck"]["Playready"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Playready") : jObject["ReadCheck"]["Playready"].Value<bool>();
                cfg_readcheck.HashReadcheck = jObject["ReadCheck"]["Hash"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Hash") : jObject["ReadCheck"]["Hash"].Value<bool>();
                cfg_readcheck.DSNReadcheck = jObject["ReadCheck"]["DSN"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "DSN") : jObject["ReadCheck"]["DSN"].Value<bool>();
                cfg_readcheck.YouTubeReadcheck = jObject["ReadCheck"]["YouTube"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "YouTube") : jObject["ReadCheck"]["YouTube"].Value<bool>();
                cfg_readcheck.EDIDPIDReadcheck = jObject["ReadCheck"]["EDIDPID"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "EDIDPID") : jObject["ReadCheck"]["EDIDPID"].Value<bool>();
                cfg_readcheck.EDIDModeNameReadcheck = jObject["ReadCheck"]["EDIDModeName"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "EDIDModeName") : jObject["ReadCheck"]["EDIDModeName"].Value<bool>();
                cfg_readcheck.ACASKeyReadcheck = jObject["ReadCheck"]["ACASKey"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "ACASKey") : jObject["ReadCheck"]["ACASKey"].Value<bool>();
                cfg_readcheck.FVPReadcheck = jObject["ReadCheck"]["FVP"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "FVP") : jObject["ReadCheck"]["FVP"].Value<bool>();
                cfg_readcheck.DAKReadcheck = jObject["ReadCheck"]["DAK"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "DAK") : jObject["ReadCheck"]["DAK"].Value<bool>();
                cfg_readcheck.DolbyReadcheck = jObject["ReadCheck"]["Dolby"] == null ? CommonMethod.InsertJsonConfig("ReadCheck", "Dolby") : jObject["ReadCheck"]["Dolby"].Value<bool>();
                #endregion

                #region WriteCheck配置读取
                cfg_writecheck.DIDCheckcheck = jObject["WriteCheck"]["DID"].Value<bool>();
                cfg_writecheck.MacCheckcheck = jObject["WriteCheck"]["MAC"].Value<bool>();
                cfg_writecheck.HDCPCheckcheck = jObject["WriteCheck"]["HDCP"].Value<bool>();
                cfg_writecheck.HDCP22Checkcheck = jObject["WriteCheck"]["HDCP22"].Value<bool>();
                cfg_writecheck.WidevineCheckcheck = jObject["WriteCheck"]["WIDEVINE"].Value<bool>();
                cfg_writecheck.ESNCheckcheck = jObject["WriteCheck"]["ESN"].Value<bool>();
                cfg_writecheck.CI_plusCheckcheck = jObject["WriteCheck"]["CI"].Value<bool>();
                cfg_writecheck.AttestationCheckcheck = jObject["WriteCheck"]["Attestation"].Value<bool>();
                cfg_writecheck.MGKCheckcheck = jObject["WriteCheck"]["MGK"].Value<bool>();
                cfg_writecheck.FairplayCheckcheck = jObject["WriteCheck"]["Fairplay"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Fairplay") : jObject["WriteCheck"]["Fairplay"].Value<bool>();
                cfg_writecheck.ECPCheckcheck = jObject["WriteCheck"]["ECP"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "ECP") : jObject["WriteCheck"]["ECP"].Value<bool>();
                cfg_writecheck.WifiMacCheckcheck = jObject["WriteCheck"]["WifiMac"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "WifiMac") : jObject["WriteCheck"]["WifiMac"].Value<bool>();
                cfg_writecheck.BTMacCheckcheck = jObject["WriteCheck"]["BTMac"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "BTMac") : jObject["WriteCheck"]["BTMac"].Value<bool>();
                cfg_writecheck.LEKCheckcheck = jObject["WriteCheck"]["LEK"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "LEK") : jObject["WriteCheck"]["LEK"].Value<bool>();
                cfg_writecheck.PEKCheckcheck = jObject["WriteCheck"]["PEK"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "PEK") : jObject["WriteCheck"]["PEK"].Value<bool>();
                cfg_writecheck.PlayreadyCheckcheck = jObject["WriteCheck"]["Playready"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Playready") : jObject["WriteCheck"]["Playready"].Value<bool>();
                cfg_writecheck.HashCheckcheck = jObject["WriteCheck"]["Hash"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Hash") : jObject["WriteCheck"]["Hash"].Value<bool>();
                cfg_writecheck.DSNCheckcheck = jObject["WriteCheck"]["DSN"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "DSN") : jObject["WriteCheck"]["DSN"].Value<bool>();
                cfg_writecheck.YouTubeCheckcheck = jObject["WriteCheck"]["YouTube"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "YouTube") : jObject["WriteCheck"]["YouTube"].Value<bool>();
                cfg_writecheck.ACASKeyCheckcheck = jObject["WriteCheck"]["ACASKey"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "ACASKey") : jObject["WriteCheck"]["ACASKey"].Value<bool>();
                cfg_writecheck.FVPCheckcheck = jObject["WriteCheck"]["FVP"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "FVP") : jObject["WriteCheck"]["FVP"].Value<bool>();
                cfg_writecheck.DAKCheckcheck = jObject["WriteCheck"]["DAK"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "DAK") : jObject["WriteCheck"]["DAK"].Value<bool>();
                cfg_writecheck.DolbyCheckcheck = jObject["WriteCheck"]["Dolby"] == null ? CommonMethod.InsertJsonConfig("WriteCheck", "Dolby") : jObject["WriteCheck"]["Dolby"].Value<bool>();
                #endregion

                #region WriteDone配置读取
                cfg_writedone.PIDWrite_YesNo = jObject["WriteDone"]["PID"].Value<bool>();
                cfg_writedone.PIDWriteDelay = jObject["WriteDone"]["PIDWirteDelay"].Value<int>();
                cfg_writedone.ClientTypeCheck_YesNo = jObject["WriteDone"]["ClientType"].Value<bool>();
                cfg_writedone.SoftwareVersionCheck_YesNo = jObject["WriteDone"]["SoftwareVersion"].Value<bool>();
                cfg_writedone.DIDWrite_YesNo = jObject["WriteDone"]["DID"].Value<bool>();
                cfg_writedone.MacWrite_YesNo = jObject["WriteDone"]["MAC"].Value<bool>();
                cfg_writedone.HDCPWrite_YesNo = jObject["WriteDone"]["HDCP"].Value<bool>();
                cfg_writedone.HDCP22Write_YesNo = jObject["WriteDone"]["HDCP22"].Value<bool>();
                cfg_writedone.WidevineWrite_YesNo = jObject["WriteDone"]["WIDEVINE"].Value<bool>();
                cfg_writedone.ESNWrite_YesNo = jObject["WriteDone"]["ESN"].Value<bool>();
                cfg_writedone.CI_plusWrite_YesNo = jObject["WriteDone"]["CI"].Value<bool>();
                cfg_writedone.AttestationWrite_YesNo = jObject["WriteDone"]["Attestation"].Value<bool>();
                cfg_writedone.MGKWrite_YesNo = jObject["WriteDone"]["MGK"].Value<bool>();
                cfg_writedone.FairplayWrite_YesNo = jObject["WriteDone"]["Fairplay"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Fairplay") : jObject["WriteDone"]["Fairplay"].Value<bool>();
                cfg_writedone.ECPWrite_YesNo = jObject["WriteDone"]["ECP"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "ECP") : jObject["WriteDone"]["ECP"].Value<bool>();
                cfg_writedone.WifiMacWrite_YesNo = jObject["WriteDone"]["WifiMac"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "WifiMac") : jObject["WriteDone"]["WifiMac"].Value<bool>();
                cfg_writedone.BTMacWrite_YesNo = jObject["WriteDone"]["BTMac"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "BTMac") : jObject["WriteDone"]["BTMac"].Value<bool>();
                cfg_writedone.LEKWrite_YesNo = jObject["WriteDone"]["LEK"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "LEK") : jObject["WriteDone"]["LEK"].Value<bool>();
                cfg_writedone.PEKWrite_YesNo = jObject["WriteDone"]["PEK"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "PEK") : jObject["WriteDone"]["PEK"].Value<bool>();
                cfg_writedone.PlayreadyWrite_YesNo = jObject["WriteDone"]["Playready"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Playready") : jObject["WriteDone"]["Playready"].Value<bool>();
                cfg_writedone.HashWrite_YesNo = jObject["WriteDone"]["Hash"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Hash") : jObject["WriteDone"]["Hash"].Value<bool>();
                cfg_writedone.DSNWrite_YesNo = jObject["WriteDone"]["DSN"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "DSN") : jObject["WriteDone"]["DSN"].Value<bool>();
                cfg_writedone.AutoWhiteBalance = jObject["WriteDone"]["AutoWhiteBalance"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "AutoWhiteBalance") : jObject["WriteDone"]["AutoWhiteBalance"].Value<bool>();
                cfg_writedone.YouTubeWrite_YesNo = jObject["WriteDone"]["YouTube"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "YouTube") : jObject["WriteDone"]["YouTube"].Value<bool>();
                cfg_writedone.EDIDPIDWrite_YesNo = jObject["WriteDone"]["EDIDPID"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "EDIDPID") : jObject["WriteDone"]["EDIDPID"].Value<bool>();
                cfg_writedone.EDIDModeNameWrite_YesNo = jObject["WriteDone"]["EDIDModeName"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "EDIDModeName") : jObject["WriteDone"]["EDIDModeName"].Value<bool>();
                cfg_writedone.ACASKeyWrite_YesNo = jObject["WriteDone"]["ACASKey"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "ACASKey") : jObject["WriteDone"]["ACASKey"].Value<bool>();
                cfg_writedone.FVPWrite_YesNo = jObject["WriteDone"]["FVP"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "FVP") : jObject["WriteDone"]["FVP"].Value<bool>();
                cfg_writedone.DAKWrite_YesNo = jObject["WriteDone"]["DAK"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "DAK") : jObject["WriteDone"]["DAK"].Value<bool>();
                cfg_writedone.DolbyWrite_YesNo = jObject["WriteDone"]["Dolby"] == null ? CommonMethod.InsertJsonConfig("WriteDone", "Dolby") : jObject["WriteDone"]["Dolby"].Value<bool>();
                #endregion
                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 (V2Method.ReportOfflineData(url, data[1], data[0], LocalDB, ErrorDB, true, id))
                                {
                                    SQLiteHelper.UpdateReportData(ErrorDB, "CopyDelayReport", "ID", id);
                                }
                            }
                            else if (V2Method.ReportOnlineData(url, OrderText.Text.Trim(), content, ErrorDB,  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))
                        {
                            bool mark = false;
                            if ( url.EndsWith("smes/RecordKey") )
                            {
                                GMethod.ReportDataBurningResultToMES(url, content, out mark);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg2(url, content, out 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);
        }
    }
}
