using Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SystemOffLine
{
    public class SerialPortES
    {
        SerialPort serialPort1;
        bool blThreadFlag = false;
        private string strCode = "";//扫码信息
        public string StrCode
        {
            get { return strCode; }
            set { strCode = value; }
        }
        private string strState = "";//状态 0重量稳定 1重量不稳定 2空磅
        public string StrState
        {
            get { return strState; }
            set { strState = value; }
        }
        private object obj = new object();
        private Thread mThread = null;

        /// <summary>
        /// comPara是配置文件中的comPara
        /// </summary>
        /// <param name="comPara"></param>
        public void StartThreadSweep(string comPara)
        {
            #region 串口采集配置
            string[] strParams = comPara.Split(new char[] { ',' });
            Parity parity = Parity.None;

            if (strParams[2].ToUpper() == "ODD")
            {
                parity = Parity.Odd;
            }
            if (strParams[2].ToUpper() == "EVEN")
            {
                parity = Parity.Even;
            }

            StopBits stopBits = StopBits.None;
            if (strParams[4] == "1")
            {
                stopBits = StopBits.One;
            }
            if (strParams[4] == "1.5")
            {
                stopBits = StopBits.OnePointFive;
            }
            if (strParams[4] == "2")
            {
                stopBits = StopBits.Two;
            }
            serialPort1 = new SerialPort(strParams[0], Int32.Parse(strParams[1]),parity, Int32.Parse(strParams[3]), stopBits);

            while (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                }
                catch (Exception err)
                {
                    serialPort1.Close();
                    
                    WriteLog($"打开串口失败,正重试{err.Message}");
                    //MessageBox.Show("打开串口失败，串口可能被占用，请联系计量大厅");
                    return;
                }
                System.Threading.Thread.Sleep(500);
            }
            #endregion
            blThreadFlag = true;
            mThread = new Thread(new ThreadStart(ThreadSweepInfo));
            mThread.Start();
        }

        /// <summary>
        /// 扫码信息读取
        /// </summary>
        /// <returns></returns>
        private void ThreadSweepInfo()
        {
            try
            {
                while (blThreadFlag)
                {
                    lock (obj)
                    {
                        Thread.Sleep(100);
                        string strtmp = "";
                        if (serialPort1.BytesToRead > 0)
                        {
                            strtmp = serialPort1.ReadExisting();
                        }
                        strtmp = strtmp.Split(new char[] { '\r' })[0];
                        if (PbCache.strState.Equals("0") || PbCache.strState.Equals("1"))
                        {
                            if (strtmp != "") strCode = strtmp;
                        }
                        else
                        {
                            strCode = "";
                        }

                        /*
                        if (strState.Equals("0") || strState.Equals("1")) 
                        {
                            string strtmp = "";
                            if (serialPort1.BytesToRead > 0)
                            {
                                strtmp = serialPort1.ReadExisting();
                            }
                            strtmp = strtmp.Split(new char[] { '\r' })[0];
                            if (strtmp != "") strCode = strtmp;
                        }
                        else if (strState.Equals("2"))
                        {
                            strCode = "";
                        }
                        //*/
                    }
                }
            }
            catch (Exception exp)
            {
                WriteLog("扫码信息读取异常！" + exp.Message);
            }
        }
        /// <summary>
        /// 关闭线程
        /// </summary>
        /// <returns></returns>
        public bool CloseThread()
        {
            try
            {
                blThreadFlag = false;
                Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #region
        /*
        /// <summary>
        /// 二维码/条形码 信息获取
        /// </summary>
        /// <param name="intSleep">扫码枪多长时间关闭</param>
        /// <param name="iPort">端口</param>
        /// <param name="strComParam">波特率</param>
        /// <returns></returns>
        public string GetSweepCodeInfo(int intSleep, int iPort, string strComParam)
        {
            try
            {
                string strSweepCode = "";
                int i = Scanning.SetDeviceType(3);//设备类型
                if (i != 0)
                {
                    WriteLog("设备类型异常");
                    return "设备类型异常";
                }

                i = Scanning.OpenDevice(iPort, strComParam);//打开扫描枪
                if (i != 0)
                {
                    WriteLog("打开扫描枪异常");
                    return "";//打开扫描枪异常
                }

                byte[] szData = new byte[256];
                i = Scanning.ReadData(ref szData[0], intSleep);//同步读条码信息

                string strGet = System.Text.Encoding.Default.GetString(szData, 0, szData.Length); //将字节数组转换为字符串
                if (!string.IsNullOrEmpty(strGet))
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(strGet);
                    strGet = Encoding.GetEncoding("utf-8").GetString(buffer);
                    WriteLog("二维码信息（转换中文操作）：" + strGet);
                }
                strSweepCode = strGet.Trim().Substring(0, 120).Replace("\r", "").Replace("\n", "").Replace(" ", "").Replace("\0", "");//得到二维码编号
                //strSweepCode = strSweepCode.Split('|')[0];
                if (!string.IsNullOrEmpty(strSweepCode))
                    WriteLog("二维码编号：【" + strSweepCode + "】");
                i = Scanning.CloseDevice();//关闭扫描枪
                return strSweepCode;
            }
            catch (Exception exp)
            {
                WriteLog("扫码异常！" + exp.Message);
                return "";
            }
        }
        //*/
        #endregion

        /// <summary>
        /// 关闭扫描枪
        /// </summary>
        public void Close()
        {
            WriteLog("扫码关闭！");
            if (serialPort1 != null && serialPort1.IsOpen) serialPort1.Close();
            //关闭线程
            if (mThread != null) mThread.Abort();
        }

        private void WriteLog(string str)
        {
            string m_szRunPath;
            m_szRunPath = System.Environment.CurrentDirectory;
            if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
            {
                System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
            }
            string strDate = System.DateTime.Now.ToString("yyyyMMdd");
            string strPathFile = m_szRunPath + "\\log\\" + strDate;
            if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(strPathFile);
            }
            System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\扫码设备_" + strDate + ".log", true);

            tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            tw.WriteLine(str);
            tw.WriteLine("\r\n");

            tw.Close();
        }
    }
}
