
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Management;
using System.Windows.Forms;
using tool;
namespace tool
{
    public class PrintManual : Singleton<PrintManual>
    {
        PrintDocument printDocument;
        Thread m_print_thread;
        bool m_isClosed;
        bool m_isStart;
        string m_print_str;
        string m_print_commedkey;

        private PrintManual()
        {
            
        }
        /// <summary>
        /// 初始化打印机
        /// </summary>
        public void PrintManualInit()
        {
            printDocument = new PrintDocument();
            m_print_thread = new Thread(print_thread);
            m_isClosed = true;
            m_isStart = false;
            m_print_str = "";
            m_print_commedkey = "";
        }
        /// <summary>
        /// 开启打印机
        /// </summary>
        public void Start()
        {
            m_isClosed = false;
            m_print_thread.Start();
        }
        /// <summary>
        /// 关闭打印机
        /// </summary>
        public void Close()
        {
            m_isClosed = true;
            m_print_thread.Abort();
        }
        /// <summary>
        /// 打印二维码，第一个参数二维码内容 第二个参数打印字符串
        /// </summary>
        /// <param name="str"></param>
        public void PrintTicket(string commedkey,string str)
        {
            if (str != "" && commedkey != "")
            {
                m_print_str = str;
                m_print_commedkey = commedkey;
                m_isStart = true;
            }
            else
            {
                MessageBox.Show("打印字符串为空！ str="+str+" commedkey="+ m_print_commedkey);
            }
        }
        private void print_thread()
        {
            while (!m_isClosed)
            {
                if (m_isStart && m_print_str!="" && m_print_commedkey != "")
                {
                    PrintTicketProcess(m_print_commedkey,m_print_str);
                    m_isStart = false;
                }
                Thread.Sleep(1);
            }
        }

        /// <summary>
        /// 打印车牌信息处理并语音提示
        /// </summary>
        /// <param name="context">车牌信息</param>
        /// <param name="APIType">语音提示要获取的类型的 ProgID</param>
        /// <param name="content">语音内容</param>
        private void PrintTicketProcess(string commedkey,string context)
        {
            //打印纸是否有的判断还可能需要改动！！！！！！！！！！！！！！！！！！！！！！！！！！！
            Task.Factory.StartNew(() =>
            {
                //判断循环，只有当打印机空闲或者打印机没有纸的时候才跳出。
                GetPrinterStat("POS80");
            });
            //在打印时如果缺打印纸，则会停止打印，直到打印纸上上来为止
            if (Print(commedkey,context))
            {
               // speak("SAPI.SpVoice", "停车完成，请取走取车凭证");
            }
        }

        /// <summary>
        /// 语音提示
        /// </summary>
        /// <param name="APIType">要获取的类型的 ProgID</param>
        /// <param name="content">语音内容</param>
        //private void speak(string APIType, string content)
        //{
        //    Task.Factory.StartNew(() =>
        //    {
        //        Type type = Type.GetTypeFromProgID(APIType);
        //        dynamic spVoice = Activator.CreateInstance(type);
        //        spVoice.Speak(content);
        //    });
        //}

        /// <summary>
        /// 打印二维码
        /// </summary>
        /// <param name="context">二维码信息</param>
        /// <returns></returns>
        private bool Print(string commedkey,string context)
        {
            if ((context == null || context == string.Empty || context == "")
                && (commedkey == null || commedkey == string.Empty || commedkey == ""))
            {
                return false;
            }
            //生成二维码
            QRCode code = new QRCode(commedkey,context);

            //打印
            code.Print(printDocument);

            return true;
        }


        /// <summary>
        /// 判断打印机是否缺纸
        /// </summary>
        /// <param name="PrinterDevice"></param>
        /// <returns></returns>
        private PrinterStatus GetPrinterStat(string PrinterDevice)
        {
            bool flag = false;
            PrinterStatus ret = 0;
            try
            {
                string path = @"win32_printer.DeviceId='" + PrinterDevice + "'";
                ManagementObject printer = new ManagementObject(path);
                int i = 0;
                //判断打印机是否缺纸
                while (true)
                {
                    Object obj = printer.Properties["PrinterStatus"].Value;
                    if (Convert.ToInt32(obj) == 4 && i >= 5)
                    {
                        flag = true;
                        break;
                    }
                    if (Convert.ToInt32(obj) == 3)
                    {
                        flag = false;
                        break;
                    }
                    if (Convert.ToInt32(obj) == 4)
                    {
                        i++;
                    }
                    Thread.Sleep(500);
                }
                if (flag)
                {
                    //这里不用处理，等到打印纸上上来了之后会自动将消息转变为“停车成功，请取走取车凭证码”？？？？？？？？
                    //Messa messageForm = new MessageForm();
                    //messageForm.msgBox.Text = "打印机缺纸，请联系管理员";
                    //messageForm.Show();
                }

                ret = (PrinterStatus)Convert.ToInt32(printer.Properties["PrinterStatus"].Value);

                printer.Get();
            }
            catch (Exception ex)
            {
            }
            return ret;
        }

        enum PrinterStatus
        {
            其他状态 = 1,
            未知,
            空闲,
            正在打印,
            预热,
            停止打印,
            打印中,
            离线
        }
    }
}
