/**
 * AI 功能门闸：拉取醒目提示 + 首次知情同意
 * 同意按 VIP 功能码隔离，签署后该功能不再弹
 */
import { h } from 'vue';

import { Modal, message } from 'ant-design-vue';

import { requestClient } from '#/api/request';

export type AiFeatureCode = 'ai_medical_record' | 'ai_prescription';

export interface AiFeatureGate {
  id: number;
  feature_code: string;
  record_label: string;
  disclaimer_text: string;
  consent_text: string;
  consented: boolean;
}

/** 拉取门闸信息 */
export async function fetchAiFeatureGate(
  featureCode: AiFeatureCode,
): Promise<AiFeatureGate> {
  const res = await requestClient.get<any>('doctor-reception/ai-feature-gate', {
    params: { feature_code: featureCode },
  });
  const data = res?.data || res || {};
  return {
    id: Number(data.id || 0),
    feature_code: String(data.feature_code || featureCode),
    record_label: String(data.record_label || ''),
    disclaimer_text: String(data.disclaimer_text || ''),
    consent_text: String(data.consent_text || ''),
    consented: !!data.consented,
  };
}

/** 签署知情同意 */
export async function agreeAiFeatureConsent(
  featureCode: AiFeatureCode,
  storeId?: number,
): Promise<void> {
  await requestClient.post<any>('doctor-reception/ai-agree-consent', {
    feature_code: featureCode,
    store_id: storeId || 0,
  });
}

/**
 * 打开 AI 功能前：未签署则弹子模态框；拒绝则返回 null
 */
export async function ensureAiFeatureConsent(options: {
  featureCode: AiFeatureCode;
  storeId?: number;
}): Promise<AiFeatureGate | null> {
  const gate = await fetchAiFeatureGate(options.featureCode);
  if (gate.consented) {
    return gate;
  }
  const ok = await new Promise<boolean>((resolve) => {
    Modal.confirm({
      title: 'AI 使用知情同意',
      width: 560,
      centered: true,
      okText: '我已知悉并同意',
      cancelText: '取消',
      content: () =>
        h(
          'div',
          {
            style: {
              whiteSpace: 'pre-wrap',
              maxHeight: '50vh',
              overflow: 'auto',
              lineHeight: '1.6',
              fontSize: '13px',
            },
          },
          gate.consent_text || '请先阅读并同意 AI 使用规范',
        ),
      onOk: async () => {
        try {
          await agreeAiFeatureConsent(options.featureCode, options.storeId);
          message.success('已记录知情同意');
          resolve(true);
        } catch (e: any) {
          message.error(e?.message || e?.msg || '签署失败');
          resolve(false);
          return Promise.reject(e);
        }
      },
      onCancel: () => resolve(false),
    });
  });
  if (!ok) {
    return null;
  }
  return { ...gate, consented: true };
}
