using System;
using System.IO;
using System.IO.Ports;
using ChuPiao.AutoPrint.Machine.Models;
using ChuPiao.AutoPrint.Machine.Printer;
using ChuPiao.Common.Core.Utils;
using ChuPiao.Common.Models;
using log4net;
using ChuPiao.Common.Utils;

namespace ChuPiao.AutoPrint.Machine
{
    public abstract class BaseVirtualPrinter:IVirtualPrinter
    {
        #region Implementation of IVirtualPrinter

        private VirtualPrinterStatus _status;

        private ILog _log;

        private string _logPath;

        private SerialPort _printerPort;

        private string _port;

        private int _portBps;

        private M_MachineEntity _machineInfo;

        private int _lastPrintCounter;

        private string _lastPrintFilePath;

        private ILotMachine _lotMachine;

        /// <summary>
        /// 
        /// </summary>
        public ILotMachine LotMachine
        {
            get { return _lotMachine; }
            set { _lotMachine = value; }
        }

        /// <summary>
        /// 打印机状态
        /// </summary>
        public VirtualPrinterStatus Status
        {
            get { return _status; }
            set { _status=value; }
        }

        /// <summary>
        /// 日志记录器
        /// </summary>
        public ILog Log
        {
            get { return _log; }
            set { _log = value; }
        }

        /// <summary>
        /// 日志路径，不单单是日志，还有彩票机的电子票文件等都在这个路径下面，格式如：C:\example\
        /// </summary>
        public string LogPath
        {
            get { return _logPath; }
            set { _logPath = value; }
        }

        /// <summary>
        /// 端口
        /// </summary>
        public SerialPort PrinterPort
        {
            get { return _printerPort; }
            set { _printerPort = value; }
        }

        /// <summary>
        /// 端口号
        /// </summary>
        public string Port
        {
            get { return _port; }
            set { _port = value; }
        }

        /// <summary>
        /// 端口波特率
        /// </summary>
        public int PortBps
        {
            get { return _portBps; }
            set { _portBps = value; }
        }

        /// <summary>
        /// 彩票机相关信息
        /// </summary>
        public M_MachineEntity MachineInfo
        {
            get { return _machineInfo; }
            set { _machineInfo = value; }
        }
        private IPrinterClient _printerClient; 
        /// <summary>
        /// 彩票打印机
        /// </summary>
        public IPrinterClient PrinterClient
        {
            get { return _printerClient; }
            set { _printerClient = value; }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public abstract void Initialize();

        /// <summary>
        /// 启动
        /// </summary>
        public abstract void Start();

        /// <summary>
        /// 停止
        /// </summary>
        public abstract void Stop();

        /// <summary>
        /// 输出电子票数据
        /// </summary>
        /// <returns></returns>
        public abstract CaptureDataInfo Output();

        /// <summary>
        /// 输出电子票数据
        /// </summary>
        /// <returns></returns>
        public abstract CaptureDataInfo ReOutput();

        /// <summary>
        /// 强行停止当前票
        /// </summary>
        public abstract void ForceStop();

        /// <summary>
        /// 清空接收缓存
        /// </summary>
        public abstract void ClearBuffer();

        /// <summary>
        /// 打印计数器
        /// </summary>
        public int LastPrintCounter
        {
            get { return _lastPrintCounter; }
            set { _lastPrintCounter = value; }
        }

        /// <summary>
        /// 最近的打印文件路径
        /// </summary>
        public string LastPrintFilePath
        {
            get { return _lastPrintFilePath; }
            set { _lastPrintFilePath = value; }
        }

        #endregion

        protected string AlldataFilePath
        {
            get
            {
                string ticketFilePath = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "alldata");
                if (!Directory.Exists(ticketFilePath))
                {
                    Directory.CreateDirectory(ticketFilePath);
                }
                return Path.Combine(ticketFilePath, MachineInfo.M_Number + "_alldata.prn");
            }
        }

        public void SaveLastFile(CaptureDataInfo captureDataInfo)
        {
            SaveLastFile(captureDataInfo.CaptureDataBytes);
            //try
            //{
            //    LastPrintCounter++;
            //    if (LastPrintCounter > 5000)
            //    {
            //        LastPrintCounter = 1;
            //    }
            //    string ticketFilePath = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "last");
            //    if (!Directory.Exists(ticketFilePath))
            //    {
            //        Directory.CreateDirectory(ticketFilePath);
            //    }
            //    ticketFilePath = Path.Combine(ticketFilePath, LastPrintCounter + ".prn");
            //    LastPrintFilePath = ticketFilePath;
            //    File.WriteAllText(ticketFilePath, TicketTextUtil.CompressAndEncrypt(captureDataInfo.CaptureDataBytes));
            //    Log.Info(string.Concat("保存Last文件：", ticketFilePath));
            //}
            //catch (Exception exception)
            //{
            //    Log.Warn(string.Concat("保存Last文件异常。错误信息：", exception.ToString()));
            //}
        }
        public void SaveLastFile(byte[] captureDataBytes)
        {
            try
            {
                //LastPrintCounter++;
                //if (LastPrintCounter > 1000)
                //{
                //    LastPrintCounter = 1;
                //}
                string ticketFilePath = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "last");
                if (!Directory.Exists(ticketFilePath))
                {
                    Directory.CreateDirectory(ticketFilePath);
                }
                ticketFilePath = Path.Combine(ticketFilePath, DateTime.Now.ToString("yyyyMMddHHmmss") + ".prn");
                LastPrintFilePath = ticketFilePath;
                File.WriteAllText(ticketFilePath, TicketTextUtil.CompressAndEncrypt(captureDataBytes));
                //Log.Debug(string.Concat("保存Last文件：", ticketFilePath));
                Log.Debug("保存Last文件");
            }
            catch (Exception exception)
            {
                Log.Warn(string.Concat("保存Last文件异常。错误信息：", exception.ToString()));
            }
        }

        public void DeleteLastFile()
        {
            try
            {
                string ticketFilePath = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "last");
                if (Directory.Exists(ticketFilePath))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(ticketFilePath);
                    FileInfo[] fileInfoList = directoryInfo.GetFiles("*.prn");

                    if (fileInfoList.Length == 0)
                        return;

                    LastTicketFileComparer fileComparer = new LastTicketFileComparer();
                    Array.Sort(fileInfoList, fileComparer);

                    FileInfo file = fileInfoList[0];
                    file.Delete();
                    //Log.Debug(string.Concat("删除Last文件：", file.FullName));
                    Log.Debug("删除Last文件");
                }
            }
            catch (Exception exception)
            {
                Log.Debug(string.Concat("删除Last文件异常。错误信息：", exception.ToString()));
            }
        }

    }
}
