using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Forms;
using PTMedicalInsurance.Helper;
using Spire.Pdf;
using Spire.Pdf.Print;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PTMedicalInsurance.Business
{
    class LocalSettleBillPrintProcess : AbstractProcess
    {
        public override CallResult Process(JObject joInParam)
        {
            string errMsg = "";
            string insuAdmObj = JsonHelper.getDestValue(joInParam, "insuAdmObj");
            JObject joInsuAdmObj = JObject.Parse(insuAdmObj);
            JObject joRtn = invoker.invokeCenterService(TradeEnum.PrintSettlementList, joInsuAdmObj);

            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
            {
                return Exception("读卡失败：", errMsg);
            }
            else
            {
                // 仅有一个report映射到output节点
                string reportData = JsonHelper.getDestValue(joRtn, "output");
                if (!string.IsNullOrEmpty(reportData))
                {
                    PrintBase64Pdf(reportData);
                }
                return IrisReturn("打印成功",joRtn);
            }
        }

        public void PrintBase64Pdf(string base64Pdf)
        {
            string pdfFile = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\bill.pdf";
            byte[] bytes = Convert.FromBase64String(base64Pdf);
            try
            {
                using (PdfDocument doc = new PdfDocument())
                {
                    File.WriteAllBytes(pdfFile, bytes);
                    doc.LoadFromFile(pdfFile);

                    PrintersForm printers = new PrintersForm();
                    if (printers.ShowDialog() == DialogResult.OK)
                    {
                        PdfPrintSettings settings = new PdfPrintSettings();
                        settings.PrinterName = printers.PrinterName;
                        settings.Landscape = printers.Landscape;
                        doc.Print(settings);
                    }
                   
                }
            }
            finally
            {
                if (File.Exists(pdfFile))
                {
                    File.Delete(pdfFile);
                }
            }
        }
    }
}
