using Nirvana.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Timer = System.Timers.Timer;

namespace YBDevice.PrintTool
{
    public partial class Form1 : Form
    {
        private ScanHook scanerHook = new ScanHook();
        private bool IsPrint = false; //是否正在打印,false-否,true-是
        private DateTime? PrintTime = null;

        public Form1()
        {
            InitializeComponent();
            LoadPrinters();
            //定时器，1秒更新一次
            var timer = new Timer
            {
                AutoReset = true,
                Enabled = true,
                Interval = 1000
            };

            timer.Elapsed += this.Timer_Elapsed;
        }

        /// <summary>
        /// 定时器处理
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.BeginInvoke(
                (MethodInvoker)delegate
                {
                    this.button1.Enabled = !ScanHook.IsStart;
                    this.button2.Enabled = ScanHook.IsStart;
                    this.textBox1.Enabled = !ScanHook.IsStart;
                    this.textBox_PaperHeight.Enabled = !ScanHook.IsStart;
                    this.textBox_PaperWidth.Enabled = !ScanHook.IsStart;
                    this.button3.Enabled = this.listBox1.Items.Count > 0 && !IsPrint && ScanHook.IsStart ? true : false;
                    this.button3.Text = this.IsPrint ? "正在打印" : "打印";
                    this.comboBox1.Enabled = !ScanHook.IsStart;
                    this.textBox_x.Enabled = !ScanHook.IsStart;
                    this.textBox_y.Enabled = !ScanHook.IsStart;
                    this.comboBox_type.Enabled = !ScanHook.IsStart;
                    this.richTextBox1_logger.ReadOnly = ScanHook.IsStart;
                    this.textBox_marginw.Enabled = !ScanHook.IsStart;
                });
        }

