using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Common;
using ChuPiao.AutoPrint.Machine;
using ChuPiao.AutoPrint.Services;
using ChuPiao.AutoPrint.Services.AutoEncash;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using ChuPiao.AutoPrint.Desktop.Properties;
using System.IO;

namespace ChuPiao.AutoPrint.Desktop.AutoEncash
{
    public partial class AutoEncashView : UserControl
    {
        private AutoEncashService _service;
        public AutoEncashView()
        {
            InitializeComponent();

            this.lblEncashedTotalMoney.Text = "0";
            this.lblEncashedTotalTicket.Text = "0";
            this.lblTotalMoney.Text = "0";
            this.lblTotalTicket.Text = "0";
            this.lblTotalMoneyOfAssign.Text = "0";
            this.lblTotalTicketOfAssign.Text = "0";
        }
        public event EventHandler CheckedChanged;

        public AutoEncashService Service
        {
            get { return _service; }
            set 
            { 
                _service = value;
                ShowLotMachineInfo();
                _service.Encashing += new EventHandler<TicketEventArgs>(_service_Encashing);
                _service.Encashed += new EventHandler<TicketEventArgs>(_service_Encashed);
                _service.EncashTicketLoaded += new EventHandler(_service_EncashTicketLoaded);
                _service.StatusChanged += new EventHandler<MachineStatusArgs>(LotMachine_StatusChanged);
            }
        }
        public void ShowLotMachineInfo()
        {
            //this.gbxMachine.Text = Service.LotMachine.MachineInfo.M_ZxNumber;
            //this.chkMacNumber.Text = Service.LotMachine.MachineInfo.M_Number;

            try
            {
                M_MachineEntity machineEntity = Service.LotMachine.MachineInfo;
                string typeDesc = EnumDescription.GetFieldText((MachineType)machineEntity.M_Type);

                this.gbxMachine.Text = string.Concat(machineEntity.M_ZxNumber, "[", typeDesc, "]");
                this.llblEncashConfig.Text = machineEntity.M_Number;
                //Application.DoEvents();
            }
            catch (Exception exception)
            {
                LoggingService.Info(string.Concat("更新机器信息界面异常。错误信息：", exception.Message));
            }
        }
        void _service_EncashTicketLoaded(object sender, EventArgs e)
        {
            //WorkbenchSingleton.SafeThreadCall(new Action(ShowEncashTicket)); 
            try
            {
                
                WorkbenchSingleton.SafeThreadAsyncCall(new Action(ShowEncashTicket));
            }
            catch (Exception exception)
            {
                LoggingService.Info(string.Concat("加载兑奖票完成更新界面异常。错误信息：", exception.Message));
            }
        }
        void LotMachine_StatusChanged(object sender, MachineStatusArgs e)
        {
            //WorkbenchSingleton.SafeThreadCall(new Action<MachineStatusEnum>(ShowMachineStatus), e.MachineStatus);
            try
            {
                WorkbenchSingleton.SafeThreadAsyncCall(new Action<MachineStatusEnum>(ShowMachineStatus), e.MachineStatus);
            }
            catch (Exception exception)
            {
                LoggingService.Info(string.Concat("机器状态变化更新界面异常。错误信息：", exception.Message));
            }
        }

        void _service_Encashed(object sender, TicketEventArgs e)
        {

            //WorkbenchSingleton.SafeThreadCall(new Action<L_LotTicketEntity>(ShowTicketEncashed), e.TicketEntity);
            try
            {
                WorkbenchSingleton.SafeThreadAsyncCall(new Action<L_LotTicketEntity>(ShowTicketEncashed), e.TicketEntity);
            }
            catch (Exception exception)
            {
                LoggingService.Info(string.Concat("更新兑奖完成界面异常。错误信息：", exception.Message));
            }
        }

