/** 畜牧资源详情展示辅助（对接 GET /app/livestockResource/{id}?type=1|2） */

const CONSULT_MODE_KEYS = {
  1: 'consultMode1',
  2: 'consultMode2',
  3: 'consultMode3'
}

const ORG_LEVEL_KEYS = {
  1: 'orgLevel1',
  2: 'orgLevel2'
}

function isEmpty(val) {
  if (val == null) return true
  if (typeof val === 'string') return val.trim() === ''
  if (Array.isArray(val)) return !val.length
  return false
}

function pickText(val) {
  if (val == null) return ''
  return String(val).trim()
}

export function formatPublishTime(val) {
  const s = pickText(val)
  if (!s) return ''
  return s.length >= 10 ? s.slice(0, 10) : s
}

export function formatWeekdays(raw, list, t) {
  let days = []
  if (Array.isArray(list) && list.length) {
    days = list.map((n) => parseInt(n, 10)).filter((n) => n >= 1 && n <= 7)
  } else if (!isEmpty(raw)) {
    days = String(raw)
      .split(',')
      .map((s) => parseInt(s.trim(), 10))
      .filter((n) => n >= 1 && n <= 7)
  }
  if (!days.length) return ''
  return days.map((n) => t(`livestockResourceDetailPage.weekday.${n}`)).join('、')
}

export function formatConsultModes(raw, list, t) {
  let modes = []
  if (Array.isArray(list) && list.length) {
    modes = list.map((n) => parseInt(n, 10))
  } else if (!isEmpty(raw)) {
    modes = String(raw)
      .split(',')
      .map((s) => parseInt(s.trim(), 10))
      .filter((n) => n >= 1 && n <= 3)
  }
  if (!modes.length) return ''
  return modes
    .map((n) => {
      const key = CONSULT_MODE_KEYS[n]
      return key ? t(`livestockResourceDetailPage.${key}`) : String(n)
    })
    .join('、')
}

function formatMoney(val) {
  if (val == null || val === '') return ''
  const n = Number(val)
  if (Number.isNaN(n)) return pickText(val)
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 })
}

function formatServiceHours(start, end) {
  const s = pickText(start)
  const e = pickText(end)
  if (s && e) return `${s} - ${e}`
  return s || e || ''
}

function pushRow(rows, label, value) {
  const v = pickText(value)
  if (!v) return
  rows.push({ label, value: v })
}

/**
 * @param {object} d 详情 data
 * @param {number} sourceType 1 医疗 / 2 科技
 * @param {(key:string)=>string} t i18n
 */
export function buildLivestockDetailRows(d, sourceType, t) {
  if (!d) return []
  const rows = []
  const rt = pickText(d.resourceType)
  const prefix = 'livestockResourceDetailPage'

  if (sourceType === 1) {
    pushRow(rows, t(`${prefix}.affiliatedUnit`), d.affiliatedUnit)
    pushRow(rows, t(`${prefix}.detailAddress`), d.detailAddress)
    pushRow(rows, t(`${prefix}.contactPhone`), d.contactPhone)
    pushRow(rows, t(`${prefix}.personInCharge`), d.personInCharge)
    pushRow(rows, t(`${prefix}.teamSize`), d.teamSize != null ? String(d.teamSize) : '')
    pushRow(rows, t(`${prefix}.teamMembers`), d.teamMembers)
    if (d.establishDate) {
      pushRow(rows, t(`${prefix}.establishDate`), formatPublishTime(d.establishDate))
    }
    pushRow(rows, t(`${prefix}.serviceArea`), d.serviceArea)
    pushRow(rows, t(`${prefix}.consultModes`), formatConsultModes(d.consultModes, d.consultModesList, t))
    if (d.feeStandard != null && d.feeStandard !== '') {
      pushRow(rows, t(`${prefix}.feeStandard`), `${formatMoney(d.feeStandard)} ${t(`${prefix}.feeUnit`)}`)
    }
    pushRow(rows, t(`${prefix}.serviceHours`), formatServiceHours(d.serviceStartTime, d.serviceEndTime))
    pushRow(rows, t(`${prefix}.serviceWeekdays`), formatWeekdays(d.serviceWeekdays, d.serviceWeekdaysList, t))
    if (d.orgLevel != null && ORG_LEVEL_KEYS[d.orgLevel]) {
      pushRow(rows, t(`${prefix}.orgLevel`), t(`${prefix}.${ORG_LEVEL_KEYS[d.orgLevel]}`))
    }
    pushRow(rows, t(`${prefix}.equipmentModel`), d.equipmentModel)
    return rows
  }

  pushRow(rows, t(`${prefix}.affiliatedUnit`), d.affiliatedUnit)
  pushRow(rows, t(`${prefix}.completionUnit`), d.completionUnit)
  pushRow(rows, t(`${prefix}.contactPhone`), d.contactPhone)
  pushRow(rows, t(`${prefix}.personInCharge`), d.personInCharge)
  pushRow(rows, t(`${prefix}.detailAddress`), d.detailAddress)
  pushRow(rows, t(`${prefix}.serviceArea`), d.serviceArea)

  if (rt === '004006') {
    pushRow(rows, t(`${prefix}.achievementSummary`), d.achievementSummary)
    pushRow(rows, t(`${prefix}.keyTechPrinciple`), d.keyTechPrinciple)
    pushRow(rows, t(`${prefix}.techAdvantage`), d.techAdvantage)
    pushRow(rows, t(`${prefix}.researchDirection`), d.researchDirection)
  }

  if (rt === '004007') {
    pushRow(rows, t(`${prefix}.instrumentModel`), d.instrumentModel)
    pushRow(rows, t(`${prefix}.storageLocation`), d.storageLocation)
    pushRow(rows, t(`${prefix}.reservationProcess`), d.reservationProcess)
    if (d.borrowFee != null && d.borrowFee !== '') {
      pushRow(rows, t(`${prefix}.borrowFee`), `${formatMoney(d.borrowFee)} ${t(`${prefix}.feeUnit`)}`)
    }
    if (d.feeStandard != null && d.feeStandard !== '') {
      pushRow(rows, t(`${prefix}.feeStandard`), `${formatMoney(d.feeStandard)} ${t(`${prefix}.feeUnit`)}`)
    }
    pushRow(rows, t(`${prefix}.serviceHours`), formatServiceHours(d.serviceStartTime, d.serviceEndTime))
    pushRow(rows, t(`${prefix}.serviceWeekdays`), formatWeekdays(d.serviceWeekdays, d.serviceWeekdaysList, t))
  }

  if (rt === '004008') {
    pushRow(rows, t(`${prefix}.courseTopic`), d.courseTopic)
  }

  return rows
}

export function resolveDetailCover(d, sourceType) {
  if (!d) return ''
  if (sourceType === 1) {
    return pickText(d.photoFileUrl)
  }
  return pickText(d.coverFileUrl) || pickText(d.photoFileUrl)
}

export function resolveDetailVideo(d) {
  return pickText(d && d.videoFileUrl)
}
