using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Imaging;

public class PrinterManager : MonoBehaviour
{
  public static PrinterManager Instance;

  [SerializeField] private PrinterSetting ps = new PrinterSetting();

  // ==================================================

  private void Awake() => Instance = this;
  private void Start() => Init();

  // ==================================================

  private void Init()
  {
    SetPrinterName("L805");
  }

  // ==================================================

  /// <summary>
  /// 设置打印机名称所包含的关键词
  /// </summary>
  /// <param name="keyword"></param>
  public void SetPrinterName(string keyword)
  {
    foreach (string item in PrinterSettings.InstalledPrinters)
    {
      if (item.Contains(keyword))
      {
        ps.printerName = item;
        return;
      }
    }

    ps.printerName = new PrinterSettings().PrinterName; // 如果没有找到，使用默认打印机
  }

  // ==================================================

  /// <summary>
  /// 打印
  /// </summary>
  /// <param name="texture"></param>
  public void Print(Texture2D texture)
  {
    if (!Application.isEditor && Application.platform != RuntimePlatform.WindowsPlayer)
    {
      Debug.LogWarning("[PM] 打印功能仅支持Windows平台");
      return;
    }

    try
    {
      using (Bitmap bitmap = T2D2BitmapSafe(texture))
      {
        PrintBitmap(bitmap);
      }
    }
    catch (Exception e)
    {
      Debug.LogError("[PM] 打印失败: " + e.Message);
    }
  }



  /// <summary>
  /// 将Texture2D转换为Bitmap
  /// </summary>
  /// <param name="texture"></param>
  /// <returns></returns>
  private Bitmap T2D2BitmapSafe(Texture2D texture)
  {
    // 方法1：使用逐像素复制（更稳定但稍慢）
    Bitmap bitmap = new Bitmap(texture.width, texture.height, PixelFormat.Format32bppArgb);
    // 锁定Bitmap数据
    BitmapData bitmapData = bitmap.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.WriteOnly,
        bitmap.PixelFormat);

    try
    {
      Color32[] pixels = texture.GetPixels32(); // 获取Texture2D的像素数据

      // 将Color32[]转换为byte[]
      byte[] bytes = new byte[pixels.Length * 4];
      for (int i = 0; i < pixels.Length; i++)
      {
        bytes[i * 4] = pixels[i].b;     // Blue
        bytes[i * 4 + 1] = pixels[i].g; // Green
        bytes[i * 4 + 2] = pixels[i].r; // Red
        bytes[i * 4 + 3] = pixels[i].a; // Alpha
      }

      // 复制到Bitmap
      System.Runtime.InteropServices.Marshal.Copy(bytes, 0, bitmapData.Scan0, bytes.Length);
    }
    finally
    {
      bitmap.UnlockBits(bitmapData);
    }

    return bitmap;
  }



  /// <summary>
  /// 打印Bitmap
  /// </summary>
  /// <param name="bitmap"></param>
  private void PrintBitmap(Bitmap bitmap)
  {
    using (PrintDocument pd = new PrintDocument())
    {
      pd.PrinterSettings.PrinterName = ps.printerName; // 设置打印机

      // 创建6寸照片纸张大小（4x6英寸，100dpi）
      PaperSize photoSize = new PaperSize(ps.paperSizeName, ps.width, ps.height);
      pd.DefaultPageSettings.PaperSize = photoSize;
      pd.DefaultPageSettings.Landscape = false; // 纵向打印

      pd.PrintPage += (sender, args) =>
      {
        try
        {
          // 计算适合打印区域的尺寸
          Rectangle printArea = args.MarginBounds;

          // 保持宽高比
          float ratio = Mathf.Min(
            (float)printArea.Width / bitmap.Width,
            (float)printArea.Height / bitmap.Height);

          int newWidth = (int)(bitmap.Width * ratio);
          int newHeight = (int)(bitmap.Height * ratio);

          // 居中显示
          int x = printArea.Left + (printArea.Width - newWidth) / 2;
          int y = printArea.Top + (printArea.Height - newHeight) / 2;

          args.Graphics.DrawImage(bitmap, x, y, newWidth, newHeight);
        }
        catch (Exception e)
        {
          Debug.LogError("[PM] 绘制图像时出错: " + e.Message);
          args.Cancel = true;
        }
      };

      try
      {
        pd.Print();
        Debug.Log("[PM] 打印任务已发送");
      }
      catch (Exception e)
      {
        Debug.LogError("[PM] 打印过程中出错: " + e.Message);
      }
    }
  }

  // ==================================================

  [Serializable]
  public class PrinterSetting
  {
    public string printerName = "L805";
    public string paperSizeName = "6x4 Photo";
    public int width = 400; // mm
    public int height = 600; // mm
  }
}