using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Common;

namespace MeterPlugInLibrary
{
    public class SweepCode
    {
        private string strCode = "";//扫码信息

        private bool isError = false;//扫码信息
        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;
        public void StartThreadSweep()
        {
            mThread = new Thread(new ThreadStart(ThreadSweepInfo));
            mThread.Start();
        }

        /// <summary>
        /// 扫码信息读取
        /// </summary>
        /// <returns></returns>
        private void ThreadSweepInfo()
        {
            try
            {
                while (true)
                {
                    lock (obj)
                    {
                        string sCode = "";
                        Thread.Sleep(500);
                        //WriteLog("开始扫码线程：重量状态为：" + strState);
                        if (strState.Equals("0"))
                        {
                            sCode = GetSweepCodeInfo(15, 11, "9600,N,8,1");//扫码信息;九江用COM7
                            WriteLog("扫码返回：" + sCode);
                            if (!string.IsNullOrEmpty(sCode) && !isError) 
                            {
                                strCode = sCode;
                                string lb = "进入扫码";
                                WriteLog(lb + ",读到的二维码扫码信息：" + strCode);
                            }
                            else
                            {
                                strCode = "";
                            }
                            //Thread.Sleep(20 * 1000);//15秒执行一次
                        }
                        else if (strState.Equals("2"))
                        {
                            strCode = "";
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                strCode = "";
                WriteLog("扫码信息读取异常！" + exp.Message);
            }
        }
        /// <summary>
        /// 关闭线程
        /// </summary>
        /// <returns></returns>
        public bool CloseThread()
        {
            try
            {
                if (mThread != null)
                {
                    mThread.Abort();
                    Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <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)
                {
                    isError = true;
                    WriteLog("设备类型异常");
                    return "设备类型异常";
                }

                i = Scanning.OpenDevice(iPort, strComParam);//打开扫描枪
                if (i != 0)
                {
                    isError = true;
                    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)
            {
                isError = true;
                WriteLog("扫码异常！" + exp.Message);
                return "";
            }
        }
      
        /// <summary>
        /// 关闭扫描枪
        /// </summary>
        public void Close()
        {
            WriteLog("扫码关闭！");
            Scanning.CloseDevice();//关闭扫描枪
        }

        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();
        }
    }
}