        void _service_Encashing(object sender, TicketEventArgs e)
        {
            //WorkbenchSingleton.SafeThreadCall(new Action<L_LotTicketEntity>(ShowTicketEncashing), e.TicketEntity);

            try
            {
                WorkbenchSingleton.SafeThreadAsyncCall(new Action<L_LotTicketEntity>(ShowTicketEncashing), e.TicketEntity);
            }
            catch (Exception exception)
            {
                LoggingService.Info(string.Concat("更新兑奖中界面异常。错误信息：", exception.Message));
            }
        }
        void ShowEncashTicket()
        {
            this.lblTotalMoney.Text = _service.TotalMoney.ToString("0.##");
            this.lblTotalTicket.Text = _service.TotalTicket.ToString();
            this.lblEncashedTotalMoney.Text = _service.EncashedTotalMoney.ToString("0.##");
            this.lblEncashedTotalTicket.Text = _service.EncashedTotalTicket.ToString();
            this.lblTotalMoneyOfAssign.Text = _service.TotalMoneyOfAssign.ToString("0.##");
            this.lblTotalTicketOfAssign.Text = _service.TotalTicketOfAssign.ToString();

            this.AddEncashTickets(_service.AllEncashTickets);
        }
        void ShowEncashSummary()
        {
            this.lblTotalMoney.Text = _service.TotalMoney.ToString("0.##");
            this.lblTotalTicket.Text = _service.TotalTicket.ToString();
            this.lblEncashedTotalMoney.Text = _service.EncashedTotalMoney.ToString("0.##");
            this.lblEncashedTotalTicket.Text = _service.EncashedTotalTicket.ToString();
        }

