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>
 * 结论与合格率来自报告上下文，由规则引擎在渲染前算好；
 * 这里只负责展示，不在组件里做任何判定计算。
 */
const CONCLUSION_EXPR = '{{report.conclusion}}';
const PASS_RATE_EXPR = '{{report.passRate}}';

export const reportResultDefinition: QualityComponentDefinition = {
  type: 'Result',
  name: 'reportResult',
  label: '判定结果',
  category: QUALITY_CATEGORY.RESULT,
  icon: QUALITY_ICONS.result,
  aiHint: '整份报告的判定结论与判定依据，放在报告末尾。',
  defaults: {
    label: '判定结论',
    conclusion: CONCLUSION_EXPR,
    showPassRate: true,
    passRateLabel: '合格率',
  },
  propertySchema: [
    { key: 'label', label: '结论标签', type: 'string', defaultValue: '判定结论' },
    {
      key: 'conclusion',
      label: '结论取值',
      type: 'string',
      defaultValue: CONCLUSION_EXPR,
      required: true,
      bindable: true,
    },
    { key: 'showPassRate', label: '显示合格率', type: 'boolean', defaultValue: true },
    { key: 'passRateLabel', label: '合格率标签', type: 'string', defaultValue: '合格率' },
  ],
  dataSchema: [
    { key: 'report.conclusion', label: '判定结论', type: 'string', bindable: true },
    { key: 'report.passRate', label: '合格率', type: 'string', bindable: true },
  ],
  buildContent: (properties) => {
    const label = escapeHtml(String(properties.label ?? '').trim());
    const conclusion = escapeHtml(String(properties.conclusion ?? '').trim());
    const conclusionLine =
      `<div style="${cssStyle({ 'font-size': '13px', 'line-height': '1.9' })}">` +
      `${label ? `${label}：<span style="font-weight:600">${conclusion}</span>` : `<span style="font-weight:600">${conclusion}</span>`}` +
      `</div>`;
    const passRateLine = properties.showPassRate
      ? `<div style="${cssStyle({ 'font-size': '12px', color: '#595959', 'line-height': '1.9' })}">` +
        `${escapeHtml(String(properties.passRateLabel ?? '').trim())}：<span>${PASS_RATE_EXPR}</span>` +
        `</div>`
      : '';
    return {
      tagName: 'div',
      components: conclusionLine + passRateLine,
      style: {
        margin: '0 0 10px',
        padding: '8px 10px',
        border: '1px solid #b7eb8f',
        background: '#f6ffed',
      },
    };
  },
};