/**
 * 从 patient-item 等接口响应中解析特色方选方记录
 */
export function pickSpecialPrescriptionRecord(data) {
  if (!data || typeof data !== 'object') {
    return null;
  }
  return (
    data.special_prescription_patient_record
    || data.specialPrescriptionPatientRecord
    || null
  );
}

/**
 * 导入卡片规格文案：SKU 套餐名或单剂
 * @param record {{ sku_id?, sku_name? }|null}
 */
export function resolveSpecialPrescriptionPurchaseLabel(record) {
  if (!record) return ''
  return Number(record.sku_id) > 0
    ? (record.sku_name || 'SKU套餐')
    : '单剂'
}

/**
 * 是否已导入特色方并锁定药方编辑
 * @param page 处方页实例
 */
export function isSpecialPrescriptionCartLocked(page) {
  if (!page) return false
  return Number(page.appliedSpecialPrescriptionId) > 0
}

/** 特色方锁定提示文案 */
export const SP_CART_LOCK_MSG = '特色方药方不可修改，请先清空药方'

/**
 * 特色方锁定中则 toast 并返回 true
 * @param page 处方页实例
 */
export function guardSpecialPrescriptionCartEdit(page) {
  if (!isSpecialPrescriptionCartLocked(page)) return false
  if (page.$toast) {
    page.$toast(SP_CART_LOCK_MSG)
  } else {
    uni.showToast({ title: SP_CART_LOCK_MSG, icon: 'none' })
  }
  return true
}

/**
 * 清空「已导入特色方」状态（普通开方/常用方时调用）
 * @param page 处方页实例
 */
export function clearAppliedSpecialPrescription(page) {
  if (!page) return
  page.appliedSpecialPrescriptionId = 0
  page.appliedSpecialPrescriptionExpectedTotal = null
  page.appliedSpecialPrescriptionFreeShipping = false
}

/**
 * 将 apply 接口返回的数据写入处方页 state
 */
export function applySpecialPrescriptionPayload(page, data) {
  const categoryMap = { west: 2, chinese: 1, granular: 1 };
  const prescriptionType = data.prescription_type || 'chinese';
  page.activeCategory = categoryMap[prescriptionType] || 1;
  page.loadCurrentCategoryDrugs();
  const recipes = data.recipes || [];
  page.currentDrugs.splice(0, page.currentDrugs.length);
  recipes.forEach((recipe) => {
    const drugId = recipe.drug_id || recipe.id;
    page.currentDrugs.push(page.prepareDrugForCart({
      index_id: recipe.id,
      id: drugId,
      drug_id: drugId,
      drug_name: recipe.drug_name || recipe.name,
      number: recipe.number || 1,
      price: recipe.price || 0,
      buy_price: recipe.buy_price,
      way_id: recipe.way_id || 0,
    }));
  });
  page.chineseConfig = {
    ...page.chineseConfig,
    ruleType: data.rule_type ?? 1,
    dosage: data.dosage ?? data.dose_count ?? 7,
    dayDosage: data.day_dosage ?? 2,
    packageMethodId: data.package_method_id ?? 2,
  };
  if (data.clinical_diagnose !== undefined && data.clinical_diagnose !== null) {
    page.diagnosisText = data.clinical_diagnose;
    const names = String(data.clinical_diagnose).split('，').filter(Boolean);
    page.diagnoses = names.map((name, index) => ({ id: `temp_${index}`, name }));
  }
  if (data.doctor_order !== undefined && data.doctor_order !== null) {
    page.medicalAdvice = data.doctor_order;
  }
  page.appliedSpecialPrescriptionId = data.special_prescription_id || 0;
  page.appliedSpecialPrescriptionFreeShipping = Number(data.is_free_shipping) === 1;
  page.appliedSpecialPrescriptionExpectedTotal = data.expected_total_price != null
    ? parseFloat(data.expected_total_price)
    : null;
  page.saveToLocalStorage();
}
