using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows.Forms;
using CsvReadWrite;

using MySql.Data.MySqlClient;//Mysql
using connectorMySQL;//クラス用

using System.IO;

namespace BR_RCV
{
    public partial class Form1 : Form
    {
        //グローバル変数
        private List<List<string>> Rcvs = new List<List<string>>();

        private List<List<string>> tcpTargets = new List<List<string>>();

        private List<string> csvPath = new List<string>();

        private List<List<string>> Targets = new List<List<string>>();
        private List<List<string>> Targets_PQ = new List<List<string>>();
        private List<List<string>> McNames = new List<List<string>>();
        private List<List<string>> Evs = new List<List<string>>();
        private List<List<string>> Errs = new List<List<string>>();

        string ChangeTime = "08:00";
        string[] LineNames = {"mc20","mc21","mc22","mc23","mc23","mc24","office" };

        //0 : db info
        //1-7 target IP

        private void Form1_Load(object sender, EventArgs e)
        {

            //string dtExport = checkStatusReturn("C:\\MySource\\TomasTech\\BR_RCV\\BR_RCV\\bin\\Debug\\mc23-1\\info.csv");
         


            //return;
            //target list よみこみ
            //target ip, port
            List<string> tmp = null;
            listBox1.HorizontalScrollbar = true;
            listBox1.Items.Clear();



            try
            {
                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\tcpTargetList.csv"))
                {

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        tcpTargets.Add(tmp);

                    }

                }//using end

                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\TargetList.csv"))
                {//mysql

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        Targets.Add(tmp);

                    }

                }//using end\

                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\TargetList_PQ.csv"))
                {//mysql

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        Targets_PQ.Add(tmp);

                    }
                }

                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\McNameList.csv"))
                {//McName

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        McNames.Add(tmp);

                    }

                }//using end

                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\EvList.csv"))
                {//Ev

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        Evs.Add(tmp);

                    }

                }//using end

                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\ErrList.csv"))
                {//McName

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        Errs.Add(tmp);

                    }

                }//using end




            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            //rcv data 初期化
            for (int i = 0; i < 7; i++)
            {
                List<string> tmps = new List<string>();
                tmps.Add("none");
                tmps.Add(System.DateTime.Now.ToString("yyyyMMddHHmmss"));
                Rcvs.Add(tmps);
            }

            //初期処理
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\mc20\\info.csv");
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\mc21\\info.csv");
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\mc22\\info.csv");
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\mc23-1\\info.csv");
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\mc23-2\\info.csv");
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\mc24\\info.csv");
            csvPath.Add(System.IO.Directory.GetCurrentDirectory() + "\\office\\info.csv");



            UpdateText();
            //timer start

            backgroundWorker1.RunWorkerAsync(tcpTargets[1]);
            backgroundWorker2.RunWorkerAsync(tcpTargets[2]);
            backgroundWorker3.RunWorkerAsync(tcpTargets[3]);
            backgroundWorker4.RunWorkerAsync(tcpTargets[4]);
            backgroundWorker5.RunWorkerAsync(tcpTargets[5]);
            backgroundWorker6.RunWorkerAsync(tcpTargets[6]);
            backgroundWorker7.RunWorkerAsync(tcpTargets[7]);
      
            timer1.Start();

            timer2.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            try
            {
                if (backgroundWorker1.IsBusy == false)
                {
                    backgroundWorker1.RunWorkerAsync(tcpTargets[1]);
                }

                if (backgroundWorker2.IsBusy == false)
                {
                    backgroundWorker2.RunWorkerAsync(tcpTargets[2]);
                }

                if (backgroundWorker3.IsBusy == false)
                {
                    backgroundWorker3.RunWorkerAsync(tcpTargets[3]);
                }

                if (backgroundWorker4.IsBusy == false)
                {
                    backgroundWorker4.RunWorkerAsync(tcpTargets[4]);
                }

                if (backgroundWorker5.IsBusy == false)
                {
                    backgroundWorker5.RunWorkerAsync(tcpTargets[5]);
                }

                if (backgroundWorker6.IsBusy == false)
                {
                    backgroundWorker6.RunWorkerAsync(tcpTargets[6]);
                }

                if (backgroundWorker7.IsBusy == false)
                {
                    backgroundWorker7.RunWorkerAsync(tcpTargets[7]);
                }

                if (backgroundWorker_okaya.IsBusy == false)
                {
                    backgroundWorker_okaya.RunWorkerAsync(tcpTargets[7]);
                }

                if (backgroundWorker_okaya_M25.IsBusy == false)
                {
                    backgroundWorker_okaya_M25.RunWorkerAsync(tcpTargets[1]);
                }

                if (backgroundWorker_okaya_M26.IsBusy == false)
                {
                    backgroundWorker_okaya_M26.RunWorkerAsync(tcpTargets[3]);
                }

            }
            catch (Exception x)
            {
                textBox14.Text = x.ToString();
            }
            timer1.Start();
        }



        #region "25 26 27"
        protected override System.Windows.Forms.CreateParams CreateParams
        {
            get
            {
                const int CS_NOCLOSE = 0x200;

                System.Windows.Forms.CreateParams createParams = base.CreateParams;
                createParams.ClassStyle |= CS_NOCLOSE;

                return createParams;
            }
        }

        public Form1()
        {
            InitializeComponent();
        }

        //CSV保存
        //DataTableをcsvとして保存 UTF8
        /// <summary>
        /// DataTableの内容をCSVファイルに保存する
        /// </summary>
        /// <param name="dt">CSVに変換するDataTable</param>
        /// <param name="csvPath">保存先のCSVファイルのパス</param>
        /// <param name="writeHeader">ヘッダを書き込む時はtrue。</param>
        public void ConvertDataTableToCsv(
            DataTable dt, string csvPath, bool writeHeader)
        {
            //CSVファイルに書き込むときに使うEncoding
            System.Text.Encoding enc =
                System.Text.Encoding.UTF8;

            //書き込むファイルを開く
            System.IO.StreamWriter sr =
                new System.IO.StreamWriter(csvPath, false, enc);

            int colCount = dt.Columns.Count;
            int lastColIndex = colCount - 1;

            //ヘッダを書き込む
            if (writeHeader)
            {
                for (int i = 0; i < colCount; i++)
                {
                    //ヘッダの取得
                    string field = dt.Columns[i].Caption;
                    //"で囲む
                    field = EncloseDoubleQuotesIfNeed(field);
                    //フィールドを書き込む
                    sr.Write(field);
                    //カンマを書き込む
                    if (lastColIndex > i)
                    {
                        sr.Write(',');
                    }
                }
                //改行する
                sr.Write("\r\n");
            }

            //レコードを書き込む
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < colCount; i++)
                {
                    //フィールドの取得
                    string field = row[i].ToString();
                    //"で囲む
                    field = EncloseDoubleQuotesIfNeed(field);
                    //フィールドを書き込む
                    sr.Write(field);
                    //カンマを書き込む
                    if (lastColIndex > i)
                    {
                        sr.Write(',');
                    }
                }
                //改行する
                sr.Write("\r\n");
            }

            //閉じる
            sr.Close();
        }

        /// <summary>
        /// 必要ならば、文字列をダブルクォートで囲む
        /// </summary>
        private string EncloseDoubleQuotesIfNeed(string field)
        {
            if (NeedEncloseDoubleQuotes(field))
            {
                return EncloseDoubleQuotes(field);
            }
            return field;
        }

        /// <summary>
        /// 文字列をダブルクォートで囲む
        /// </summary>
        private string EncloseDoubleQuotes(string field)
        {
            if (field.IndexOf('"') > -1)
            {
                //"を""とする
                field = field.Replace("\"", "\"\"");
            }
            return "\"" + field + "\"";
        }

        /// <summary>
        /// 文字列をダブルクォートで囲む必要があるか調べる
        /// </summary>
        private bool NeedEncloseDoubleQuotes(string field)
        {
            return field.IndexOf('"') > -1 ||
                field.IndexOf(',') > -1 ||
                field.IndexOf('\r') > -1 ||
                field.IndexOf('\n') > -1 ||
                field.StartsWith(" ") ||
                field.StartsWith("\t") ||
                field.EndsWith(" ") ||
                field.EndsWith("\t");
        }//CSV保存 ここまで

        //DataTable sort
        /// <summary>
        /// 指定したDataTableを対象にsort文字列で並び替えた結果を返します。
        /// </summary>
        /// <param name="dt">並び替え対象となるDataTableです。</param>
        /// <param name="sort">ソート条件</param>
        /// <returns>並び替え後のDataTalbeです。</returns>
        static public DataTable GetSortedDataTable(DataTable dt, string express, string sort)
        {
            // dtのスキーマや制約をコピーしたDataTableを作成します。
            DataTable table = dt.Clone();

            DataRow[] rows = dt.Select(express, sort);

            foreach (DataRow row in rows)
            {
                DataRow addRow = table.NewRow();

                // カラム情報をコピーします。
                addRow.ItemArray = row.ItemArray;

                // DataTableに格納します。
                table.Rows.Add(addRow);
            }

            return table;
        }//DataTable sort end

      
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //[0] ID [1] targ IP [2] port
            List<string>targ = (e.Argument as List<string>);

            //TCP通信　タイムアウトでリトライ?
            // 接続先IPと使用ポート番号
            IPAddress ServerIP =  IPAddress.Parse(targ[1]);
            int portNo = int.Parse(targ[2]);           

            // 接続
            IPEndPoint remoteEP = new IPEndPoint(ServerIP, portNo);

            Socket client;
           
            bool RcvFinish = false;
            int size = 0;
            string receiveString = "";

            List<string> ans = new List<string>();
            ans.Add(targ[0]);
            ans.Add("none");

            while (RcvFinish == false)//受信完了まで
            {
                client = new Socket(AddressFamily.InterNetwork,
                                       SocketType.Stream,
                                       ProtocolType.Tcp);


                while (client.Connected == false)
                {
                    try
                    {
                       // Console.WriteLine("接続中...");
                        client.Connect(remoteEP);
                        //Console.WriteLine("接続完了!\n");
                    }
                    catch (SocketException)
                    {
                        //Console.WriteLine("接続失敗!!! 再接続します。\n");
                    }
                }

                // 文字列送信
                //Console.Write("送信文字列 ->");
                //string sendString = Console.ReadLine();
                //byte[] sendData = Encoding.UTF8.GetBytes(sendString);
                //client.Send(sendData, sendData.Length, SocketFlags.None);
                //Console.Write("送信しました。\n");

                // 文字列受信
                //Console.WriteLine("サーバから受信中...");
                byte[] receiveData = new byte[1000];

                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 30000);
                size = 0;
                receiveString = "";
                try
                {
                    size = client.Receive(receiveData);
                    receiveString = Encoding.GetEncoding(932).GetString(receiveData, 0, size);
                }
                catch(SocketException)
                {
                    //time out
                    size = 0;
                }
                //Console.WriteLine("受信完了!");
                //Console.WriteLine("{0}\n", receiveString);

                // 切断
                if (client != null)
                {
                    try
                    {
                        client.Disconnect(false);
                    }
                    catch(Exception exxx)
                    {

                    }
                }
                //Console.WriteLine("切断");
                if(size != 0)
                {
                    RcvFinish = true;
                }
            }//while end
            //受信データを返す
            ans[1] = receiveString.TrimEnd();
            e.Result = ans;

        }

        //forMC27
        private bool receiveFileFtp(string targetPath, string savePath,string targetIP)
        {


            bool ans = true;

            Ping checker = new Ping();
            System.Net.NetworkInformation.PingReply reply = checker.Send(targetIP, 50);
            if (reply.Status != System.Net.NetworkInformation.IPStatus.Success)
            {
                return false;
            }
                //ダウンロードするファイルのURI
                Uri u = new Uri(targetPath);//Uri("ftp://localhost/test.txt");
            //ダウンロードしたファイルの保存先
            string downFile = savePath;//"C:\\test.txt";
            try
            {
                //FtpWebRequestの作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                    System.Net.WebRequest.Create(u);
                //ログインユーザー名とパスワードを設定
                ftpReq.Credentials = new System.Net.NetworkCredential("keyence", "keyence");
                //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")を設定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                //要求の完了後に接続を閉じる
                ftpReq.KeepAlive = false;
                //ASCIIモードで転送する
                ftpReq.UseBinary = false;
                //PASSIVEモードを無効にする
                ftpReq.UsePassive = false;

                //FtpWebResponseを取得
                System.Net.FtpWebResponse ftpRes = null;

                 ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //ファイルをダウンロードするためのStreamを取得
                System.IO.Stream resStrm = ftpRes.GetResponseStream();
                //ダウンロードしたファイルを書き込むためのFileStreamを作成
                System.IO.FileStream fs = new System.IO.FileStream(
                    downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                //ダウンロードしたデータを書き込む
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = resStrm.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                        break;
                    fs.Write(buffer, 0, readSize);
                }
                fs.Close();
                resStrm.Close();

                //FTPサーバーから送信されたステータスを表示
                Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
                //閉じる
                ftpRes.Close();
            }
            catch (Exception ees)
            {
                //MessageBox.Show(ees.Message);
                ans = false;
            }
            return ans;
        }
        private bool SendFileFtp(string targetPath, string savePath,string targetIP)
        {
            bool ans = true;
            Ping checker = new Ping();
            System.Net.NetworkInformation.PingReply reply = checker.Send(targetIP, 50);
            if (reply.Status != System.Net.NetworkInformation.IPStatus.Success)
            {
                return false;
            }

            //アップロードするファイル
            string upFile = savePath;//"C:\\test.txt";
            //アップロード先のURI
            Uri u = new Uri(targetPath);//("ftp://localhost/test.txt");

            try
            {
                //FtpWebRequestの作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                    System.Net.WebRequest.Create(u);
                //ログインユーザー名とパスワードを設定
                ftpReq.Credentials = new System.Net.NetworkCredential("keyence", "keyence");
                //MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
                //要求の完了後に接続を閉じる
                ftpReq.KeepAlive = false;
                //ASCIIモードで転送する
                ftpReq.UseBinary = false;
                //PASVモードを無効にする
                ftpReq.UsePassive = false;

                //ファイルをアップロードするためのStreamを取得
                System.IO.Stream reqStrm = ftpReq.GetRequestStream();
                //アップロードするファイルを開く
                System.IO.FileStream fs = new System.IO.FileStream(
                    upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                //アップロードStreamに書き込む
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = fs.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                        break;
                    reqStrm.Write(buffer, 0, readSize);
                }
                fs.Close();
                reqStrm.Close();

                //FtpWebResponseを取得
                System.Net.FtpWebResponse ftpRes = null;
                
                   ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //FTPサーバーから送信されたステータスを表示
                Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
                //閉じる
                ftpRes.Close();
            }
            catch (Exception snd)
            {
                MessageBox.Show(snd.Message);
                ans = false;
            }

            return ans;

        }


        private void mc27_backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> targ = (e.Argument as List<string>);
            bool RcvFinish = false;
            int size = 0;
            string receiveString = "";
            int id = int.Parse(targ[0]);
            string lastReads = Rcvs[id - 1][1];
            List<string> ans = new List<string>();
            ans.Add(targ[0]);
            ans.Add("none");
            ans.Add(lastReads);
            string savePath = System.IO.Directory.GetCurrentDirectory() + "\\scans.csv";
            string tgtPath = "ftp://192.168.65.222/%2fFlashDisk/BT_FILES/drv1/SendData/scans.csv";

            bool fok = receiveFileFtp(tgtPath,savePath,"192.168.65.222");
            List<string> tmp = new List<string>();
            List<List<string>> scanResult = new List<List<string>>();
            if (fok)
            {
                using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\scans.csv"))
                {

                    while ((tmp = csv.ReadRow()) != null)
                    {
                        scanResult.Add(tmp);

                    }

                }//using end

                DateTime ScanDate = System.DateTime.ParseExact(scanResult[0][1],
                    "yyyyMMddHHmmss",
                    System.Globalization.DateTimeFormatInfo.InvariantInfo,
                    System.Globalization.DateTimeStyles.None);

                DateTime lastScanDate = System.DateTime.ParseExact(lastReads,
                    "yyyyMMddHHmmss",
                    System.Globalization.DateTimeFormatInfo.InvariantInfo,
                    System.Globalization.DateTimeStyles.None);


                if (ScanDate > lastScanDate)
                {
                    ans[1] = scanResult[0][0];
                    ans[2] = scanResult[0][1];

                }
                else
                {
                    ans[1] = "skip";
                }

            }
            //else
            //{
                //ans[1] = receiveString.TrimEnd();
                e.Result = ans;
            //}


        }

        private void mc27_backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            if (result[1] != "skip")
            {
                //表示更新
                Rcvs[id - 1][0] = result[1];
                Rcvs[id - 1][1] = result[2];//System.DateTime.Now.ToString("yyyyMMddHHmmss");
                var cons = new Connector();
                //DBへpush
                if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
                {
                    cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                    cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                    cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                    //insert
                    string lineName = "mc23";
                    string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                    string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                    Rcvs[id - 1][1], result[1], lineName
                                                    );

                    cons.insert(cmd_key + cmd_val);

                    cons.Close();
                }

                UpdateText();
                makeCSV(3);

                cons = new Connector();
                DataTable logs = new DataTable();
                /*
                //DBへpush
                if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
                {
                    cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc22 WHERE " + getRangeTxt(), logs);

                    cons.Close();
                }
                if (logs.Rows.Count > 0)
                {
                    ConvertDataTableToCsv(logs, @"D:\scanLog\mc22\" + getLogFileName("mc22") + ".csv", true);
                }
                */
            }

            backgroundWorker4.RunWorkerAsync(tcpTargets[4]);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            //表示更新
            Rcvs[id-1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1],tcpTargets[0][2],tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                //insert
                string lineName = "mc20";
                string cmd_key = "insert into sch_"+lineName+"(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1],lineName
                                                );

                    cons.insert(cmd_key + cmd_val);


                cons.Close();
            }

                
                UpdateText();
            makeCSV(0);

            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc20 WHERE "+getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs,@"D:\scanLog\mc20\"+getLogFileName("mc20")+".csv",true);
            }
            backgroundWorker1.RunWorkerAsync(tcpTargets[1]);

        }

        private void UpdateText()
        {
            try
            {
                textBox1.Text = Rcvs[0][0];
                textBox1.Update();
                textBox2.Text = Rcvs[0][1];
                textBox2.Update();

                textBox3.Text = Rcvs[1][0];
                textBox3.Update();
                textBox4.Text = Rcvs[1][1];
                textBox4.Update();

                textBox5.Text = Rcvs[2][0];
                textBox5.Update();
                textBox6.Text = Rcvs[2][1];
                textBox6.Update();

                textBox7.Text = Rcvs[3][0];
                textBox7.Update();
                textBox8.Text = Rcvs[3][1];
                textBox8.Update();

                textBox9.Text = Rcvs[4][0];
                textBox9.Update();
                textBox10.Text = Rcvs[4][1];
                textBox10.Update();

                textBox11.Text = Rcvs[5][0];
                textBox11.Update();
                textBox12.Text = Rcvs[5][1];
                textBox12.Update();

                textBox13.Text = Rcvs[6][0];
                textBox13.Update();
                textBox14.Text = Rcvs[6][1];
                textBox14.Update();

            }
            catch(Exception ex)
            {

            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            //表示更新
            Rcvs[id - 1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                //insert
                string lineName = "mc21";
                string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1], lineName
                                                );

                cons.insert(cmd_key + cmd_val);


                cons.Close();
            }

            UpdateText();
            makeCSV(1);

            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc21 WHERE " + getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs, @"D:\scanLog\mc21\" + getLogFileName("mc21") + ".csv", true);
            }

            backgroundWorker2.RunWorkerAsync(tcpTargets[2]);

        }

        private void backgroundWorker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            //表示更新
            Rcvs[id - 1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                //insert
                string lineName = "mc22";
                string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1], lineName
                                                );

                cons.insert(cmd_key + cmd_val);

                cons.Close();
            }

            UpdateText();
            makeCSV(2);

            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc22 WHERE " + getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs, @"D:\scanLog\mc22\" + getLogFileName("mc22") + ".csv", true);
            }


            backgroundWorker3.RunWorkerAsync(tcpTargets[3]);
        }

        private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            //表示更新
            Rcvs[id - 1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);
                //insert
                string lineName = "mc23";
                string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1], lineName
                                                );

                cons.insert(cmd_key + cmd_val);


                cons.Close();
            }

            UpdateText();
            makeCSV(3);

            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc23 WHERE " + getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs, @"D:\scanLog\mc23\" + getLogFileName("mc23") + ".csv", true);
            }

            backgroundWorker4.RunWorkerAsync(tcpTargets[4]);
        }

        private void backgroundWorker5_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            //表示更新
            Rcvs[id - 1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                //insert
                string lineName = "mc23";
                string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1], lineName
                                                );

                cons.insert(cmd_key + cmd_val);

                cons.Close();
            }

            UpdateText();
            makeCSV(4);

            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc23 WHERE " + getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs, @"D:\scanLog\mc23\" + getLogFileName("mc23") + ".csv", true);
            }

            backgroundWorker5.RunWorkerAsync(tcpTargets[5]);
        }

        private void backgroundWorker6_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);

            //表示更新
            Rcvs[id - 1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                //insert
                string lineName = "mc24";
                string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1], lineName
                                                );

                cons.insert(cmd_key + cmd_val);

                cons.Close();
            }

            UpdateText();
            makeCSV(5);

            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_mc24 WHERE " + getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs, @"D:\scanLog\mc24\" + getLogFileName("mc24") + ".csv", true);
            }

            backgroundWorker6.RunWorkerAsync(tcpTargets[6]);
        }

        void AddTime(string mess)
        {


            listBox1.Items.Add(mess + " " + System.DateTime.Now.ToString("HH:mm:ss"));
        }

        private void backgroundWorker7_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            
            List<string> result = (e.Result as List<string>);
            int id = int.Parse(result[0]);
            listBox1.Items.Clear();
            AddTime("msStart:");
            //表示更新
            Rcvs[id - 1][0] = result[1];
            Rcvs[id - 1][1] = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var cons = new Connector();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                //insert
                string lineName = "office";
                string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                Rcvs[id - 1][1], result[1], lineName
                                                );

                cons.insert(cmd_key + cmd_val);

                cons.Close();
            }
            if (result[1].Length > 2)
            {
                AddTime("DBupEnd:");
                UpdateText();
                AddTime("UTEnd:");
                makeCSV(6);
                AddTime("mCEND:");
            }
            cons = new Connector();
            DataTable logs = new DataTable();
            //DBへpush
            if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
            {
                cons.TableReader("SELECT rcv_time,rcv_data, rcv_line FROM sch_office WHERE " + getRangeTxt(), logs);

                cons.Close();
            }
            if (logs.Rows.Count > 0)
            {
                ConvertDataTableToCsv(logs, @"D:\scanLog\office\" + getLogFileName("office") + ".csv", true);
            }

            backgroundWorker7.RunWorkerAsync(tcpTargets[7]);
            AddTime("msEND:");
        }

        /// <summary>
        /// 文字列の末尾から指定した長さの文字列を取得する
        /// </summary>
        /// <param name="str">文字列</param>
        /// <param name="len">長さ</param>
        /// <returns>取得した文字列</returns>
        public static string Right(string str, int len)
        {
            if (len < 0)
            {
                throw new ArgumentException("引数'len'は0以上でなければなりません。");
            }
            if (str == null)
            {
                return "";
            }
            if (str.Length <= len)
            {
                return str;
            }
            return str.Substring(str.Length - len, len);
        }

        /// <summary>
        /// 条件に当てはまるレコードをDataTableから削除します。
        /// </summary>
        /// <param name="dt">データテーブル</param>
        /// <param name="filter">条件</param>
        /// <returns>0:正常終了 -1:異常終了</returns>
        public static int RemoveSelectRows(DataTable dt, string filter)
        {
            try
            {
                DataRow[] rows = dt.Select(filter);

                for (int i = 0; i < rows.Length; i++)
                {
                    if (rows[i].RowState != DataRowState.Deleted)
                    {
                        rows[i].Delete();
                    }
                }
                dt.AcceptChanges();
                return 0;
            }
            catch (Exception)
            {
                dt.RejectChanges();
                return -1;
            }
        }
    


        private void makeCSV(int linNum)
        {
            //sc_rcvを取得
            //for loop
            //push == goなら
            //push をnoneに
            //rcv_dataでtb_pmからselect serial = rcv_data AND(ev=3 or ev =5)
            // 時刻でsort
            //DBへpush
            // for (int linNum = 0; linNum < 7; linNum++)
            // {
            var cons = new Connector();
            if (cons.Connect(Targets[0][0], Targets[0][1], Targets[0][2], Targets[0][3]))
                {
                DataTable firstData = new DataTable();
                    DataTable tempData = new DataTable();
                    DataTable scanSt = new DataTable();
                DataTable QcResult = new DataTable();
                    bool readOK = cons.TableReader("SELECT * FROM sc_rcv", scanSt);
                  //  textBox1.Text = scanSt.Rows[0]["rcv_data"].ToString();
                  //  textBox2.Text = scanSt.Rows[1]["rcv_data"].ToString();
                  //  textBox3.Text = scanSt.Rows[2]["rcv_data"].ToString();
                  //  textBox4.Text = scanSt.Rows[3]["rcv_data"].ToString();
                  //  textBox5.Text = scanSt.Rows[4]["rcv_data"].ToString();
                  //  textBox6.Text = scanSt.Rows[5]["rcv_data"].ToString();
                  //  textBox7.Text = scanSt.Rows[6]["rcv_data"].ToString();




                    if (scanSt.Rows[linNum]["push"].ToString() == "go")
                    {

                        string selectKey = scanSt.Rows[linNum]["rcv_data"].ToString();
                        
                        if(selectKey.Length > 19)
                        {
                        selectKey = Right(selectKey, 19);
                        }
                        else if(selectKey.Length < 16)
                        {
                            return;
                        }
                        string selectKey2 = selectKey;

                    if (linNum == 1)
                    {
                        try
                        {
                            selectKey2 = selectKey.Substring(2, 10);
                            //selectKey = selectKey2;
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    else
                    {
                        try
                        {
                            if (selectKey.Length > 15)
                            {
                                selectKey2 = selectKey.Substring(0, selectKey.Length - 7);
                                //selectKey = selectKey2;
                            }
                        }
                        catch (Exception ee)
                        {

                        }
                    }


                    List<List<string>> csvs = new List<List<string>>();
                    List<string> tmprw = new List<string>();
                    //tmprw.Add(selectKey2);
                    //for kn serial
                    string str0 = selectKey.Substring(0,6);
                    string str1 = selectKey.Substring(6, 6);
                    string str2 = selectKey.Substring(16, 3);//botom == model name

                    //for QC KN
                    string lineNumStr = str0.Substring(0, 2);
                    string ModelNumStr = str2;

                    tmprw.Add(str0 + " " + str1 + " " + str2);//for KN line
                    tmprw.Add("Search..");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");

                    csvs.Add(tmprw);

                    for (int i = 0; i < 30; i++)
                    {
                        tmprw = new List<string>();
                        tmprw.Add("-");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");

                        csvs.Add(tmprw);
                    }

                    //とりあえず一発
                    using (var writer = new CsvWriter(csvPath[linNum]))
                    {
                        writer.Write(csvs);
                    }

                    //QC KN
                    string qdbName;
                    if (lineNumStr == "25")
                    {
                        qdbName = "pq_25_30";
                    }
                    else if(lineNumStr =="26")
                    {
                        qdbName = "pq_26_30";
                    }
                    else
                    {
                        qdbName = "pq_27_30_1_view";
                    }


                    double hub_high = 0.001;
                    double hub_low = 0.000;
                    double osc_high = 0.001;
                    double osc_low = 0.000;
                    string nameA = "";
                    string nameB = "";

                    switch (ModelNumStr)
                    {
                        case "630"://LR
                        case "631":
                            hub_high = 0.058;
                            hub_low = 0.012;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.79.5";
                            nameB = "Oil Seal Dia.76";

                            break;

                        case "626"://LR
                        case "627":
                            hub_high = 0.096;
                            hub_low = 0.042;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.95";
                            nameB = "Oil Seal Dia.76";

                            break;
                    }


                    string tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);


                    bool readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    if(qdbName == "pq_27_30_1_view" && readOKQ && QcResult.Rows.Count <=0)
                    {
                        QcResult = new DataTable();
                        qdbName = "pq_27_30_2_view";

                        tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);
                        readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    }

                    string tempKeyL = string.Format("SELECT * FROM tb_pm_view WHERE pmSERIAL= \"{0}\" AND (pmEV = '3' OR pmEV = '8' OR pmEV = '10' OR pmEV = '11') ORDER BY pmDATE asc, pmTIME  asc", selectKey);


                        bool readOKL = cons.TableReader(tempKeyL, firstData);

                        //dataGridView1.DataSource = tempData;

                        string stResult = "NG";

                    try
                    {
                        if (firstData.Rows.Count == 0)
                        {
                            stResult = "NoData";
                        }

                        else//重複削除
                        {

                            firstData.Columns.Remove("id");
                            DataView dv = firstData.DefaultView;
                            tempData = dv.ToTable(true, "pmDATE", "pmTIME", "pmSERIAL", "pmLINE", "pmMC", "pmAUTO", "pmEV", "pmER", "pmTOOL");

                        }

                        DataTable checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        if (checks.Rows.Count >= 1)//OP30のPM情報があれば削除
                        {
                            /*for(int i=0; i< tempData.Rows.Count; i++)
                            {
                                if(tempData.Rows[i]["pmMC"].ToString() == "300" && tempData.Rows[i].RowState != DataRowState.Deleted)
                                {
                                    tempData.Rows[i].Delete();
                                }
                            }
                            tempData.AcceptChanges();
                            */
                            RemoveSelectRows(tempData, "pmMC = '300'");
                            tempData.AcceptChanges();
                        }



                        if (QcResult.Rows.Count > 0)
                        {//QC結果からOP30ログを挿入
                            for (int i = 0; i < QcResult.Rows.Count; i++)
                            {
                                DataRow adds = tempData.NewRow();
                                adds["pmDATE"] = QcResult.Rows[i]["pqDATE"];
                                adds["pmTIME"] = QcResult.Rows[i]["pqTIME"];
                                adds["pmMC"] = "300";
                                adds["pmLINE"] = lineNumStr;
                                adds["pmEV"] = "3";
                                tempData.Rows.Add(adds);
                            }
                        }
                        tempData = GetSortedDataTable(tempData, "", "pmDATE,pmTIME,pmMC");
                        checks = new DataTable();
                        checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        bool ml_op30 = false;
                        int cnt_op30 = 1;
                        if (checks.Rows.Count > 1)
                        {
                            ml_op30 = true;
                        }

                        int maxCnt = tempData.Rows.Count;
                        int lastCnt = 0;
                        if (maxCnt > 30)
                        {
                            maxCnt = 30;
                        }


                        for (int j = 0; j < maxCnt; j++)
                        {
                            csvs[j + 1][0] = "FN_" + checkMCName(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            csvs[j + 1][1] = checkCELL(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            if (tempData.Rows[j]["pmEV"].ToString() == "3")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "10")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "11")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else//5なら
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "AL";
                                //stResult = "Alarm";
                                csvs[j + 1][4] = checkEV(tempData.Rows[j]["pmER"].ToString(), Errs);
                            }
                            //op30 check
                            if (ml_op30 == true && tempData.Rows[j]["pmMC"].ToString() == "300")
                            {
                                DateTime dt = new DateTime(2019, 10, cnt_op30);
                                string suffix;
                                if (new[] { 11, 12, 13 }.Contains(dt.Day))
                                {
                                    suffix = "th";
                                }
                                else if (dt.Day % 10 == 1)
                                {
                                    suffix = "st";
                                }
                                else if (dt.Day % 10 == 2)
                                {
                                    suffix = "nd";
                                }
                                else if (dt.Day % 10 == 3)
                                {
                                    suffix = "rd";
                                }
                                else
                                {
                                    suffix = "th";
                                }



                                csvs[j + 1][3] = "AI";
                                csvs[j + 1][4] = cnt_op30.ToString() + suffix;

                                cnt_op30++;

                                if (cnt_op30 >= checks.Rows.Count)
                                {
                                    ml_op30 = false;
                                }

                            }//op30 check end

                            //全体判定
                            string mcNumber = tempData.Rows[j]["pmMC"].ToString();
                            if (mcNumber == "701")
                            {
                                if (csvs[j + 1][3] == "OK")
                                {
                                    stResult = "OK";
                                }
                            }

                            lastCnt = j + 1;

                        }



                        if (QcResult.Rows.Count > 0)
                        {
                            csvs[1][5] = nameA;
                            csvs[1][6] = (double.Parse(QcResult.Rows[0][6].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[1][7] = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[1][8] = (double.Parse(QcResult.Rows[0][8].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[1][9] = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            double hub_dx = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0);
                            double hub_dy = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0);
                            double osc_dx = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0);
                            double osc_dy = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0);

                            if (((hub_dx <= hub_high) && (hub_dx >= hub_low)) && ((hub_dy <= hub_high) && (hub_dy >= hub_low)))
                            {
                                csvs[1][10] = "OK";
                            }
                            else
                            {
                                csvs[1][10] = "NG";
                                //stResult = "NG";
                            }


                            csvs[2][5] = nameB;
                            csvs[2][6] = (double.Parse(QcResult.Rows[0][10].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[2][7] = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[2][8] = (double.Parse(QcResult.Rows[0][12].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[2][9] = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            if (((osc_dx <= osc_high) && (osc_dx >= osc_low)) && ((osc_dy <= osc_high) && (osc_dy >= osc_low)))
                            {
                                csvs[2][10] = "OK";
                            }
                            else
                            {
                                csvs[2][10] = "NG";
                                //stResult = "NG";
                            }

                            if (csvs[1][10] == "NG" || csvs[2][10] == "NG")
                            {
                                stResult = "NG";
                            }


                        }
                        else//該当無し
                        {


                        }


                        //PQ編
                        if (linNum == 1)
                        {
                            int cntstt = lastCnt + 1;

                            foreach (List<string> odt in Targets_PQ)
                            {
                                string selects = scanSt.Rows[linNum]["rcv_data"].ToString();

                                string temps = string.Format("SELECT * FROM `{0}` WHERE pqSERIAL= \"{1}\" " +
                                    "AND pmDATE BETWEEN date_format(current_date - INTERVAL 30 DAY,'%y%m%d') " +
                                    "AND date_format(current_date,'%y%m%d')", odt[1], selects);

                                string tests;

                                tests = selects;

                                tempData = new DataTable();
                                bool readOKq;

                                //try {
                                readOKq = cons.TableReader(temps, tempData);
                                //}

                                //                                catch(Exception ex)
                                //                              {
                                //                                MessageBox.Show(ex.ToString());
                                //                          }

                                //最大カウントチェック 後で足せ


                                for (int k = 0; k < tempData.Rows.Count; k++)
                                {
                                    csvs[cntstt + k][0] = "QC_" + odt[6];//MC Name
                                    csvs[cntstt + k][1] = odt[7];//cell name


                                    switch (odt[2])
                                    {
                                        case "0":
                                            csvs[cntstt + k][2] = tempData.Rows[k]["pqDATE"].ToString() + " " + int.Parse(tempData.Rows[k]["pqTIME"].ToString()).ToString("D6");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック
                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                        case "1":
                                            DateTime conv = DateTime.Parse(tempData.Rows[k]["clocktime"].ToString());
                                            csvs[cntstt + k][2] = conv.ToString("yyMMdd HHmmss");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック

                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                    }

                                    lastCnt = cntstt + k;
                                }//for end

                                cntstt = lastCnt + 1;

                            }//foreach end


                        }//linNum if end
                    }
                    catch(Exception ee)
                    {
                        stResult = "NoPMdata";
                        goto ENDs;
                    }

                    ENDs:
                    //if (linNum == 3)
                    //{

                    //    stResult = checkStatusReturn("C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv");
                   
                    //}
                    csvs[0][1] = stResult;

                        using (var writer = new CsvWriter(csvPath[linNum]))
                        {
                            writer.Write(csvs);
                        }
                        //forMC27
                        if(linNum == 3)
                        {

                        List<string> lines2 = new List<string>();
                        string[] lines = File.ReadAllLines("C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv");
                        for (int i = 0; i < lines.Length; i++)
                        {
                            string line = lines[i];
                            if (line.Contains(","))
                            {
                                if (i == 0)
                                {
                                    var split = line.Split(',');

                                    split[1] = checkStatusReturn("C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv");
                                    line = string.Join(",", split);

                                    lines2.Add(line);
                                }
                                else
                                {
                                    var split = line.Split(',');
                                    line = string.Join(",", split);

                                    lines2.Add(line);
                                }

                            }
                        }
                        File.WriteAllLines(@"C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv", lines2);

                        SendFileFtp("ftp://192.168.65.222/%2fFlashDisk/BT_FILES/drv1/DispData/info.csv",csvPath[linNum],"192.168.65.222");
                        }


                    }
                    cons.update("update sc_rcv set push = 'no' where id=" + (linNum + 1).ToString());
                    cons.Close();
                }// go if end
            //}//for end

        }


        private string CheckQCResult(DataRow rows, string keys)
        {
            string ans = "OK";
            try
            {
                foreach (DataColumn col in rows.Table.Columns)
                {
                    string colName = col.ColumnName;

                    if (colName.Contains(keys))
                    {
                        int res = int.Parse(rows[colName].ToString());

                        if (res != 1)
                        {
                            ans = "NG";
                        }

                    }
                }//foreach end
            }
            catch (Exception exx)
            {
                ans = "ERR";
            }



            return ans;

        }



        private string checkMCName(string Ln, string Mc, List<List<string>> tgt)
        {
            foreach (List<string> tmp in tgt)
            {
                if (tmp.Count >= 3)
                    if (tmp[0] == Ln && tmp[1] == Mc)
                    {
                        return tmp[2];
                    }
            }


            return Ln + Mc;
        }

        private string checkCELL(string Ln, string Mc, List<List<string>> tgt)
        {
            foreach (List<string> tmp in tgt)
            {
                if (tmp.Count >= 3)
                    if (tmp[0] == Ln && tmp[1] == Mc)
                    {
                        return tmp[3];
                    }
            }


            return Ln + Mc;
        }

        private string checkEV(string ev, List<List<string>> tgt)
        {
            foreach (List<string> tmp in tgt)
            {
                if (tmp.Count >= 2)
                    if (tmp[0] == ev)
                    {
                        return tmp[1];
                    }
            }

            return "Alarm:" + ev;
        }

        string getLogFileName(string lineName)
        {
            string tday;
            string kyou = DateTime.Now.ToString("yyMMdd");
            string yester = DateTime.Now.AddDays(-1).ToString("yyMMdd");
            string tomoro = DateTime.Now.AddDays(1).ToString("yyMMdd");
            DateTime cDt = DateTime.Parse(ChangeTime);

            DateTime am00 = DateTime.Parse("00:00");
            DateTime pm08 = DateTime.Parse("20:00");
            string nowTime = System.DateTime.Now.ToString("HH:mm");

            DateTime nows = DateTime.Parse(nowTime);

            if (nows >= am00 && nows < cDt)
            { //today cDt  - today nows
                tday = yester;
                return lineName+"_"+yester+"_NIGHT"; //shift03
            }
            else
            {
                //rangeTXT = "ProductionDate >= '" + todays + "' AND ProductionDate <= '" + nextdays + "'";
                //rangeTXT = "ProductionDate = '" + todays + "'";
                tday = kyou;

                if (nows >= pm08)
                {
                    return lineName + "_" + tday + "_NIGHT";
                }
                else
                {
                    return lineName + "_" + tday + "_DAY";
                }
              

            }
        }

        string getRangeTxt()
        {
            string tday;
            string kyou = DateTime.Now.ToString("yyyyMMdd");
            string yester = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            string tomoro = DateTime.Now.AddDays(1).ToString("yyyyMMdd");
            DateTime cDt = DateTime.Parse(ChangeTime);

            DateTime am00 = DateTime.Parse("00:00");
            DateTime pm08 = DateTime.Parse("20:00");
            string nowTime = System.DateTime.Now.ToString("HH:mm");
            string nowstr = DateTime.Now.ToString("yyyyMMddHHmmss");
            DateTime nows = DateTime.Parse(nowTime);

            if (nows >= am00 && nows < cDt)
            { //today cDt  - today nows
                tday = yester;
                return "rcv_time BETWEEN '" +yester + "200000' AND '" + kyou + "045959'";
            }
            else
            {
                //rangeTXT = "ProductionDate >= '" + todays + "' AND ProductionDate <= '" + nextdays + "'";
                //rangeTXT = "ProductionDate = '" + todays + "'";
                tday = kyou;

                if (nows >= pm08)
                {
                    return "rcv_time BETWEEN '" + kyou + "200000' AND '"+tomoro+"045959'";
                }
                else
                {
                    return "rcv_time BETWEEN '" + kyou + "080000' AND '" + kyou + "195959'";
                }


            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string serial = textBox15.Text;


            var cons = new Connector();
            if (cons.Connect(Targets[0][0], Targets[0][1], Targets[0][2], Targets[0][3]))
            {
                DataTable firstData = new DataTable();
                DataTable tempData = new DataTable();
                DataTable scanSt = new DataTable();

                string tempKeyL = string.Format("SELECT * FROM tb_pm_view WHERE pmSERIAL= \"{0}\" AND (pmEV = '3' OR pmEV = '8' OR pmEV = '10' OR pmEV = '11') ORDER BY pmDATE asc, pmTIME  asc", serial);


                bool readOKL = cons.TableReader(tempKeyL, firstData);

                //dataGridView1.DataSource = tempData;

                if (checkBox1.Checked == true)
                {

                    firstData.Columns.Remove("id");
                    DataView dv = firstData.DefaultView;
                    tempData = dv.ToTable(true, "pmDATE", "pmTIME", "pmSERIAL", "pmLINE", "pmMC", "pmAUTO", "pmEV", "pmER", "pmTOOL");
                    dataGridView1.DataSource = tempData;
                }
                else
                {
                    dataGridView1.DataSource = firstData;
                }

                cons.Close();

            }


        }

        private void button2_Click(object sender, EventArgs e)
        {
            UpdateText();
            makeCSV(0);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            //makeCSV(2);
        }


        #endregion
                       

        #region "27 okaya"

        private string _pathPending = "\\\\192.168.65.249\\iemt\\Pending";
        private string _pathSave = "\\\\192.168.65.249\\iemt\\Judement";
        private string _filenameOkaya = string.Empty;

        List<List<string>> scanResult = new List<List<string>>();
        private void backgroundWorker__okaya_DoWork(object sender, DoWorkEventArgs e)
        {
      
            List<string> targ = (e.Argument as List<string>);
            bool RcvFinish = false;
            int size = 0;
            string receiveString = "";
            int id = int.Parse(targ[0]);
            string lastReads = Rcvs[id - 1][1];
            List<string> ans = new List<string>();
            ans.Add(targ[0]);
            ans.Add("none");
            ans.Add(lastReads);

            DirectoryInfo di = new DirectoryInfo(_pathPending);
            FileInfo[] files = di.GetFiles("*.csv");
     
            List<string> tmp = new List<string>();
            //MessageBox.Show(files.Length.ToString());
            //System.Threading.Thread.Sleep(2000);

            scanResult.Clear();
            if (files.Length > 0)
            {
             
                using (var csv = new CsvReader(files[0].FullName))
                {

                    while ((tmp = csv.ReadRow()) != null)
                    {
                     
                        scanResult.Add(tmp);
                    }
                }//using end


                _filenameOkaya = files[0].Name;
           
                //File.Delete(files[0].FullName);
                //File.Copy(files[0].FullName, _pathSave + files[0].Name, true);
            }
            if (scanResult.Count > 0)
            {
               
                ans[1] = scanResult[0][0];
                ans[2] = scanResult[0][1];

            }
            else
            {
                ans[1] = "skip";
            }
            e.Result = ans;

 
        }

        private void backgroundWorker__okaya_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {

                List<string> result = (e.Result as List<string>);
                int id = int.Parse(result[0]);

                if (result[1] != "skip")
                {
                    Rcvs[id - 1][0] = result[1];
                    Rcvs[id - 1][1] = result[2];//System.DateTime.Now.ToString("yyyyMMddHHmmss");
                    var cons = new Connector();
                    //DBへpush
                    if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
                    {


                        cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);

                        cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                        cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                        //insert
                        string lineName = "mc23";
                        string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                        string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                        Rcvs[id - 1][1], result[1], lineName
                                                        );

                        cons.insert(cmd_key + cmd_val);

                        cons.Close();


                    }


                    makeCSV_Info_Okaya(6);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


}

        private void makeCSV_Info_Okaya(int linNum)
        {
            //sc_rcvを取得
            //for loop
            //push == goなら
            //push をnoneに
            //rcv_dataでtb_pmからselect serial = rcv_data AND(ev=3 or ev =5)
            // 時刻でsort
            //DBへpush
            // for (int linNum = 0; linNum < 7; linNum++)
            // {
            var cons = new Connector();
            if (cons.Connect(Targets[0][0], Targets[0][1], Targets[0][2], Targets[0][3]))
            {

                DataTable firstData = new DataTable();
                DataTable tempData = new DataTable();
                DataTable scanSt = new DataTable();
                DataTable QcResult = new DataTable();


                bool readOK = cons.TableReader("SELECT * FROM sc_rcv", scanSt);
         
                //  textBox1.Text = scanSt.Rows[0]["rcv_data"].ToString();
                //  textBox2.Text = scanSt.Rows[1]["rcv_data"].ToString();
                //  textBox3.Text = scanSt.Rows[2]["rcv_data"].ToString();
                //  textBox4.Text = scanSt.Rows[3]["rcv_data"].ToString();
                //  textBox5.Text = scanSt.Rows[4]["rcv_data"].ToString();
                //  textBox6.Text = scanSt.Rows[5]["rcv_data"].ToString();
                //  textBox7.Text = scanSt.Rows[6]["rcv_data"].ToString();




                if (scanSt.Rows[linNum]["push"].ToString() == "go")
                {

                    string selectKey = scanSt.Rows[linNum]["rcv_data"].ToString();

                    if (selectKey.Length > 19)
                    {
                        selectKey = Right(selectKey, 19);
                    }
                    else if (selectKey.Length < 16)
                    {
                        return;
                    }
                    string selectKey2 = selectKey;

                    if (linNum == 1)
                    {
                        try
                        {
                            selectKey2 = selectKey.Substring(2, 10);
                            //selectKey = selectKey2;
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    else
                    {
                        try
                        {
                            if (selectKey.Length > 15)
                            {
                                selectKey2 = selectKey.Substring(0, selectKey.Length - 7);
                                //selectKey = selectKey2;
                            }
                        }
                        catch (Exception ee)
                        {

                        }
                    }



                    List<List<string>> csvs = new List<List<string>>();
                    List<string> tmprw = new List<string>();
                    //tmprw.Add(selectKey2);
                    //for kn serial
                    string str0 = selectKey.Substring(0, 6);
                    string str1 = selectKey.Substring(6, 6);
                    string str2 = selectKey.Substring(16, 3);//botom == model name

                    //for QC KN
                    string lineNumStr = str0.Substring(0, 2);
                    string ModelNumStr = str2;

                    tmprw.Add(str0 + " " + str1 + " " + str2);//for KN line
                    tmprw.Add("Search..");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");

                    csvs.Add(tmprw);

                    for (int i = 0; i < 30; i++)
                    {
                        tmprw = new List<string>();
                        tmprw.Add("-");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");

                        csvs.Add(tmprw);
                    }

                    //とりあえず一発
                    using (var writer = new CsvWriter(csvPath[linNum]))
                    {
                        writer.Write(csvs);
                    }

                    //QC KN
                    string qdbName;
                    if (lineNumStr == "25")
                    {
                        qdbName = "pq_25_30";
                    }
                    else if (lineNumStr == "26")
                    {
                        qdbName = "pq_26_30";
                    }
                    else
                    {
                        qdbName = "pq_27_30_1_view";
                    }


                    double hub_high = 0.001;
                    double hub_low = 0.000;
                    double osc_high = 0.001;
                    double osc_low = 0.000;
                    string nameA = "";
                    string nameB = "";

                    switch (ModelNumStr)
                    {
                        case "630"://LR
                        case "631":
                            hub_high = 0.058;
                            hub_low = 0.012;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.79.5";
                            nameB = "Oil Seal Dia.76";

                            break;

                        case "626"://LR
                        case "627":
                            hub_high = 0.096;
                            hub_low = 0.042;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.95";
                            nameB = "Oil Seal Dia.76";

                            break;
                    }


                    string tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);


                    bool readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    if (qdbName == "pq_27_30_1_view" && readOKQ && QcResult.Rows.Count <= 0)
                    {
                        QcResult = new DataTable();
                        qdbName = "pq_27_30_2_view";

                        tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);
                        readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    }

                    string tempKeyL = string.Format("SELECT * FROM tb_pm_view WHERE pmSERIAL= \"{0}\" AND (pmEV = '3' OR pmEV = '8' OR pmEV = '10' OR pmEV = '11') ORDER BY pmDATE asc, pmTIME  asc", selectKey);


                    bool readOKL = cons.TableReader(tempKeyL, firstData);

                    //dataGridView1.DataSource = tempData;

                    string stResult = "NG";

                    try
                    {
                        if (firstData.Rows.Count == 0)
                        {
                            stResult = "NoData";
                        }

                        else//重複削除
                        {

                            firstData.Columns.Remove("id");
                            DataView dv = firstData.DefaultView;
                            tempData = dv.ToTable(true, "pmDATE", "pmTIME", "pmSERIAL", "pmLINE", "pmMC", "pmAUTO", "pmEV", "pmER", "pmTOOL");

                        }

                        DataTable checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        if (checks.Rows.Count >= 1)//OP30のPM情報があれば削除
                        {
                            /*for(int i=0; i< tempData.Rows.Count; i++)
                            {
                                if(tempData.Rows[i]["pmMC"].ToString() == "300" && tempData.Rows[i].RowState != DataRowState.Deleted)
                                {
                                    tempData.Rows[i].Delete();
                                }
                            }
                            tempData.AcceptChanges();
                            */
                            RemoveSelectRows(tempData, "pmMC = '300'");
                            tempData.AcceptChanges();
                        }



                        if (QcResult.Rows.Count > 0)
                        {//QC結果からOP30ログを挿入
                            for (int i = 0; i < QcResult.Rows.Count; i++)
                            {
                                DataRow adds = tempData.NewRow();
                                adds["pmDATE"] = QcResult.Rows[i]["pqDATE"];
                                adds["pmTIME"] = QcResult.Rows[i]["pqTIME"];
                                adds["pmMC"] = "300";
                                adds["pmLINE"] = lineNumStr;
                                adds["pmEV"] = "3";
                                tempData.Rows.Add(adds);
                            }
                        }
                        tempData = GetSortedDataTable(tempData, "", "pmDATE,pmTIME,pmMC");
                        checks = new DataTable();
                        checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        bool ml_op30 = false;
                        int cnt_op30 = 1;
                        if (checks.Rows.Count > 1)
                        {
                            ml_op30 = true;
                        }

                        int maxCnt = tempData.Rows.Count;
                        int lastCnt = 0;
                        if (maxCnt > 30)
                        {
                            maxCnt = 30;
                        }



                        for (int j = 0; j < maxCnt; j++)
                        {

                            csvs[j + 1][0] = "FN_" + checkMCName(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            csvs[j + 1][1] = checkCELL(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            if (tempData.Rows[j]["pmEV"].ToString() == "3")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "10")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "11")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else//5なら
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "AL";
                                //stResult = "Alarm";
                                csvs[j + 1][4] = checkEV(tempData.Rows[j]["pmER"].ToString(), Errs);
                            }
                            //op30 check
                            if (ml_op30 == true && tempData.Rows[j]["pmMC"].ToString() == "300")
                            {
                                DateTime dt = new DateTime(2019, 10, cnt_op30);
                                string suffix;
                                if (new[] { 11, 12, 13 }.Contains(dt.Day))
                                {
                                    suffix = "th";
                                }
                                else if (dt.Day % 10 == 1)
                                {
                                    suffix = "st";
                                }
                                else if (dt.Day % 10 == 2)
                                {
                                    suffix = "nd";
                                }
                                else if (dt.Day % 10 == 3)
                                {
                                    suffix = "rd";
                                }
                                else
                                {
                                    suffix = "th";
                                }



                                csvs[j + 1][3] = "AI";
                                csvs[j + 1][4] = cnt_op30.ToString() + suffix;

                                cnt_op30++;

                                if (cnt_op30 >= checks.Rows.Count)
                                {
                                    ml_op30 = false;
                                }

                            }//op30 check end

                            //全体判定
                            string mcNumber = tempData.Rows[j]["pmMC"].ToString();
                            if (mcNumber == "701")
                            {
                                if (csvs[j + 1][3] == "OK")
                                {
                                    stResult = "OK";
                                }
                            }

                            lastCnt = j + 1;

                        }



                        if (QcResult.Rows.Count > 0)
                        {
                            csvs[1][5] = nameA;
                            csvs[1][6] = (double.Parse(QcResult.Rows[0][6].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[1][7] = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[1][8] = (double.Parse(QcResult.Rows[0][8].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[1][9] = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            double hub_dx = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0);
                            double hub_dy = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0);
                            double osc_dx = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0);
                            double osc_dy = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0);

                            if (((hub_dx <= hub_high) && (hub_dx >= hub_low)) && ((hub_dy <= hub_high) && (hub_dy >= hub_low)))
                            {
                                csvs[1][10] = "OK";
                            }
                            else
                            {
                                csvs[1][10] = "NG";
                                //stResult = "NG";
                            }


                            csvs[2][5] = nameB;
                            csvs[2][6] = (double.Parse(QcResult.Rows[0][10].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[2][7] = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[2][8] = (double.Parse(QcResult.Rows[0][12].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[2][9] = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            if (((osc_dx <= osc_high) && (osc_dx >= osc_low)) && ((osc_dy <= osc_high) && (osc_dy >= osc_low)))
                            {
                                csvs[2][10] = "OK";
                            }
                            else
                            {
                                csvs[2][10] = "NG";
                                //stResult = "NG";
                            }

                            if (csvs[1][10] == "NG" || csvs[2][10] == "NG")
                            {
                                stResult = "NG";
                            }


                        }
                        else//該当無し
                        {


                        }


                        //PQ編
                        if (linNum == 1)
                        {
                            int cntstt = lastCnt + 1;

                            foreach (List<string> odt in Targets_PQ)
                            {
                                string selects = scanSt.Rows[linNum]["rcv_data"].ToString();

                                string temps = string.Format("SELECT * FROM `{0}` WHERE pqSERIAL= \"{1}\" " +
                                    "AND pmDATE BETWEEN date_format(current_date - INTERVAL 30 DAY,'%y%m%d') " +
                                    "AND date_format(current_date,'%y%m%d')", odt[1], selects);

                                string tests;

                                tests = selects;

                                tempData = new DataTable();
                                bool readOKq;

                                //try {
                                readOKq = cons.TableReader(temps, tempData);
                                //}

                                //                                catch(Exception ex)
                                //                              {
                                //                                MessageBox.Show(ex.ToString());
                                //                          }

                                //最大カウントチェック 後で足せ


                                for (int k = 0; k < tempData.Rows.Count; k++)
                                {
                                    csvs[cntstt + k][0] = "QC_" + odt[6];//MC Name
                                    csvs[cntstt + k][1] = odt[7];//cell name


                                    switch (odt[2])
                                    {
                                        case "0":
                                            csvs[cntstt + k][2] = tempData.Rows[k]["pqDATE"].ToString() + " " + int.Parse(tempData.Rows[k]["pqTIME"].ToString()).ToString("D6");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック
                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                        case "1":
                                            DateTime conv = DateTime.Parse(tempData.Rows[k]["clocktime"].ToString());
                                            csvs[cntstt + k][2] = conv.ToString("yyMMdd HHmmss");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック

                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                    }

                                    lastCnt = cntstt + k;
                                }//for end

                                cntstt = lastCnt + 1;

                            }//foreach end


                        }//linNum if end
                    }
                    catch (Exception ee)
                    {
                        stResult = "NoPMdata";
                        goto ENDs;
                    }

                    ENDs:

              
                    csvs[0][1] = stResult;


                    using (var writer = new CsvWriter("C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv"))
                    {
                        writer.Write(csvs);
                    }


                    string _Result = checkStatusReturn("C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv");
                    List<string> lines2 = new List<string>();
                    string[] lines = File.ReadAllLines("C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv");
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string line = lines[i];
                        if (line.Contains(","))
                        {
                            if (i == 0)
                            {
                                var split = line.Split(',');

                                split[1] = _Result;
                                line = string.Join(",", split);

                                lines2.Add(line);
                            }
                            else
                            {
                                var split = line.Split(',');
                                line = string.Join(",", split);

                                lines2.Add(line);
                            }

                        }
                    }
                    File.WriteAllLines(@"C:\\xampp\\htdocs\\isz\\mc23-1\\info.csv", lines2);




                    //if (_status)
                    //  {


                    var csv = new StringBuilder();


                        foreach (List<string> a in scanResult)
                        {
                            foreach (string b in a)
                            {
                                var newLine = string.Format("{0},{1},{2}", a[0], a[1], _Result.Replace("\r\n", ""));
                                csv.AppendLine(newLine);
                                //after your loop
                               
                                if (!Directory.Exists(_pathSave))
                                {
                                    Directory.CreateDirectory(_pathSave);
                                }

                                File.WriteAllText(_pathSave + "\\" + _filenameOkaya, csv.ToString());
                             
                                string[] files = Directory.GetFiles(_pathPending);
                                //System.Threading.Thread.Sleep(2000);
                                foreach (string file in files)
                                {
                                    File.Delete(file);

                                }
                              
                                return;
                            }
                        }



                    //}

                    //else
                    //{

                    //    var csv = new StringBuilder();


                    //    foreach (List<string> a in scanResult)
                    //    {
                    //        foreach (string b in a)
                    //        {
                    //            var newLine = string.Format("{0},{1},{2}", a[0], a[1], "NG");
                    //            csv.AppendLine(newLine);

                    //            File.WriteAllText(_pathSave + "\\" + _filenameOkaya, csv.ToString());

                    //            string[] files = Directory.GetFiles(_pathPending);
                    //            foreach (string file in files)
                    //            {
                    //                File.Delete(file);

                    //            }
                    //            return;
                    //        }
                    //    }


                    //    after your loop


                    //}

                    //

                }
                cons.update("update sc_rcv set push = 'no' where id=" + (linNum + 1).ToString());
                cons.Close();
            }// go if end
             //}//for end

        }

        public string checkStatusReturn(string filePath)
        {
            string _isvalid = string.Empty;
            //reading all the lines(rows) from the file.
            string[] rows = File.ReadAllLines(filePath);

            DataTable dtData = new DataTable();
            string[] rowValues = null;
            DataRow dr = dtData.NewRow();

            //Creating columns
            Int32 _i = 0;
            if (rows.Length > 0)
            {
                for (int row = 0; row < rows.Length; row++)
                {
                    rowValues = rows[row].Split(',');
                    if (rowValues[0].Contains("OP20"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP30"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP40"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP50"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP60"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP70"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP80"))
                    { _i = _i + 1; }
                    if (rowValues[0].Contains("OP90"))
                    { _i = _i + 1; }
         
                }
                //foreach (string columnName in rows[0].Split(','))
                //{ 
                //    dtData.Columns.Add(_i.ToString()); _i = _i + 1; 
                //}
            }
            if (_i > 7)
            { _isvalid = "OK"; }
            else
            { _isvalid = "NG"; }
            ////Creating row for each line.(except the first line, which contain column names)
            //for (int row = 0; row < rows.Length; row++)
            //{
            //    rowValues = rows[row].Split(',');
            //    dr = dtData.NewRow();
            //    if (rowValues[0].ToString().Trim() != "FN_OP10")
            //    {
            //        dr.ItemArray = rowValues;
            //    }


            //    dtData.Rows.Add(dr);
            //}



            return _isvalid;
        }
        #endregion

        #region "25 okaya"

        private string _pathPending25 = "\\\\192.168.65.247\\iemt\\Pending";
        private string _pathSave25 = "\\\\192.168.65.247\\iemt\\Judement";
        private string _filenameOkaya25 = string.Empty;

        List<List<string>> scanResult25 = new List<List<string>>();
        private void backgroundWorker_okaya_M25_DoWork(object sender, DoWorkEventArgs e)
        {

            List<string> targ = (e.Argument as List<string>);
            bool RcvFinish = false;
            int size = 0;
            string receiveString = "";
            int id = int.Parse(targ[0]);
            string lastReads = Rcvs[id - 1][1];
            List<string> ans = new List<string>();
            ans.Add(targ[0]);
            ans.Add("none");
            ans.Add(lastReads);

            DirectoryInfo di = new DirectoryInfo(_pathPending25);
            FileInfo[] files = di.GetFiles("*.csv");

            List<string> tmp = new List<string>();
            //MessageBox.Show(files.Length.ToString());
            //System.Threading.Thread.Sleep(2000);

            scanResult25.Clear();
            if (files.Length > 0)
            {

                using (var csv = new CsvReader(files[0].FullName))
                {

                    while ((tmp = csv.ReadRow()) != null)
                    {

                        scanResult25.Add(tmp);
                    }
                }//using end


                _filenameOkaya25 = files[0].Name;

                //File.Delete(files[0].FullName);
                //File.Copy(files[0].FullName, _pathSave + files[0].Name, true);
            }
            if (scanResult25.Count > 0)
            {

                ans[1] = scanResult25[0][0];
                ans[2] = scanResult25[0][1];

            }
            else
            {
                ans[1] = "skip";
            }
            e.Result = ans;


        }

        private void backgroundWorker_okaya_M25_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {

                List<string> result = (e.Result as List<string>);
                int id = int.Parse(result[0]);

                if (result[1] != "skip")
                {
                    Rcvs[id - 1][0] = result[1];
                    Rcvs[id - 1][1] = result[2];//System.DateTime.Now.ToString("yyyyMMddHHmmss");
                    var cons = new Connector();
                    //DBへpush
                    if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
                    {


                        cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);

                        cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                        cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                        //insert
                        string lineName = "mc20";
                        string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                        string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                        Rcvs[id - 1][1], result[1], lineName
                                                        );

                        cons.insert(cmd_key + cmd_val);

                        cons.Close();


                    }


                    makeCSV_Info_Okaya25(0);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void makeCSV_Info_Okaya25(int linNum)
        {
            //sc_rcvを取得
            //for loop
            //push == goなら
            //push をnoneに
            //rcv_dataでtb_pmからselect serial = rcv_data AND(ev=3 or ev =5)
            // 時刻でsort
            //DBへpush
            // for (int linNum = 0; linNum < 7; linNum++)
            // {
            var cons = new Connector();
            if (cons.Connect(Targets[0][0], Targets[0][1], Targets[0][2], Targets[0][3]))
            {

                DataTable firstData = new DataTable();
                DataTable tempData = new DataTable();
                DataTable scanSt = new DataTable();
                DataTable QcResult = new DataTable();


                bool readOK = cons.TableReader("SELECT * FROM sc_rcv", scanSt);

                //  textBox1.Text = scanSt.Rows[0]["rcv_data"].ToString();
                //  textBox2.Text = scanSt.Rows[1]["rcv_data"].ToString();
                //  textBox3.Text = scanSt.Rows[2]["rcv_data"].ToString();
                //  textBox4.Text = scanSt.Rows[3]["rcv_data"].ToString();
                //  textBox5.Text = scanSt.Rows[4]["rcv_data"].ToString();
                //  textBox6.Text = scanSt.Rows[5]["rcv_data"].ToString();
                //  textBox7.Text = scanSt.Rows[6]["rcv_data"].ToString();




                if (scanSt.Rows[linNum]["push"].ToString() == "go")
                {

                    string selectKey = scanSt.Rows[linNum]["rcv_data"].ToString();

                    if (selectKey.Length > 19)
                    {
                        selectKey = Right(selectKey, 19);
                    }
                    else if (selectKey.Length < 16)
                    {
                        return;
                    }
                    string selectKey2 = selectKey;

                    if (linNum == 1)
                    {
                        try
                        {
                            selectKey2 = selectKey.Substring(2, 10);
                            //selectKey = selectKey2;
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    else
                    {
                        try
                        {
                            if (selectKey.Length > 15)
                            {
                                selectKey2 = selectKey.Substring(0, selectKey.Length - 7);
                                //selectKey = selectKey2;
                            }
                        }
                        catch (Exception ee)
                        {

                        }
                    }



                    List<List<string>> csvs = new List<List<string>>();
                    List<string> tmprw = new List<string>();
                    //tmprw.Add(selectKey2);
                    //for kn serial
                    string str0 = selectKey.Substring(0, 6);
                    string str1 = selectKey.Substring(6, 6);
                    string str2 = selectKey.Substring(16, 3);//botom == model name

                    //for QC KN
                    string lineNumStr = str0.Substring(0, 2);
                    string ModelNumStr = str2;

                    tmprw.Add(str0 + " " + str1 + " " + str2);//for KN line
                    tmprw.Add("Search..");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");

                    csvs.Add(tmprw);

                    for (int i = 0; i < 30; i++)
                    {
                        tmprw = new List<string>();
                        tmprw.Add("-");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");

                        csvs.Add(tmprw);
                    }

                    //とりあえず一発
                    using (var writer = new CsvWriter(csvPath[linNum]))
                    {
                        writer.Write(csvs);
                    }

                    //QC KN
                    string qdbName;
                    if (lineNumStr == "25")
                    {
                        qdbName = "pq_25_30";
                    }
                    else if (lineNumStr == "26")
                    {
                        qdbName = "pq_26_30";
                    }
                    else
                    {
                        qdbName = "pq_27_30_1_view";
                    }

                    qdbName = "pq_25_30_view";

                    double hub_high = 0.001;
                    double hub_low = 0.000;
                    double osc_high = 0.001;
                    double osc_low = 0.000;
                    string nameA = "";
                    string nameB = "";

                    switch (ModelNumStr)
                    {
                        case "630"://LR
                        case "631":
                            hub_high = 0.058;
                            hub_low = 0.012;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.79.5";
                            nameB = "Oil Seal Dia.76";

                            break;

                        case "626"://LR
                        case "627":
                            hub_high = 0.096;
                            hub_low = 0.042;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.95";
                            nameB = "Oil Seal Dia.76";

                            break;
                    }


                    string tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);


                    bool readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    if (qdbName == "pq_25_30_view" && readOKQ && QcResult.Rows.Count <= 0)
                    {
                        QcResult = new DataTable();
                        qdbName = "pq_25_30_view";

                        tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);
                        readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    }

                    string tempKeyL = string.Format("SELECT * FROM tb_pm_view WHERE pmSERIAL= \"{0}\" AND (pmEV = '3' OR pmEV = '8' OR pmEV = '10' OR pmEV = '11') ORDER BY pmDATE asc, pmTIME  asc", selectKey);


                    bool readOKL = cons.TableReader(tempKeyL, firstData);

                    //dataGridView1.DataSource = tempData;

                    string stResult = "NG";

                    try
                    {
                        if (firstData.Rows.Count == 0)
                        {
                            stResult = "NoData";
                        }

                        else//重複削除
                        {

                            firstData.Columns.Remove("id");
                            DataView dv = firstData.DefaultView;
                            tempData = dv.ToTable(true, "pmDATE", "pmTIME", "pmSERIAL", "pmLINE", "pmMC", "pmAUTO", "pmEV", "pmER", "pmTOOL");

                        }

                        DataTable checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        if (checks.Rows.Count >= 1)//OP30のPM情報があれば削除
                        {
                            /*for(int i=0; i< tempData.Rows.Count; i++)
                            {
                                if(tempData.Rows[i]["pmMC"].ToString() == "300" && tempData.Rows[i].RowState != DataRowState.Deleted)
                                {
                                    tempData.Rows[i].Delete();
                                }
                            }
                            tempData.AcceptChanges();
                            */
                            RemoveSelectRows(tempData, "pmMC = '300'");
                            tempData.AcceptChanges();
                        }



                        if (QcResult.Rows.Count > 0)
                        {//QC結果からOP30ログを挿入
                            for (int i = 0; i < QcResult.Rows.Count; i++)
                            {
                                DataRow adds = tempData.NewRow();
                                adds["pmDATE"] = QcResult.Rows[i]["pqDATE"];
                                adds["pmTIME"] = QcResult.Rows[i]["pqTIME"];
                                adds["pmMC"] = "300";
                                adds["pmLINE"] = lineNumStr;
                                adds["pmEV"] = "3";
                                tempData.Rows.Add(adds);
                            }
                        }
                        tempData = GetSortedDataTable(tempData, "", "pmDATE,pmTIME,pmMC");
                        checks = new DataTable();
                        checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        bool ml_op30 = false;
                        int cnt_op30 = 1;
                        if (checks.Rows.Count > 1)
                        {
                            ml_op30 = true;
                        }

                        int maxCnt = tempData.Rows.Count;
                        int lastCnt = 0;
                        if (maxCnt > 30)
                        {
                            maxCnt = 30;
                        }



                        for (int j = 0; j < maxCnt; j++)
                        {

                            csvs[j + 1][0] = "FN_" + checkMCName(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            csvs[j + 1][1] = checkCELL(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            if (tempData.Rows[j]["pmEV"].ToString() == "3")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "10")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "11")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else//5なら
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "AL";
                                //stResult = "Alarm";
                                csvs[j + 1][4] = checkEV(tempData.Rows[j]["pmER"].ToString(), Errs);
                            }
                            //op30 check
                            if (ml_op30 == true && tempData.Rows[j]["pmMC"].ToString() == "300")
                            {
                                DateTime dt = new DateTime(2019, 10, cnt_op30);
                                string suffix;
                                if (new[] { 11, 12, 13 }.Contains(dt.Day))
                                {
                                    suffix = "th";
                                }
                                else if (dt.Day % 10 == 1)
                                {
                                    suffix = "st";
                                }
                                else if (dt.Day % 10 == 2)
                                {
                                    suffix = "nd";
                                }
                                else if (dt.Day % 10 == 3)
                                {
                                    suffix = "rd";
                                }
                                else
                                {
                                    suffix = "th";
                                }



                                csvs[j + 1][3] = "AI";
                                csvs[j + 1][4] = cnt_op30.ToString() + suffix;

                                cnt_op30++;

                                if (cnt_op30 >= checks.Rows.Count)
                                {
                                    ml_op30 = false;
                                }

                            }//op30 check end

                            //全体判定
                            string mcNumber = tempData.Rows[j]["pmMC"].ToString();
                            if (mcNumber == "701")
                            {
                                if (csvs[j + 1][3] == "OK")
                                {
                                    stResult = "OK";
                                }
                            }

                            lastCnt = j + 1;

                        }



                        if (QcResult.Rows.Count > 0)
                        {
                            csvs[1][5] = nameA;
                            csvs[1][6] = (double.Parse(QcResult.Rows[0][6].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[1][7] = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[1][8] = (double.Parse(QcResult.Rows[0][8].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[1][9] = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            double hub_dx = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0);
                            double hub_dy = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0);
                            double osc_dx = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0);
                            double osc_dy = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0);

                            if (((hub_dx <= hub_high) && (hub_dx >= hub_low)) && ((hub_dy <= hub_high) && (hub_dy >= hub_low)))
                            {
                                csvs[1][10] = "OK";
                            }
                            else
                            {
                                csvs[1][10] = "NG";
                                //stResult = "NG";
                            }


                            csvs[2][5] = nameB;
                            csvs[2][6] = (double.Parse(QcResult.Rows[0][10].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[2][7] = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[2][8] = (double.Parse(QcResult.Rows[0][12].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[2][9] = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            if (((osc_dx <= osc_high) && (osc_dx >= osc_low)) && ((osc_dy <= osc_high) && (osc_dy >= osc_low)))
                            {
                                csvs[2][10] = "OK";
                            }
                            else
                            {
                                csvs[2][10] = "NG";
                                //stResult = "NG";
                            }

                            if (csvs[1][10] == "NG" || csvs[2][10] == "NG")
                            {
                                stResult = "NG";
                            }


                        }
                        else//該当無し
                        {


                        }


                        //PQ編
                        if (linNum == 1)
                        {
                            int cntstt = lastCnt + 1;

                            foreach (List<string> odt in Targets_PQ)
                            {
                                string selects = scanSt.Rows[linNum]["rcv_data"].ToString();

                                string temps = string.Format("SELECT * FROM `{0}` WHERE pqSERIAL= \"{1}\" " +
                                    "AND pmDATE BETWEEN date_format(current_date - INTERVAL 30 DAY,'%y%m%d') " +
                                    "AND date_format(current_date,'%y%m%d')", odt[1], selects);

                                string tests;

                                tests = selects;

                                tempData = new DataTable();
                                bool readOKq;

                                //try {
                                readOKq = cons.TableReader(temps, tempData);
                                //}

                                //                                catch(Exception ex)
                                //                              {
                                //                                MessageBox.Show(ex.ToString());
                                //                          }

                                //最大カウントチェック 後で足せ


                                for (int k = 0; k < tempData.Rows.Count; k++)
                                {
                                    csvs[cntstt + k][0] = "QC_" + odt[6];//MC Name
                                    csvs[cntstt + k][1] = odt[7];//cell name


                                    switch (odt[2])
                                    {
                                        case "0":
                                            csvs[cntstt + k][2] = tempData.Rows[k]["pqDATE"].ToString() + " " + int.Parse(tempData.Rows[k]["pqTIME"].ToString()).ToString("D6");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック
                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                        case "1":
                                            DateTime conv = DateTime.Parse(tempData.Rows[k]["clocktime"].ToString());
                                            csvs[cntstt + k][2] = conv.ToString("yyMMdd HHmmss");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック

                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                    }

                                    lastCnt = cntstt + k;
                                }//for end

                                cntstt = lastCnt + 1;

                            }//foreach end


                        }//linNum if end
                    }
                    catch (Exception ee)
                    {
                        stResult = "NoPMdata";
                        goto ENDs;
                    }

                ENDs:


                    csvs[0][1] = stResult;


                    using (var writer = new CsvWriter("C:\\xampp\\htdocs\\isz\\mc20\\info.csv"))
                    {
                        writer.Write(csvs);
                    }


                    string _Result = checkStatusReturn25("C:\\xampp\\htdocs\\isz\\mc20\\info.csv");
                    List<string> lines2 = new List<string>();
                    string[] lines = File.ReadAllLines("C:\\xampp\\htdocs\\isz\\mc20\\info.csv");
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string line = lines[i];
                        if (line.Contains(","))
                        {
                            if (i == 0)
                            {
                                var split = line.Split(',');

                                split[1] = _Result;
                                line = string.Join(",", split);

                                lines2.Add(line);
                            }
                            else
                            {
                                var split = line.Split(',');
                                line = string.Join(",", split);

                                lines2.Add(line);
                            }

                        }
                    }
                    File.WriteAllLines(@"C:\\xampp\\htdocs\\isz\\mc20\\info.csv", lines2);




                    //if (_status)
                    //  {


                    var csv = new StringBuilder();


                    foreach (List<string> a in scanResult25)
                    {
                        foreach (string b in a)
                        {
                            var newLine = string.Format("{0},{1},{2}", a[0], a[1], _Result.Replace("\r\n",""));
                            csv.AppendLine(newLine);
                            //after your loop

                            if (!Directory.Exists(_pathSave25))
                            {
                                Directory.CreateDirectory(_pathSave25);
                            }

                            File.WriteAllText(_pathSave25 + "\\" + _filenameOkaya25, csv.ToString());

                            string[] files = Directory.GetFiles(_pathPending25);
                            //System.Threading.Thread.Sleep(2000);
                            foreach (string file in files)
                            {
                                File.Delete(file);

                            }

                            return;
                        }
                    }



                    //}

                    //else
                    //{

                    //    var csv = new StringBuilder();


                    //    foreach (List<string> a in scanResult)
                    //    {
                    //        foreach (string b in a)
                    //        {
                    //            var newLine = string.Format("{0},{1},{2}", a[0], a[1], "NG");
                    //            csv.AppendLine(newLine);

                    //            File.WriteAllText(_pathSave + "\\" + _filenameOkaya, csv.ToString());

                    //            string[] files = Directory.GetFiles(_pathPending);
                    //            foreach (string file in files)
                    //            {
                    //                File.Delete(file);

                    //            }
                    //            return;
                    //        }
                    //    }


                    //    after your loop


                    //}

                    //

                }
                cons.update("update sc_rcv set push = 'no' where id=" + (linNum + 1).ToString());
                cons.Close();
            }// go if end
             //}//for end

        }

        public string checkStatusReturn25(string filePath)
        {
            string _isvalid = string.Empty;
            //reading all the lines(rows) from the file.
            string[] rows = File.ReadAllLines(filePath);

            DataTable dtData = new DataTable();
            string[] rowValues = null;
            DataRow dr = dtData.NewRow();

            //Creating columns
            Int32 _i = 0;
            if (rows.Length > 0)
            {
                for (int row = 0; row < rows.Length; row++)
                {
                    rowValues = rows[row].Split(',');
                    //if (rowValues[0].Contains("OP10"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP20"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP30"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP40"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP50"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP60"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP70"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP80"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP90"))
                    //{ _i = _i + 1; }

                    if (rowValues[3].Contains("NG"))
                    { _i = _i + 1; }

                }
                //foreach (string columnName in rows[0].Split(','))
                //{ 
                //    dtData.Columns.Add(_i.ToString()); _i = _i + 1; 
                //}
            }
            if (_i == 0)
            { _isvalid = "OK"; }
            else
            { _isvalid = "NG"; }
            ////Creating row for each line.(except the first line, which contain column names)
            //for (int row = 0; row < rows.Length; row++)
            //{
            //    rowValues = rows[row].Split(',');
            //    dr = dtData.NewRow();
            //    if (rowValues[0].ToString().Trim() != "FN_OP10")
            //    {
            //        dr.ItemArray = rowValues;
            //    }


            //    dtData.Rows.Add(dr);
            //}



            return _isvalid;
        }


        #endregion

        #region "26 okaya"

        private string _pathPending26 = "\\\\192.168.65.248\\iemt\\Pending";
        private string _pathSave26 = "\\\\192.168.65.248\\iemt\\Judement";      
        private string _filenameOkaya26 = string.Empty;

        List<List<string>> scanResult26 = new List<List<string>>();
        private void backgroundWorker_okaya_M26_DoWork_1(object sender, DoWorkEventArgs e)
        {

            List<string> targ = (e.Argument as List<string>);
            bool RcvFinish = false;
            int size = 0;
            string receiveString = "";
            //targ[0] = "3";
            int id = int.Parse(targ[0]);
            string lastReads = Rcvs[id - 1][1];
            List<string> ans = new List<string>();
            ans.Add(targ[0]);
            ans.Add("none");
            ans.Add(lastReads);

            DirectoryInfo di = new DirectoryInfo(_pathPending26);
            FileInfo[] files = di.GetFiles("*.csv");

            List<string> tmp = new List<string>();
            //MessageBox.Show(files.Length.ToString());
            //System.Threading.Thread.Sleep(2000);

            scanResult26.Clear();
            if (files.Length > 0)
            {

                using (var csv = new CsvReader(files[0].FullName))
                {

                    while ((tmp = csv.ReadRow()) != null)
                    {

                        scanResult26.Add(tmp);
                    }
                }//using end


                _filenameOkaya26 = files[0].Name;

                //File.Delete(files[0].FullName);
                //File.Copy(files[0].FullName, _pathSave + files[0].Name, true);
            }
            if (scanResult26.Count > 0)
            {

                ans[1] = scanResult26[0][0];
                ans[2] = scanResult26[0][1];

            }
            else
            {
                ans[1] = "skip";
            }
            e.Result = ans;


        }

        private void backgroundWorker_okaya_M26_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {

                List<string> result = (e.Result as List<string>);


                int id = int.Parse(result[0]);

                
                if (result[1] != "skip")
                {
                    Rcvs[id - 1][0] = result[1];
                    Rcvs[id - 1][1] = result[2];//System.DateTime.Now.ToString("yyyyMMddHHmmss");
                    var cons = new Connector();
                    //DBへpush
                    if (cons.Connect(tcpTargets[0][0], tcpTargets[0][1], tcpTargets[0][2], tcpTargets[0][3]))
                    {


                        cons.update("update sc_rcv set rcv_data = '" + result[1] + "' where id=" + result[0]);

                        cons.update("update sc_rcv set rcv_time = '" + Rcvs[id - 1][1] + "' where id=" + result[0]);
                        cons.update("update sc_rcv set push = 'go' where id=" + result[0]);

                        //insert
                        string lineName = "mc22";
                        string cmd_key = "insert into sch_" + lineName + "(rcv_time, rcv_data, rcv_line) ";

                        string cmd_val = string.Format("value( '{0}','{1}','{2}')",
                                                        Rcvs[id - 1][1], result[1], lineName
                                                        );

                        cons.insert(cmd_key + cmd_val);

                        cons.Close();


                    }


                    makeCSV_Info_Okaya26(2);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void makeCSV_Info_Okaya26(int linNum)
        {
            //sc_rcvを取得
            //for loop
            //push == goなら
            //push をnoneに
            //rcv_dataでtb_pmからselect serial = rcv_data AND(ev=3 or ev =5)
            // 時刻でsort
            //DBへpush
            // for (int linNum = 0; linNum < 7; linNum++)
            // {
            var cons = new Connector();
            if (cons.Connect(Targets[0][0], Targets[0][1], Targets[0][2], Targets[0][3]))
            {

                DataTable firstData = new DataTable();
                DataTable tempData = new DataTable();
                DataTable scanSt = new DataTable();
                DataTable QcResult = new DataTable();


                bool readOK = cons.TableReader("SELECT * FROM sc_rcv", scanSt);

                //  textBox1.Text = scanSt.Rows[0]["rcv_data"].ToString();
                //  textBox2.Text = scanSt.Rows[1]["rcv_data"].ToString();
                //  textBox3.Text = scanSt.Rows[2]["rcv_data"].ToString();
                //  textBox4.Text = scanSt.Rows[3]["rcv_data"].ToString();
                //  textBox5.Text = scanSt.Rows[4]["rcv_data"].ToString();
                //  textBox6.Text = scanSt.Rows[5]["rcv_data"].ToString();
                //  textBox7.Text = scanSt.Rows[6]["rcv_data"].ToString();




                if (scanSt.Rows[linNum]["push"].ToString() == "go")
                {

                    string selectKey = scanSt.Rows[linNum]["rcv_data"].ToString();

                    if (selectKey.Length > 19)
                    {
                        selectKey = Right(selectKey, 19);
                    }
                    else if (selectKey.Length < 16)
                    {
                        return;
                    }
                    string selectKey2 = selectKey;

                    if (linNum == 1)
                    {
                        try
                        {
                            selectKey2 = selectKey.Substring(2, 10);
                            //selectKey = selectKey2;
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    else
                    {
                        try
                        {
                            if (selectKey.Length > 15)
                            {
                                selectKey2 = selectKey.Substring(0, selectKey.Length - 7);
                                //selectKey = selectKey2;
                            }
                        }
                        catch (Exception ee)
                        {

                        }
                    }



                    List<List<string>> csvs = new List<List<string>>();
                    List<string> tmprw = new List<string>();
                    //tmprw.Add(selectKey2);
                    //for kn serial
                    string str0 = selectKey.Substring(0, 6);
                    string str1 = selectKey.Substring(6, 6);
                    string str2 = selectKey.Substring(16, 3);//botom == model name

                    //for QC KN
                    string lineNumStr = str0.Substring(0, 2);
                    string ModelNumStr = str2;

                    tmprw.Add(str0 + " " + str1 + " " + str2);//for KN line
                    tmprw.Add("Search..");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");
                    tmprw.Add("0");

                    csvs.Add(tmprw);

                    for (int i = 0; i < 30; i++)
                    {
                        tmprw = new List<string>();
                        tmprw.Add("-");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");
                        tmprw.Add("");

                        csvs.Add(tmprw);
                    }

                    //とりあえず一発
                    using (var writer = new CsvWriter(csvPath[linNum]))
                    {
                        writer.Write(csvs);
                    }

                    //QC KN
                    string qdbName;
                    if (lineNumStr == "25")
                    {
                        qdbName = "pq_25_30";
                    }
                    else if (lineNumStr == "26")
                    {
                        qdbName = "pq_26_30";
                    }
                    else
                    {
                        qdbName = "pq_27_30_1_view";
                    }


                    qdbName = "pq_26_30_view";


                    double hub_high = 0.001;
                    double hub_low = 0.000;
                    double osc_high = 0.001;
                    double osc_low = 0.000;
                    string nameA = "";
                    string nameB = "";

                    switch (ModelNumStr)
                    {
                        case "630"://LR
                        case "631":
                            hub_high = 0.058;
                            hub_low = 0.012;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.79.5";
                            nameB = "Oil Seal Dia.76";

                            break;

                        case "626"://LR
                        case "627":
                            hub_high = 0.096;
                            hub_low = 0.042;
                            osc_high = 0.04;
                            osc_low = -0.02;
                            nameA = "Hub Unit Dia.95";
                            nameB = "Oil Seal Dia.76";

                            break;
                    }


                    string tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);


                    bool readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    if (qdbName == "pq_26_30_view" && readOKQ && QcResult.Rows.Count <= 0)
                    {
                        QcResult = new DataTable();
                        qdbName = "pq_26_30_view";

                        tempKeyQ = string.Format("SELECT * FROM {0} WHERE pqSERIAL= \"{1}\" ORDER BY pqDATE desc, pqTIME  desc", qdbName, selectKey);
                        readOKQ = cons.TableReader(tempKeyQ, QcResult);

                    }

                    string tempKeyL = string.Format("SELECT * FROM tb_pm_view WHERE pmSERIAL= \"{0}\" AND (pmEV = '3' OR pmEV = '8' OR pmEV = '10' OR pmEV = '11') ORDER BY pmDATE asc, pmTIME  asc", selectKey);


                    bool readOKL = cons.TableReader(tempKeyL, firstData);

                    //dataGridView1.DataSource = tempData;

                    string stResult = "NG";

                    try
                    {
                        if (firstData.Rows.Count == 0)
                        {
                            stResult = "NoData";
                        }

                        else//重複削除
                        {

                            firstData.Columns.Remove("id");
                            DataView dv = firstData.DefaultView;
                            tempData = dv.ToTable(true, "pmDATE", "pmTIME", "pmSERIAL", "pmLINE", "pmMC", "pmAUTO", "pmEV", "pmER", "pmTOOL");

                        }

                        DataTable checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        if (checks.Rows.Count >= 1)//OP30のPM情報があれば削除
                        {
                            /*for(int i=0; i< tempData.Rows.Count; i++)
                            {
                                if(tempData.Rows[i]["pmMC"].ToString() == "300" && tempData.Rows[i].RowState != DataRowState.Deleted)
                                {
                                    tempData.Rows[i].Delete();
                                }
                            }
                            tempData.AcceptChanges();
                            */
                            RemoveSelectRows(tempData, "pmMC = '300'");
                            tempData.AcceptChanges();
                        }



                        if (QcResult.Rows.Count > 0)
                        {//QC結果からOP30ログを挿入
                            for (int i = 0; i < QcResult.Rows.Count; i++)
                            {
                                DataRow adds = tempData.NewRow();
                                adds["pmDATE"] = QcResult.Rows[i]["pqDATE"];
                                adds["pmTIME"] = QcResult.Rows[i]["pqTIME"];
                                adds["pmMC"] = "300";
                                adds["pmLINE"] = lineNumStr;
                                adds["pmEV"] = "3";
                                tempData.Rows.Add(adds);
                            }
                        }
                        tempData = GetSortedDataTable(tempData, "", "pmDATE,pmTIME,pmMC");
                        checks = new DataTable();
                        checks = GetSortedDataTable(tempData, "pmMC = '300'", "");
                        bool ml_op30 = false;
                        int cnt_op30 = 1;
                        if (checks.Rows.Count > 1)
                        {
                            ml_op30 = true;
                        }

                        int maxCnt = tempData.Rows.Count;
                        int lastCnt = 0;
                        if (maxCnt > 30)
                        {
                            maxCnt = 30;
                        }



                        for (int j = 0; j < maxCnt; j++)
                        {

                            csvs[j + 1][0] = "FN_" + checkMCName(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            csvs[j + 1][1] = checkCELL(tempData.Rows[j]["pmLINE"].ToString(), tempData.Rows[j]["pmMC"].ToString(), McNames);
                            if (tempData.Rows[j]["pmEV"].ToString() == "3")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "10")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else if (tempData.Rows[j]["pmEV"].ToString() == "11")
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "OK";
                                csvs[j + 1][4] = "";
                            }
                            else//5なら
                            {
                                csvs[j + 1][2] = tempData.Rows[j]["pmDATE"].ToString() + " " + int.Parse(tempData.Rows[j]["pmTIME"].ToString()).ToString("D6");
                                csvs[j + 1][3] = "AL";
                                //stResult = "Alarm";
                                csvs[j + 1][4] = checkEV(tempData.Rows[j]["pmER"].ToString(), Errs);
                            }
                            //op30 check
                            if (ml_op30 == true && tempData.Rows[j]["pmMC"].ToString() == "300")
                            {
                                DateTime dt = new DateTime(2019, 10, cnt_op30);
                                string suffix;
                                if (new[] { 11, 12, 13 }.Contains(dt.Day))
                                {
                                    suffix = "th";
                                }
                                else if (dt.Day % 10 == 1)
                                {
                                    suffix = "st";
                                }
                                else if (dt.Day % 10 == 2)
                                {
                                    suffix = "nd";
                                }
                                else if (dt.Day % 10 == 3)
                                {
                                    suffix = "rd";
                                }
                                else
                                {
                                    suffix = "th";
                                }



                                csvs[j + 1][3] = "AI";
                                csvs[j + 1][4] = cnt_op30.ToString() + suffix;

                                cnt_op30++;

                                if (cnt_op30 >= checks.Rows.Count)
                                {
                                    ml_op30 = false;
                                }

                            }//op30 check end

                            //全体判定
                            string mcNumber = tempData.Rows[j]["pmMC"].ToString();
                            if (mcNumber == "701")
                            {
                                if (csvs[j + 1][3] == "OK")
                                {
                                    stResult = "OK";
                                }
                            }

                            lastCnt = j + 1;

                        }



                        if (QcResult.Rows.Count > 0)
                        {
                            csvs[1][5] = nameA;
                            csvs[1][6] = (double.Parse(QcResult.Rows[0][6].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[1][7] = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[1][8] = (double.Parse(QcResult.Rows[0][8].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[1][9] = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            double hub_dx = (double.Parse(QcResult.Rows[0][5].ToString()) / 1000.0);
                            double hub_dy = (double.Parse(QcResult.Rows[0][7].ToString()) / 1000.0);
                            double osc_dx = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0);
                            double osc_dy = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0);

                            if (((hub_dx <= hub_high) && (hub_dx >= hub_low)) && ((hub_dy <= hub_high) && (hub_dy >= hub_low)))
                            {
                                csvs[1][10] = "OK";
                            }
                            else
                            {
                                csvs[1][10] = "NG";
                                //stResult = "NG";
                            }


                            csvs[2][5] = nameB;
                            csvs[2][6] = (double.Parse(QcResult.Rows[0][10].ToString()) / 1000.0).ToString("F3");//HubUnit X
                            csvs[2][7] = (double.Parse(QcResult.Rows[0][9].ToString()) / 1000.0).ToString("F3");//HubUnit dX
                            csvs[2][8] = (double.Parse(QcResult.Rows[0][12].ToString()) / 1000.0).ToString("F3");//HubUnit Y
                            csvs[2][9] = (double.Parse(QcResult.Rows[0][11].ToString()) / 1000.0).ToString("F3");//HubUnit dY

                            if (((osc_dx <= osc_high) && (osc_dx >= osc_low)) && ((osc_dy <= osc_high) && (osc_dy >= osc_low)))
                            {
                                csvs[2][10] = "OK";
                            }
                            else
                            {
                                csvs[2][10] = "NG";
                                //stResult = "NG";
                            }

                            if (csvs[1][10] == "NG" || csvs[2][10] == "NG")
                            {
                                stResult = "NG";
                            }


                        }
                        else//該当無し
                        {


                        }


                        //PQ編
                        if (linNum == 1)
                        {
                            int cntstt = lastCnt + 1;

                            foreach (List<string> odt in Targets_PQ)
                            {
                                string selects = scanSt.Rows[linNum]["rcv_data"].ToString();

                                string temps = string.Format("SELECT * FROM `{0}` WHERE pqSERIAL= \"{1}\" " +
                                    "AND pmDATE BETWEEN date_format(current_date - INTERVAL 30 DAY,'%y%m%d') " +
                                    "AND date_format(current_date,'%y%m%d')", odt[1], selects);

                                string tests;

                                tests = selects;

                                tempData = new DataTable();
                                bool readOKq;

                                //try {
                                readOKq = cons.TableReader(temps, tempData);
                                //}

                                //                                catch(Exception ex)
                                //                              {
                                //                                MessageBox.Show(ex.ToString());
                                //                          }

                                //最大カウントチェック 後で足せ


                                for (int k = 0; k < tempData.Rows.Count; k++)
                                {
                                    csvs[cntstt + k][0] = "QC_" + odt[6];//MC Name
                                    csvs[cntstt + k][1] = odt[7];//cell name


                                    switch (odt[2])
                                    {
                                        case "0":
                                            csvs[cntstt + k][2] = tempData.Rows[k]["pqDATE"].ToString() + " " + int.Parse(tempData.Rows[k]["pqTIME"].ToString()).ToString("D6");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック
                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                        case "1":
                                            DateTime conv = DateTime.Parse(tempData.Rows[k]["clocktime"].ToString());
                                            csvs[cntstt + k][2] = conv.ToString("yyMMdd HHmmss");

                                            csvs[cntstt + k][3] = CheckQCResult(tempData.Rows[k], odt[8]);//OK NGをチェック

                                            if (csvs[cntstt + k][3] == "NG")
                                            {
                                                stResult = "NG";
                                            }

                                            csvs[cntstt + k][4] = "";

                                            break;
                                    }

                                    lastCnt = cntstt + k;
                                }//for end

                                cntstt = lastCnt + 1;

                            }//foreach end


                        }//linNum if end
                    }
                    catch (Exception ee)
                    {
                        stResult = "NoPMdata";
                        goto ENDs;
                    }

                ENDs:


                    csvs[0][1] = stResult;


                    using (var writer = new CsvWriter("C:\\xampp\\htdocs\\isz\\mc22\\info.csv"))
                    {
                        writer.Write(csvs);
                    }


                    string _Result = checkStatusReturn26("C:\\xampp\\htdocs\\isz\\mc22\\info.csv");
                    List<string> lines2 = new List<string>();
                    string[] lines = File.ReadAllLines("C:\\xampp\\htdocs\\isz\\mc22\\info.csv");
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string line = lines[i];
                        if (line.Contains(","))
                        {
                            if (i == 0)
                            {
                                var split = line.Split(',');

                                split[1] = _Result;
                                line = string.Join(",", split);

                                lines2.Add(line);
                            }
                            else
                            {
                                var split = line.Split(',');
                                line = string.Join(",", split);

                                lines2.Add(line);
                            }

                        }
                    }
                    File.WriteAllLines(@"C:\\xampp\\htdocs\\isz\\mc22\\info.csv", lines2);




                    //if (_status)
                    //  {


                    var csv = new StringBuilder();


                    foreach (List<string> a in scanResult26)
                    {
                        foreach (string b in a)
                        {
                            var newLine = string.Format("{0},{1},{2}", a[0], a[1], _Result.Replace("\r\n", ""));
                            csv.AppendLine(newLine);
                            //after your loop

                            if (!Directory.Exists(_pathSave26))
                            {
                                Directory.CreateDirectory(_pathSave26);
                            }

                            File.WriteAllText(_pathSave26 + "\\" + _filenameOkaya26, csv.ToString());

                            string[] files = Directory.GetFiles(_pathPending26);
                            //System.Threading.Thread.Sleep(2000);
                            foreach (string file in files)
                            {
                                File.Delete(file);

                            }

                            return;
                        }
                    }



                    //}

                    //else
                    //{

                    //    var csv = new StringBuilder();


                    //    foreach (List<string> a in scanResult)
                    //    {
                    //        foreach (string b in a)
                    //        {
                    //            var newLine = string.Format("{0},{1},{2}", a[0], a[1], "NG");
                    //            csv.AppendLine(newLine);

                    //            File.WriteAllText(_pathSave + "\\" + _filenameOkaya, csv.ToString());

                    //            string[] files = Directory.GetFiles(_pathPending);
                    //            foreach (string file in files)
                    //            {
                    //                File.Delete(file);

                    //            }
                    //            return;
                    //        }
                    //    }


                    //    after your loop


                    //}

                    //

                }
                cons.update("update sc_rcv set push = 'no' where id=" + (linNum + 1).ToString());
                cons.Close();
            }// go if end
             //}//for end

        }

        public string checkStatusReturn26(string filePath)
        {
            string _isvalid = string.Empty;
            //reading all the lines(rows) from the file.
            string[] rows = File.ReadAllLines(filePath);

            DataTable dtData = new DataTable();
            string[] rowValues = null;
            DataRow dr = dtData.NewRow();

            //Creating columns
            Int32 _i = 0;
            if (rows.Length > 0)
            {
                for (int row = 0; row < rows.Length; row++)
                {
                    rowValues = rows[row].Split(',');
                    //if (rowValues[0].Contains("OP10"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP20"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP30"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP40"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP50"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP60"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP70"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP80"))
                    //{ _i = _i + 1; }
                    //if (rowValues[0].Contains("OP90"))
                    //{ _i = _i + 1; }

                    if (rowValues[3].Contains("NG"))
                    { _i = _i + 1; }

                }
                //foreach (string columnName in rows[0].Split(','))
                //{ 
                //    dtData.Columns.Add(_i.ToString()); _i = _i + 1; 
                //}
            }
            if (_i == 0)
            { _isvalid = "OK"; }
            else
            { _isvalid = "NG"; }
            ////Creating row for each line.(except the first line, which contain column names)
            //for (int row = 0; row < rows.Length; row++)
            //{
            //    rowValues = rows[row].Split(',');
            //    dr = dtData.NewRow();
            //    if (rowValues[0].ToString().Trim() != "FN_OP10")
            //    {
            //        dr.ItemArray = rowValues;
            //    }


            //    dtData.Rows.Add(dr);
            //}



            return _isvalid;
        }





        #endregion

       
    }//class end
}//namespace end

namespace connectorMySQL
{
    class Connector
    {
        //MySQLへの接続情報
        public MySqlConnection conn;
        public Connector()
        {
            // public MySqlConnection conn;
        }

        //MySQLに接続する　boolで接続が成功したかどうかを返す
        public bool Connect(string user, string password, string db, string HostIP)
        {
            string connstr = string.Format("userid={0};password={1};database={2};Host={3}",
            user, password, db, HostIP);
            conn = new MySqlConnection(connstr);

            try
            {
                conn.Open();
            }
            catch (MySqlException ex)
            {
                //MessageBox.Show("Connection Failed.\n" + ex.Message);
                return false;
            }

            //MessageBox.Show("Connection Success.");
            return true;
        }

        //MySQLから切断する　boolで切断が成功したかどうかを返す
        public bool Close()
        {

            try
            {
                conn.Close();
            }
            catch (MySqlException ex)
            {
                // MessageBox.Show("Connection Failed.\n" + ex.Message);
                return false;
            }

            //  MessageBox.Show("Connection Success.");
            return true;
        }

        //テーブルからデータを取得する
        public bool TableReader(string select_sql, DataTable datatable)
        {
            MySqlDataAdapter da = new MySqlDataAdapter(select_sql, conn);
            try
            {
                da.Fill(datatable);
            }
            catch (MySqlException ex)
            {
                //    //MessageBox.Show("データ取得に失敗しました\n" + ex.Message);
                return false;
            }
            return true;

        }
        //データ追加　Auto Incrementの数値を返す 失敗時は 0
        public int insert(string insert_sql)
        {
            MySqlCommand cmd = new MySqlCommand(insert_sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                //  MessageBox.Show("データの追加に失敗しました\n" + ex.Message);
                return 0;
            }
            //int autoinc = int.Parse(MySqlHelper.ExecuteScalar(conn, "select last_insert_id()").ToString());
            return 1;//return autoinc;
        }

        //データ更新　boolで成功/失敗を返す
        public bool update(string update_sql)
        {
            MySqlCommand cmd = new MySqlCommand(update_sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                //MessageBox.Show("データの更新に失敗しました\n" + ex.Message);
                return false;
            }
            return true;
        }

        //データ削除　boolで成功/失敗を返す
        public bool delete(string delete_sql)
        {
            MySqlCommand cmd = new MySqlCommand(delete_sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                //MessageBox.Show("Delete failed.\n" + ex.Message);
                return false;
            }
            return true;
        }



       
    }//class end


}//namespace end
