import type { QualityComponentDefinition } from '../core/types';

import { cssStyle, escapeHtml } from '../core/html';
import { QUALITY_ICONS } from '../core/icons';
import { QUALITY_CATEGORY } from '../core/types';

/**
 * 单个检验项的明细块。
 * <p>
 * 取值全部来自循环变量 item，放在检验项表格的重复行里、或独立的重复容器里使用；
 * 单独拖到画布上时渲染期没有 item 上下文，会渲染成空值，这是预期行为。
 */
const LOOP_VAR = 'item';

interface FieldSpec {
  label: string;
  /** 取值表达式，'' 表示该字段只有一个值、不带标签 */
  expr: string;
  toggle: string;
}

const FIELDS: FieldSpec[] = [
  { label: '', expr: `{{${LOOP_VAR}.itemName}}`, toggle: '' },
  { label: '标准值：', expr: `{{${LOOP_VAR}.standardValue}}`, toggle: 'showStandard' },
  { label: '实测值：', expr: `{{${LOOP_VAR}.actualValue}}`, toggle: 'showActual' },
  { label: '单位：', expr: `{{${LOOP_VAR}.unit}}`, toggle: 'showUnit' },
  { label: '判定：', expr: `{{${LOOP_VAR}.resultText}}`, toggle: 'showResult' },
];

export const inspectionItemDefinition: QualityComponentDefinition = {
  type: 'InspectionItem',
  name: 'inspectionItem',
  label: '检验项明细',
  category: QUALITY_CATEGORY.INSPECTION,
  icon: QUALITY_ICONS.inspection,
  aiHint:
    '单条检验项的竖排明细卡片，用于检验项很少、不适合排成表格的场合。多行数据用 QualityTable。',
  defaults: {
    showStandard: true,
    showActual: true,
    showUnit: true,
    showResult: true,
    showBorder: true,
  },
  propertySchema: [
    { key: 'showStandard', label: '显示标准值', type: 'boolean', defaultValue: true },
    { key: 'showActual', label: '显示实测值', type: 'boolean', defaultValue: true },
    { key: 'showUnit', label: '显示单位', type: 'boolean', defaultValue: true },
    { key: 'showResult', label: '显示判定', type: 'boolean', defaultValue: true },
    { key: 'showBorder', label: '显示边框', type: 'boolean', defaultValue: true },
  ],
  dataSchema: [
    { key: `${LOOP_VAR}.itemName`, label: '检验项目名称', type: 'string', bindable: true },
    { key: `${LOOP_VAR}.standardValue`, label: '标准值', type: 'string', bindable: true },
    { key: `${LOOP_VAR}.actualValue`, label: '实测值', type: 'string', bindable: true },
    { key: `${LOOP_VAR}.unit`, label: '单位', type: 'string', bindable: true },
    { key: `${LOOP_VAR}.resultText`, label: '判定结果', type: 'string', bindable: true },
  ],
  buildContent: (properties) => {
    const visible = FIELDS.filter(
      (field) => field.toggle === '' || properties[field.toggle] !== false,
    );
    const [first, ...rest] = visible;
    const name = first
      ? `<div style="${cssStyle({ 'font-weight': 600, 'font-size': '13px' })}">${first.expr}</div>`
      : '';
    const details = rest
      .map(
        (field) =>
          `<div style="${cssStyle({ 'font-size': '12px', 'line-height': '1.8' })}">${escapeHtml(field.label)}<span>${field.expr}</span></div>`,
      )
      .join('');
    return {
      tagName: 'div',
      components: name + details,
      style: {
        margin: '0 0 6px',
        padding: '6px 8px',
        border: properties.showBorder === false ? 'none' : '1px solid #d9d9d9',
      },
    };
  },
};