using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Services;
using ChuPiao.AutoPrint.Services.AutoPrint;
using ChuPiao.Common.Core.Utils;
using ChuPiao.Common.Utils;
using ChuPiao.AutoPrint.Desktop.ZxEncashTicket;

namespace ChuPiao.AutoPrint.Desktop.AutoPrint
{
    public partial class LastTicket : Form
    {
        public string MacNumber
        {
            get { return _macNumber; }
            set { _macNumber = value; }
        }

        public string LogPath
        {
            get { return _logPath; }
            set { _logPath = value; }
        }

        public string TicketFilePath
        {
            get { return _ticketFilePath; }
            set { _ticketFilePath = value; }
        }

        public FileInfo CurrentFileInfo
        {
            get { return _currentFileInfo; }
            set { _currentFileInfo = value; }
        }

        private string _macNumber;

        private string _logPath;

        private string _ticketFilePath;

        private FileInfo _currentFileInfo;


        public LastTicket(string macNumber,string logPath)
        {
            InitializeComponent();
            _macNumber = macNumber;
            _logPath = logPath;
        }

        private void LastTicket_Load(object sender, EventArgs e)
        {
            this.Text = string.Concat(MacNumber,"最近出票记录【按出票时间由近到远排序】");

            this.dateTimePicker1.Value = DateTime.Now;

            //try
            //{
            //    TicketFilePath = Path.Combine(LogPath + DateTime.Now.ToString("yyyy-MM-dd"), "last");
            //    if(!Directory.Exists(TicketFilePath))
            //    {
            //        MessageService.ShowMessage(string.Concat("路径",TicketFilePath,"不存在！"));
            //        return;
            //    }
            //    DirectoryInfo directoryInfo=new DirectoryInfo(TicketFilePath);
            //    FileInfo[] fileInfoList = directoryInfo.GetFiles("*.prn");
            //    LastTicketFileComparer fileComparer=new LastTicketFileComparer();
            //    Array.Sort(fileInfoList, fileComparer);
            //    this.lvwTicket.Items.Clear();
            //    int index = 1;
            //    foreach (FileInfo fileInfo in fileInfoList)
            //    {
            //        ListViewItem listViewItem =
            //            new ListViewItem(new string[]
            //                                 {
            //                                     index.ToString(), fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
            //                                     fileInfo.Name
            //                                 });
            //        listViewItem.Tag = fileInfo;
            //        if(index==1)
            //        {
            //            listViewItem.Selected = true;
            //            CurrentFileInfo = fileInfo;
            //        }
            //        this.lvwTicket.Items.Add(listViewItem);
            //        index++;
            //        //if(index>50) break;
            //    }
            //}
            //catch (Exception exception)
            //{
            //    MessageService.ShowMessage(string.Concat("查看最近出票记录初始化异常。错误信息：",exception.Message));
            //}
            
        }

        private void lvwTicket_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if(this.lvwTicket.SelectedItems.Count>0)
                {
                    FileInfo fileInfo = this.lvwTicket.SelectedItems[0].Tag as FileInfo;
                    if(fileInfo!=null)
                    {
                        CurrentFileInfo = fileInfo;
                        //this.txtTicketPath.Text = fileInfo.FullName;
                        string content = File.ReadAllText(fileInfo.FullName);
                        byte[] arr = TicketTextUtil.DecryptAndDecompress(content);
                        using (MemoryStream ms = new MemoryStream())
                        {
                            ms.Write(arr, 0, arr.Length);
                            ms.Position = 0;
                            this.richTextBoxTicket.LoadFile(ms, RichTextBoxStreamType.PlainText);
                        }

                        if (this.richTextBoxTicket.Text.Contains("报表"))
                        {
                            this.btnPrint.Visible = true;
                        }
                        else
                        {
                            this.btnPrint.Visible = false;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("查看电子票内容异常。错误信息：", exception.Message));
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentFileInfo != null)
                {
                    LotMachineService.PrintETicket(MacNumber, CurrentFileInfo.FullName,true);
                   
                    //LotMachineService.PrinterClient.AddFile(CurrentFileInfo.FullName);
                    //ChuPiao.Common.Communication.CpdJson.Packs.P12014PrintTicketFile reqPack = new ChuPiao.Common.Communication.CpdJson.Packs.P12014PrintTicketFile();
                    //reqPack.MacNumber = MacNumber;
                    //reqPack.PrnText =
                    //    HexStringUtil.ByteToString(
                    //        TicketTextUtil.DecryptAndDecompress(File.ReadAllText(CurrentFileInfo.FullName)));
                    //ChuPiao.Common.Communication.CpdJson.PackRetBase packRetBase = ChuPiao.Common.Communication.CpdJson.PackManager.Instance.Transaction(MacNumber, reqPack);
                    //if (packRetBase == null)
                    //{
                    //    throw new Exception(string.Concat("执行命令失败。机器号：", MacNumber));
                    //}
                    //if (packRetBase.ReturnCode != 0)
                    //{
                    //    throw new Exception(string.Concat("彩票机返回错误编码：", packRetBase.ReturnCode, " 错误信息：", packRetBase.ReturnMessage));
                    //}
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowError(string.Concat("打印电子票异常。错误信息：", exception.Message));
            }
        }