        public bool IsSelected
        {
            get { return this.chkMacNumber.Checked; }
        }
        private void chkMacNumber_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckedChanged != null)
            {
                CheckedChanged(sender, e);
            }
        }

        public void DeSelect()
        {
            this.chkMacNumber.Checked = !this.chkMacNumber.Checked;
        }

        public void Start()
        {
            if (IsSelected)
            {
                //Service.TicketInterval=this.

                Service.WaitEncashTickets.Clear();
                Service.EncashedTotalTicket = 0;
                //Service.EncashedTotalMoney = 0;
                foreach (ListViewItem item in this.lvwTicket.CheckedItems)
                {
                    //item.UseItemStyleForSubItems = false;
                    item.SubItems[item.SubItems.Count - 1].Text = "未打印";
                    item.ForeColor = Color.Red;
                    L_LotTicketEntity entity = item.Tag as L_LotTicketEntity;
                    Service.WaitEncashTickets.Enqueue(entity);
                }
                //foreach (ListViewItem item in this.lvwTicket.Items)
                //{
                //    if(item.Checked)
                //    {
                //        L_LotTicketEntity entity = item.Tag as L_LotTicketEntity;
                //        Service.WaitEncashTickets.Enqueue(entity);
                //    }
                    
                    
                //}

                this.lblStatus.Image = Resources.Run;
                Service.Start();
                _service.LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Encashing;
            }
        }
        public void Stop()
        {
            if (IsSelected)
            {
                //this.lblPlayType.Text = "服务已停止";
                this.lblStatus.Image = Resources.Stop;
                Service.Stop();
                _service.LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Stopped;
            }
        }

        void ShowTicketEncashing(L_LotTicketEntity ticketEntity)
        {
            ShowEncashSummary();
            int lineIndex = -1;
            for (int i = 0; i < this.lvwTicket.Items.Count; i++)
            {
                L_LotTicketEntity entity = this.lvwTicket.Items[i].Tag as L_LotTicketEntity;
                if (entity!=null && entity.L_TicketCode == ticketEntity.L_TicketCode)
                {
                    lineIndex = i;
                }
            }
            if(lineIndex>=0)
            {
                this.lvwTicket.Items[lineIndex].SubItems[2].Text = "打印中……";
                this.lvwTicket.Items[lineIndex].ForeColor = Color.Blue;
            }
        }
        void ShowTicketEncashed(L_LotTicketEntity ticketEntity)
        {
            ShowEncashSummary();
            int lineIndex = -1;
            for (int i = 0; i < this.lvwTicket.Items.Count; i++)
            {
                L_LotTicketEntity entity = this.lvwTicket.Items[i].Tag as L_LotTicketEntity;
                if (entity != null && entity.L_TicketCode == ticketEntity.L_TicketCode)
                {
                    lineIndex = i;
                }
            }
            if (lineIndex >= 0)
            {
                //已兑奖移至尾行
                this.lvwTicket.Items[lineIndex].Checked = false;
                this.lvwTicket.Items[lineIndex].SubItems[2].Text = "打印完成"; ;
                this.lvwTicket.Items[lineIndex].ForeColor = Color.Green;
                this.lvwTicket.EnsureVisible(lineIndex);
                //ListViewItem item = this.lvwTicket.Items[lineIndex];
                //this.lvwTicket.Items.RemoveAt(lineIndex);
                //this.lvwTicket.Items.Add(item);
            }
        }
        void ShowMachineStatus(MachineStatusEnum machineStatus)
        {
            switch (machineStatus)
            {
                case MachineStatusEnum.Stopped:
                    this.lblStatus.Image = Resources.Stop;
                    break;
                case MachineStatusEnum.Stopping:
                    this.lblStatus.Image = Resources.Pause;
                    break;
                case MachineStatusEnum.Error:
                    this.lblStatus.Image = Resources.Warning;
                    break;
                case MachineStatusEnum.Encashing:
                    this.lblStatus.Image = Resources.Run;
                    break;
            }
        }

        public void AddEncashTickets(List<L_LotTicketEntity> tickets)
        {
            this.lvwTicket.Items.Clear();
            int i = 1;
            foreach (L_LotTicketEntity ticket in tickets)
            {
                ListViewItem listViewItem =
                    new ListViewItem(new string[]
                                         {i.ToString(), ticket.L_TicketCode, "未打印"});
                listViewItem.ForeColor = Color.Red;
                listViewItem.Checked = true;
                listViewItem.Tag = ticket;
                this.lvwTicket.Items.Add(listViewItem);
                i++;
            }
        }

        private void llblEncashConfig_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            try
            {
                EncashConfigDialog dlgMachineEdit = new EncashConfigDialog(_service.LotMachine.MachineInfo);
                dlgMachineEdit.ShowDialog();
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("查看兑奖配置异常。错误信息：", exception.Message));
            }
        }

        private void llblReverseSelect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
           
                for (int i = 0; i < this.lvwTicket.Items.Count; i++)
                {
                    lvwTicket.Items[i].Checked = !lvwTicket.Items[i].Checked;
                }
                LoggingService.Info("反选成功！");

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            int from = 0;
            int to = 0;
            if (!Int32.TryParse(this.textBox1.Text.Trim(), out from) || !Int32.TryParse(this.textBox2.Text.Trim(), out to))
            {
                MessageBox.Show("序号请填数字！");
                return;
            }

            if (from >= to)
            {
                MessageBox.Show("前面的序号要小于后面的序号，请重填！");
                return;
            }


                for (int i = 0; i < this.lvwTicket.Items.Count; i++)
                {
                    if (i + 1 >= from && i + 1 <= to)
                    {
                        lvwTicket.Items[i].Checked = true;
                    }
                    else
                    {
                        lvwTicket.Items[i].Checked = false;
                    }
                }

                LoggingService.Info("序号选择成功！");

        }

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

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (this.lvwTicket.CheckedItems.Count == 0)
            {
                MessageBox.Show("请选择要导出的记录！");
                return;
            }

            FolderBrowserDialog dialog = new FolderBrowserDialog();
             dialog.Description = "请选择导出文件到哪个目录";
             //dialog.RootFolder = Environment.SpecialFolder.Programs;
             if (dialog.ShowDialog() == DialogResult.OK)
             {
                 string prnPath = Path.Combine(dialog.SelectedPath, _service.LotMachine.MachineInfo.M_Number+"_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                 if (!Directory.Exists(prnPath))
                 {
                     Directory.CreateDirectory(prnPath);
                 }
                 string ticketFilePath;
                 foreach (ListViewItem item in this.lvwTicket.CheckedItems)
                 {
                     
                     L_LotTicketEntity entity = item.Tag as L_LotTicketEntity;
                     ticketFilePath = Path.Combine(prnPath, entity.L_TicketCode + ".prn");

                     try
                     {     
                         File.WriteAllText(ticketFilePath, entity.L_PrnText);
                         LoggingService.Info(string.Concat("导出电子票文件：", ticketFilePath));
                     }
                     catch (Exception exception)
                     {
                         LoggingService.Warn(string.Concat(ticketFilePath, "导出电子票文件异常。错误信息：", exception.ToString()));
                     }
                 }
             }

            
        }

       
    }
}
