import { setTemItem } from "./temObjs";
import { router } from "@/router";

/** WebOffice 支持的文档扩展名（阿里云 IMM） */
export const WEB_OFFICE_EXTENSIONS = ['pdf', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'] as const;

/**
 * 判断资源是否可由 WebOffice 预览（与 WebOffice 对接）
 * @param resource 资源对象，需包含 fileType/type、filePath
 */
export function isWebOfficeSupported(resource: { fileType?: string; type?: string; filePath?: string }): boolean {
  const fileType = resource.fileType ?? resource.type;
  if (fileType === 'PDF') return true;
  if (fileType === 'PPT') return true;
  if (fileType === 'OTHER' && resource.filePath) {
    const ext = resource.filePath.toLowerCase().split('.').pop()?.split('?')[0] || '';
    return (WEB_OFFICE_EXTENSIONS as readonly string[]).includes(ext);
  }
  return false;
}

/**
 * @param res obj
 * @param isEdit 是否编辑
 * @param type 1.公共空间 2.个人空间 3.资源库 4.活动素材
 * @returns
 */
export function openWebOffice(res: any) {
  if (!res.url) {
    return;
  }
  const query: any = {
    _t: setTemItem({
      id: res.id,
      url: encodeURIComponent(res.url),
      name: `${res.name}.${res.type}`,
      isEdit: false,
    }),
  };
  let routeUrl = router.resolve({
    path: "/office/WebOffice",
    query: query,
  });
  window.open(routeUrl.href, "_blank");
}

export async function insertWordImage(instance, imageUrl) {
  // 获取当前激活的应用
  const app = instance.Application;
  // 检查是否为支持插入图片的应用类型
  if (app && app.ActiveDocument) {
    try {
      const _imageUrl = false
        ? `${imageUrl}?x-oss-process=image/resize,w_1080`
        : imageUrl;
      const base64String: any = await urlToBase64(_imageUrl);
      const img = await getImgSize(base64String, "doc");
      const obj = {
        FileName: base64String,
        // FileName: _imageUrl,
        LinkToFile: true,
        SaveWithDocument: true,
        ...img,
      };
      console.log("obj", obj);
      await app.ActiveDocument.Shapes.AddPicture(obj);

      console.log("图片插入成功");
    } catch (error) {
      console.error("ActiveDocument图片插入失败:", error);
    }
  } else {
    console.warn("当前没有活动的文档可以插入图片");
  }
}
export async function insertExcelImage(instance, imageUrl) {
  const app = instance.Application;

  if (app && app.ActiveWorkbook) {
    try {
      const activeSheet = await app.ActiveWorkbook.ActiveSheet;
      const shapes = await activeSheet.Shapes;

      const base64String: any = await urlToBase64(imageUrl);
      await shapes.AddPicture({
        // FileName: imageUrl,
        FileName: base64String,
        LinkToFile: -1,
        SaveWithDocument: 0,
        Left: 0.2, // 图片左边缘距离幻灯片左边缘 10%
        Top: 0.2, // 图片上边缘距离幻灯片上边缘 10%
        Width: 0.6, // 图片宽度为幻灯片宽度的 50%
        Height: 0.6, // 图片高度为幻灯片高度的 30%
        Scale: true, // 按幻灯片比例计算宽高和坐标
      });

      console.log("图片插入成功");
    } catch (error) {
      console.error("insertExcelImage图片插入失败:", error);
    }
  } else {
    console.warn("当前没有活动的工作表可以插入图片");
  }
}

export async function insertPPTImage(instance, imageUrl) {
  // 确保WebOffice实例已经准备好
  await instance.ready();
  const app = instance.Application;

  if (app && app.ActivePresentation) {
    try {
      const slide = await app.ActivePresentation.SlideShowWindow.View.Slide;
      const shapes = await slide.Shapes;
      const base64String: any = await urlToBase64(imageUrl);
      const img = await getImgSize(base64String, "ppt");

      const _res = await shapes.AddPicture({
        // FileName: imageUrl,
        FileName: base64String,

        LinkToFile: -1, // 链接到文件
        SaveWithDocument: 0, // 不随文档保存
        ...img,
      });

      console.log("图片插入成功", _res);
    } catch (error) {
      console.error("图片插入失败:", error);
    }
  } else {
    console.warn("当前没有活动的幻灯片可以插入图片");
  }
}
async function urlToBase64(url) {
  return new Promise((resolve, reject) => {
    fetch(url)
      .then((response) => response.blob()) // 获取Blob
      .then((blob) => {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onloadend = () => resolve(reader.result);
          reader.onerror = reject;
          reader.readAsDataURL(blob); // 读取为Data URL，即Base64编码
        });
      })
      .then((base64String: string) => {
        resolve(base64String);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
function getImgSize(url: string, type: string) {
  let image = new Image();
  image.src = url;
  return new Promise<{
    Left: number;
    Top: number;
    Width: number;
    Height: number;
    Scale?: boolean;
  }>((resolve, reject) => {
    image.onload = () => {
      const size = type === "ppt" ? getPPTSize(image) : getDOCSize(image);
      resolve({
        ...size,
      });
    };
    image.onerror = () => {
      reject(null);
    };
  });
}
function getPPTSize(image: HTMLImageElement) {
  const width = 1280 * 0.8; //600
  const height = 720 * 0.8; //360
  const isH = image.width <= image.height; // false
  const _r = isH ? image.width / image.height : image.height / image.width; // 0.5625
  const _rw = isH ? (_r * 0.8 * height) / width : 0.8;
  const _rh = isH ? 0.8 : (_r * 0.8 * width) / height;
  /**
   * 按幻灯片比例计算宽高和坐标 ,
   */
  return {
    Scale: true,
    Left: isH ? (1 - _rw) / 2 : 0.1,
    Top: isH ? 0.1 : (1 - _rh) / 2,
    Width: _rw,
    Height: _rh,
  };
}
function getDOCSize(image: HTMLImageElement) {
  //796,1125
  const rw = 400 / image.width;
  const rh = 400 / image.height;
  const r = rw < rh ? rw : rh;
  return {
    Left: 50, // 图片距离左边位置
    Top: 100, // 图片距离顶部位置
    Width: Math.ceil(image.width * r), // 图片宽度
    Height: Math.ceil(image.height * r), // 图片高度
    // Width: image.width * r, // 图片宽度
    // Height: image.height * r, // 图片高度
  };
}
export const imgstr =
  "data:image/png;base64,[encoded data, 8784 characters]";