        /// <summary>
        /// 开启钩子
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            scanerHook.Start();
            scanerHook.ScanerEvent += new ScanHook.ScanerDelegate(ScanerHook_BarCodeEventAsync);
        }

        /// <summary>
        /// 关闭钩子
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            scanerHook.Stop();
            scanerHook = new ScanHook();
        }

        /// <summary>
        /// 扫码结果
        /// </summary>
        /// <param name="scanerCodes"></param>
        private void ScanerHook_BarCodeEventAsync(ScanHook.ScanerCodes scanerCodes)
        {
            if (PrintTime.HasValue && (DateTime.Now - PrintTime.Value).TotalSeconds < 2)
            {
                return;
            }
            var text = scanerCodes.Result;
            string code = text;
            if (!string.IsNullOrEmpty(text))
            {
                if (text.ToLower().StartsWith("http"))
                {
                    var arr = text.Split('?');
                    if (arr.Length == 2)
                    {
                        arr = arr[1].Split('=');
                        if (arr.Length == 2)
                        {
                            code = arr[1];
                        }
                    }
                }
            }
            if (code.Length < 5)
            {
                AddLogger($"二维码内容过短,最少为5个字");
                return;
            }
            //检测装箱台数
            int cnt = this.textBox1.Text.ToInt();
            if (this.listBox1.Items.Count < cnt)
            {
                if (!this.listBox1.Items.Contains(code))
                {
                    this.listBox1.Items.Add(code);
                }
            }
            if (this.listBox1.Items.Count == cnt)
            {
                CreateImage();
                StartPrint();
            }
        }

        /// <summary>
        /// 生成图片
        /// </summary>
        private void CreateImage()
        {
            //获取二维码链接
            string ercode = GetCodeAsync();
            if (string.IsNullOrEmpty(ercode))
            {
                MessageBox.Show("二维码生成失败");
                return;
            }
            string imgurl = string.Empty;
            // string url = $"https://ybapi.ybhdmob.com/print/index?id={ercode}";
            string url = ercode;
            using (Bitmap map = BarcodeHelper.QrCode(url, 200, 200, 0))
            {
                var filename = $"{AppDomain.CurrentDomain.BaseDirectory}/reg/{DateTime.Now.ToString("yyyyMMdd")}";
                if (!Directory.Exists(filename))
                {
                    Directory.CreateDirectory(filename);
                }
                imgurl = $"{filename}/{DateTime.Now.ToString("yyyyMMddHHmmss")}.jpg";
                if (!File.Exists(imgurl))
                {
                    map.Save(imgurl, ImageFormat.Jpeg);
                }
            }
            var img = Image.FromFile(imgurl);
            this.pictureBox1.Image = img;
        }

        /// <summary>
        /// 获取二维码内容
        /// </summary>
        private string GetCodeAsync()
        {
            List<string> codes = new List<string>();
            foreach (var item in this.listBox1.Items)
            {
                codes.Add(item.ToString());
            }
            string str = string.Empty;
            //如果设备类型是G01,则调用接口生成二维码
            if (this.comboBox_type.SelectedIndex == 0)
            {
                //二维码格式,多个之间以|分隔
                str = string.Join("|", codes);
            }
            else
            {
                MessageBox.Show("获取二维码失败");
            }
            return str;
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            int cnt = this.textBox1.Text.ToInt();
            if (this.listBox1.Items.Count != cnt)
            {
                MessageBox.Show("装箱台数不符合要求");
                return;
            }
            CreateImage();
            StartPrint();
        }

        /// <summary>
        /// 开始打印
        /// </summary>
        private void StartPrint()
        {
            if (IsPrint)
            {
                return;
            }
            int width = this.textBox_PaperWidth.Text.ToInt();
            int height = this.textBox_PaperHeight.Text.ToInt();
            if (width <= 0 || height <= 0)
            {
                MessageBox.Show("纸张宽度/高度不可小于0");
                return;
            }
            if (this.comboBox1.SelectedItem == null)
            {
                MessageBox.Show("请先选择打印机");
                return;
            }
            string printer = this.comboBox1.SelectedItem.ToString();//选择的打印机
            if (string.IsNullOrEmpty(printer))
            {
                MessageBox.Show("请先选择打印机");
                return;
            }
            PaperSize paperSize = new PaperSize("", width, height);
            PrintDocument fPrintDocument = new PrintDocument();
            fPrintDocument.PrinterSettings.PrinterName = printer;
            fPrintDocument.PrinterSettings.Copies = 1;
            fPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
            fPrintDocument.DefaultPageSettings.PaperSize = paperSize;
            fPrintDocument.BeginPrint += startprint;
            fPrintDocument.EndPrint += endprint;
            fPrintDocument.PrintPage += printboxpage;
            fPrintDocument.Print();
        }

        /// <summary>
        /// 开始打印
        /// </summary>
        /// <param name="sender"></param>202
        /// <param name="e"></param>
        private void startprint(object sender, PrintEventArgs e)
        {
            AddLogger($"开始打印,台数{this.listBox1.Items.Count}台");
            this.IsPrint = true;
            this.listBox1.Items.Clear();
        }

        /// <summary>
        /// 打印结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void endprint(object sender, PrintEventArgs e)
        {
            AddLogger($"打印完成");
            this.listBox1.Items.Clear();
            this.IsPrint = false;
        }

        /// <summary>
        /// 打印日志
        /// </summary>
        /// <param name="text"></param>
        private void AddLogger(string text)
        {
            var PrintTime = DateTime.Now;
            this.richTextBox1_logger.Text += $"{PrintTime}:{text}\r\n";
        }

        /// <summary>
        /// 画写打印页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printboxpage(object sender, PrintPageEventArgs e)
        {
            try
            {
                int width = this.textBox_PaperWidth.Text.ToInt();
                // int ercodewidth = width - 69 <= 120 ? 120 : width - 69;
                int mw = this.textBox_marginw.Text.ToInt();
                int ercodewidth = width - mw;
                int x = this.textBox_x.Text.ToInt();
                int y = this.textBox_y.Text.ToInt();
                var img = this.pictureBox1.Image;
                Brush brush = new SolidBrush(Color.Black);//画刷
                e.Graphics.DrawImage(img, x, y, ercodewidth, ercodewidth);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 加载本地打印机列表
        /// </summary>
        /// <returns></returns>
        public void LoadPrinters()
        {
            var list = new List<string>();
            var defaultprinter = new PrintDocument().PrinterSettings.PrinterName;
            list.Add(defaultprinter);
            this.comboBox1.Items.Add(defaultprinter);
            this.comboBox1.SelectedIndex = 0;
            foreach (string fprintname in PrinterSettings.InstalledPrinters)
            {
                if (!list.Contains(fprintname))
                {
                    list.Add(fprintname);
                    this.comboBox1.Items.Add(fprintname);
                }
            }
        }
    }
}