        private void splitContainer1_Panel2_DoubleClick(object sender, EventArgs e)
        {
            //用户验证
            if (DialogResult.OK != new UserLogin(true).ShowDialog())
            {
                return;
            }

            try
            {
                if (CurrentFileInfo != null)
                {
                    LotMachineService.PrintETicket(MacNumber, CurrentFileInfo.FullName, true);

                    //LotMachineService.PrinterClient.AddFile(CurrentFileInfo.FullName);
                    //ChuPiao.Common.Communication.CpdJson.Packs.P12014PrintTicketFile reqPack = new ChuPiao.Common.Communication.CpdJson.Packs.P12014PrintTicketFile();
                    //reqPack.MacNumber = MacNumber;
                    //reqPack.PrnText =
                    //    HexStringUtil.ByteToString(
                    //        TicketTextUtil.DecryptAndDecompress(File.ReadAllText(CurrentFileInfo.FullName)));
                    //ChuPiao.Common.Communication.CpdJson.PackRetBase packRetBase = ChuPiao.Common.Communication.CpdJson.PackManager.Instance.Transaction(MacNumber, reqPack);
                    //if (packRetBase == null)
                    //{
                    //    throw new Exception(string.Concat("执行命令失败。机器号：", MacNumber));
                    //}
                    //if (packRetBase.ReturnCode != 0)
                    //{
                    //    throw new Exception(string.Concat("彩票机返回错误编码：", packRetBase.ReturnCode, " 错误信息：", packRetBase.ReturnMessage));
                    //}
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowError(string.Concat("打印电子票异常。错误信息：", exception.Message));
            }
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            this.labelMsg.Text = "-";
            this.lvwTicket.Items.Clear();
            try
            {
                TicketFilePath = Path.Combine(LogPath + this.dateTimePicker1.Value.ToString("yyyy-MM-dd"), "last");
                if (!Directory.Exists(TicketFilePath))
                {
                    //MessageService.ShowMessage(string.Concat("路径", TicketFilePath, "不存在！"));
                    this.labelMsg.Text= string.Concat(this.dateTimePicker1.Value.ToString("yyyy-MM-dd")+" 没有电子票！");
                    return;
                }
                DirectoryInfo directoryInfo = new DirectoryInfo(TicketFilePath);
                FileInfo[] fileInfoList = directoryInfo.GetFiles("*.prn",SearchOption.AllDirectories);

                if (fileInfoList.Length == 0)
                {
                    this.labelMsg.Text = string.Concat(this.dateTimePicker1.Value.ToString("yyyy-MM-dd") + " 没有电子票！");
                    return;
                }

                LastTicketFileComparer fileComparer = new LastTicketFileComparer();
                Array.Sort(fileInfoList, fileComparer);               
                int index = 1;
                foreach (FileInfo fileInfo in fileInfoList)
                {
                    ListViewItem listViewItem =
                        new ListViewItem(new string[]
                                             {
                                                 index.ToString(), fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                                 fileInfo.Name
                                             });
                    listViewItem.Tag = fileInfo;
                    if (index == 1)
                    {
                        listViewItem.Selected = true;
                        CurrentFileInfo = fileInfo;
                    }
                    this.lvwTicket.Items.Add(listViewItem);
                    index++;
                    //if(index>50) break;
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("查看最近出票记录初始化异常。错误信息：", exception.Message));
            }
        }

        private void lvwTicket_MouseDown(object sender, MouseEventArgs e)
        {
            //鼠标右键
            if (e.Button == MouseButtons.Right)
            {
                //获取鼠标在listview1的坐标
                Point p = lvwTicket.PointToClient(Control.MousePosition);
                ListViewItem item = lvwTicket.GetItemAt(p.X, p.Y);
                if (item!=null)
                {
                    FileInfo fileInfo = item.Tag as FileInfo;
                    string text = File.ReadAllText(fileInfo.FullName);
                    //将内容添加到粘贴板中
                    try
                    {
                        Clipboard.SetDataObject(text);
                        MessageBox.Show(this, "复制成功");
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show(this, ee.Message);
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;
            dialog.Title = "请选择文件";
            dialog.Filter = "(*.prn)|*.prn";
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            foreach (string filename in dialog.FileNames)
            {
                try
                {
                    LotMachineService.PrintETicket(MacNumber, filename, true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Concat("文件：", filename, ",打印票异常"));
                }
            }


        }
    }

    
}