import type { QcReportVersionApi } from '#/api/mes/qc/report/version';

import { resolvePageMm } from '#/components/quality/engine/page';

/**
 * 当前 Schema 版本号，与后端 ReportTemplateSchema.SCHEMA_VERSION 必须一致
 * 1.1 删除了从未使用的 dataSources / bindings / styles，详见 version/index.ts 的契约说明
 */
export const SCHEMA_VERSION = '1.1';

/** CSS 像素与毫米的换算：1mm = 96/25.4 px */
export const MM_TO_PX = 96 / 25.4;

/** 画布上纸张的颜色，仅作视觉参考 */
export const PAPER_COLOR = '#ffffff';

/** 默认纸张配置 */
export const DEFAULT_PAGE: QcReportVersionApi.SchemaPage = {
  size: 'A4',
  orientation: 'portrait',
  margin: { top: 10, right: 10, bottom: 10, left: 10 },
};

/** 计算画布尺寸（px），按纸张方向自动翻转宽高 */
export function resolveCanvasSize(page?: QcReportVersionApi.SchemaPage): {
  height: number;
  marginPx: Required<QcReportVersionApi.SchemaMargin>;
  width: number;
} {
  const { heightMm, marginMm, widthMm } = resolvePageMm(page);
  return {
    width: Math.round(widthMm * MM_TO_PX),
    height: Math.round(heightMm * MM_TO_PX),
    marginPx: {
      top: marginMm.top * MM_TO_PX,
      right: marginMm.right * MM_TO_PX,
      bottom: marginMm.bottom * MM_TO_PX,
      left: marginMm.left * MM_TO_PX,
    },
  };
}

/** 由模板元数据推导初始 Schema（新建版本时使用） */
export function createEmptySchema(
  page?: QcReportVersionApi.SchemaPage,
): QcReportVersionApi.ReportTemplateSchema {
  return {
    schemaVersion: SCHEMA_VERSION,
    page: { ...DEFAULT_PAGE, ...page },
    grapes: {},
    components: [],
    rules: [],
  };
}