using BarcodeLib;
using BBWY.Client.APIServices.QiKu;
using BBWY.Client.Helpers;
using BBWY.Client.Models;
using BBWY.Client.Models.APIModel.Request;
using BBWY.Client.Views.PackTask;
using BBWY.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BBWY.Client.Views.QualityTask
{
    /// <summary>
    /// BatchPrintWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BatchPrintWindow : BWindow
    {
        public BatchPrintWindow(BrandMarkType brandMarkType, Need isNeedPrintCer, long taskId, string BrandName, int GoodProductQuantity, CertificateModel[] CertificateModel, BarCodeModel BarCodeModel, QualityTaskService qualityTaskService, Action completedQuality)
        {
            InitializeComponent();
            this.Loaded += BatchPrintWindow_Loaded;
            BrandMarkType = brandMarkType;
            IsNeedPrintCer = isNeedPrintCer;
            this.BarCodeModel = BarCodeModel;
            this.GoodProductQuantity = GoodProductQuantity;
            this.CertificateModel = CertificateModel;
            this.qualityTaskService = qualityTaskService;
            this.DataContext = this;

            BarNumber = GoodProductQuantity.ToString();
            if (IsNeedPrintCer == Need.需要)
            {
                CerNumber = GoodProductQuantity.ToString();
            }
            else
            {
                CerNumber = "0";
            }




            this.qualityTaskRequest = new QualityTaskRequest
            {
                BrandMarkType = brandMarkType,
                BrandName = BrandName,
                TaskId = taskId,
            };
            if (CertificateModel != null)
                qualityTaskRequest.CerId = string.Join(",", CertificateModel.Select(c => c.Id));
            if (BarCodeModel != null)
                qualityTaskRequest.BarcodeId = BarCodeModel?.Id;
            CompletedQuality = completedQuality;

        }
        Action CompletedQuality;
        QualityTaskRequest qualityTaskRequest;
        QualityTaskService qualityTaskService;
        public Need IsNeedPrintCer { get => isNeedPrintCer; set { Set(ref isNeedPrintCer, value); } }

        private Need isNeedPrintCer;

        public BrandMarkType BrandMarkType { get => brandMarkType; set { Set(ref brandMarkType, value); } }

        private BrandMarkType brandMarkType;


        public void SetData()
        {


        }



        public CertificateModel[] CertificateModel { get; set; }

        public BarCodeModel BarCodeModel { get; set; }


        public int GoodProductQuantity { get; set; }

        private void BatchPrintWindow_Loaded(object sender, RoutedEventArgs e)
        {
            LoadPrints();
        }
        /// <summary>
        /// 获取打印机名称
        /// </summary>
        private void LoadPrints()
        {
            var printingNames = PrinterSettings.InstalledPrinters;//获取本机的打印机数据
            int index = -1;
            int selectIndex = 0;
            foreach (string name in printingNames)
            {
                if (name == "Microsoft XPS Document Writer" || name == "Microsoft Print to PDF" || name == "Fax")
                {
                    continue;
                }
                index++;
                if (name.Contains("Deli"))
                {
                    selectIndex = index;
                }
                cbPrints.Items.Add(name);
            }
            if (cbPrints.Items.Count > selectIndex)
            {
                cbPrints.SelectedIndex = selectIndex;
            }
        }


        private string barNumber;
        public string BarNumber { get => barNumber; set { Set(ref barNumber, value); } }

        private string cerNumber;
        public string CerNumber { get => cerNumber; set { Set(ref cerNumber, value); } }


        private void PrintData(int printCount, string printName, BarCodeModel barCode = null, CertificateModel certificateModel = null)
        {
            try
            {

                PrintDocument document = new PrintDocument();
                document.PrinterSettings.PrinterName = printName;//使用打印机名称,指定特定的打印机进行打印。
                                                                 //设置打印页面
                                                                 //document.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("Custom", 236, 157);
                document.PrintPage += (s, a) =>
                {
                    Font font = new Font("宋体", 6, System.Drawing.FontStyle.Regular);
                    if (barCode != null)
                    {
                        MyPrintHelper.PrintBarcode(ref a, barCode, font);
                    }
                    if (certificateModel != null)
                    {
                        MyPrintHelper.PrintCertificate(ref a, certificateModel, font);
                    }

                };
                document.PrinterSettings.Copies = (short)printCount;//打印份数
                document.Print();

            }
            catch (Exception ex)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    new TipsWindow($"打印失败,{ex.Message}").Show();
                });

            }
        }

        private void Document_PrintPage(object sender, PrintPageEventArgs args)
        {

            Font font = new Font("宋体", 6, System.Drawing.FontStyle.Regular);
            if (BarCodeModel != null)
            {
                MyPrintHelper.PrintBarcode(ref args, BarCodeModel, font);
            }
            if (CertificateModel != null)
            {
                foreach (var cer in CertificateModel)
                {
                    MyPrintHelper.PrintCertificate(ref args, cer, font);
                }

            }

        }

        private void BButton_Click(object sender, RoutedEventArgs e)
        {
            int cerNum = 0, barNum = 0;
            if (!string.IsNullOrEmpty(CerNumber))
                try
                {
                    cerNum = Convert.ToInt32(CerNumber);
                }
                catch
                {
                    MessageBox.Show("请输入数字");
                    return;
                }
            if (!string.IsNullOrEmpty(BarNumber))
                try
                {
                    barNum = Convert.ToInt32(BarNumber);
                }
                catch
                {
                    MessageBox.Show("请输入数字");
                    return;
                }



            if (barNum > 0)
            {
                if (BarCodeModel == null)
                {
                    MessageBox.Show("未设置条形码模板");
                    return;
                }
            }
            if (cerNum > 0)
            {
                if (CertificateModel == null || CertificateModel.Count() <= 0)
                {
                    MessageBox.Show("未设置合格证模板");
                    return;
                }
            }


            var res = qualityTaskService.CompeteQualityTask(qualityTaskRequest);

            if (res == null || !res.Success)
            {
                MessageBox.Show(res?.Msg ?? "未知异常");
                return;
            }


            string printName = cbPrints.Text;
            Task.Factory.StartNew(() =>
            {




                if (barNum > 0)
                {
                    if (BarCodeModel != null)
                        PrintData(barNum, printName, BarCodeModel);

                }
                if (cerNum > 0)
                {
                    if (CertificateModel != null && CertificateModel.Count() > 0)
                        foreach (var cer in CertificateModel)
                            PrintData(cerNum, printName, null, cer);
                }
                CompletedQuality?.Invoke();

                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    this.Close();
                }));


            });

        }
    }
}