import { metaData } from '@cornerstonejs/core'
// import { InstanceMetadata } from '@cornerstonejs/calculate-suv'
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
function parseImageId(imageId) {
  // build a url by parsing out the url scheme and frame index from the imageId
  const firstColonIndex = imageId.indexOf(':')

  let url = imageId.substring(firstColonIndex + 1)
  const frameIndex = url.indexOf('frame=')

  let frame

  if (frameIndex !== -1) {
    const frameStr = url.substr(frameIndex + 6)

    frame = parseInt(frameStr, 10)
    url = url.substr(0, frameIndex - 1)
  }

  return {
    scheme: imageId.substr(0, firstColonIndex),
    url,
    frame
  }
}
function getMetaData(type, imageId) {
  // const { dicomParser } = cornerstoneDICOMImageLoader.external
  const parsedImageId = parseImageId(imageId)
  const url = parsedImageId.url
  const dataSet = cornerstoneDICOMImageLoader.wadouri.dataSetCacheManager.get(url)

  if (!dataSet) {
    return
  }
  if (type === 'petImageModule') {
    // 1340137.4196974 240000
    // console.log(dataSet.string('x00541300'), dataSet.string('x00181242'))
    return {
      frameReferenceTime: dataSet.string('x00541300') || '',
      actualFrameDuration: dataSet.string('x00181242')
    }
  }
}
export default function getPTImageIdInstanceMetadata(imageId) {
  const petSequenceModule = metaData.get('petIsotopeModule', imageId)

  const generalSeriesModule = metaData.get('generalSeriesModule', imageId)
  const patientStudyModule = metaData.get('patientStudyModule', imageId)

  const ptSeriesModule = metaData.get('petSeriesModule', imageId)
  // const ptImageModule = metaData.get('petImageModule', imageId)

  const ptImageModule = getMetaData('petImageModule', imageId)
  if (!petSequenceModule) {
    throw new Error('petSequenceModule metadata is required')
  }

  const radiopharmaceuticalInfo = petSequenceModule.radiopharmaceuticalInfo

  const { seriesDate, seriesTime, acquisitionDate, acquisitionTime } =
    generalSeriesModule
  var { patientWeight } = patientStudyModule
  // console.log('更改前：', patientWeight)
  // patientWeight = patientWeight * 10
  // console.log('更改后：', patientWeight)
  const { correctedImage, units, decayCorrection } = ptSeriesModule

  if (
    seriesDate === undefined ||
    seriesTime === undefined ||
    patientWeight === undefined ||
    acquisitionDate === undefined ||
    acquisitionTime === undefined ||
    correctedImage === undefined ||
    units === undefined ||
    decayCorrection === undefined ||
    radiopharmaceuticalInfo.radionuclideTotalDose === undefined ||
    radiopharmaceuticalInfo.radionuclideHalfLife === undefined ||
    (radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime === undefined &&
      seriesDate === undefined &&
      radiopharmaceuticalInfo.radiopharmaceuticalStartTime === undefined)
    //
  ) {
    throw new Error('required metadata are missing')
  }

  const instanceMetadata = {
    CorrectedImage: correctedImage,
    Units: units,
    RadionuclideHalfLife: radiopharmaceuticalInfo.radionuclideHalfLife,
    RadionuclideTotalDose: radiopharmaceuticalInfo.radionuclideTotalDose,
    DecayCorrection: decayCorrection,
    PatientWeight: patientWeight,
    SeriesDate: seriesDate,
    SeriesTime: seriesTime,
    AcquisitionDate: acquisitionDate,
    AcquisitionTime: acquisitionTime
  }

  if (
    radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime &&
    radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime !== undefined &&
    typeof radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime === 'string'
  ) {
    instanceMetadata.RadiopharmaceuticalStartDateTime =
      radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime
  }

  if (
    radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime &&
    radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime !== undefined &&
    typeof radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime !== 'string'
  ) {
    const dateString = convertInterfaceDateToString(
      radiopharmaceuticalInfo.radiopharmaceuticalStartDateTime
    )
    instanceMetadata.RadiopharmaceuticalStartDateTime = dateString
  }

  if (
    instanceMetadata.AcquisitionDate &&
    instanceMetadata.AcquisitionDate !== undefined &&
    typeof instanceMetadata.AcquisitionDate !== 'string'
  ) {
    const dateString = convertInterfaceDateToString(
      instanceMetadata.AcquisitionDate
    )
    instanceMetadata.AcquisitionDate = dateString
  }

  if (
    instanceMetadata.SeriesDate &&
    instanceMetadata.SeriesDate !== undefined &&
    typeof instanceMetadata.SeriesDate !== 'string'
  ) {
    const dateString = convertInterfaceDateToString(
      instanceMetadata.SeriesDate
    )
    instanceMetadata.SeriesDate = dateString
  }

  if (
    radiopharmaceuticalInfo.radiopharmaceuticalStartTime &&
    radiopharmaceuticalInfo.radiopharmaceuticalStartTime !== undefined &&
    typeof radiopharmaceuticalInfo.radiopharmaceuticalStartTime === 'string'
  ) {
    instanceMetadata.RadiopharmaceuticalStartTime =
      radiopharmaceuticalInfo.radiopharmaceuticalStartTime
  }

  if (
    radiopharmaceuticalInfo.radiopharmaceuticalStartTime &&
    radiopharmaceuticalInfo.radiopharmaceuticalStartTime !== undefined &&
    typeof radiopharmaceuticalInfo.radiopharmaceuticalStartTime !== 'string'
  ) {
    const timeString = convertInterfaceTimeToString(
      radiopharmaceuticalInfo.radiopharmaceuticalStartTime
    )
    instanceMetadata.RadiopharmaceuticalStartTime = timeString
  }

  if (
    instanceMetadata.AcquisitionTime &&
    instanceMetadata.AcquisitionTime !== undefined &&
    typeof instanceMetadata.AcquisitionTime !== 'string'
  ) {
    const timeString = convertInterfaceTimeToString(
      instanceMetadata.AcquisitionTime
    )
    instanceMetadata.AcquisitionTime = timeString
  }

  if (
    instanceMetadata.SeriesTime &&
    instanceMetadata.SeriesTime !== undefined &&
    typeof instanceMetadata.SeriesTime !== 'string'
  ) {
    const timeString = convertInterfaceTimeToString(
      instanceMetadata.SeriesTime
    )
    instanceMetadata.SeriesTime = timeString
  }

  if (
    ptImageModule.frameReferenceTime &&
    ptImageModule.frameReferenceTime !== undefined
  ) {
    instanceMetadata.FrameReferenceTime = ptImageModule.frameReferenceTime
  }

  if (
    ptImageModule.actualFrameDuration &&
    ptImageModule.actualFrameDuration !== undefined
  ) {
    instanceMetadata.ActualFrameDuration = ptImageModule.actualFrameDuration
  }

  if (
    patientStudyModule.patientSex &&
    patientStudyModule.patientSex !== undefined
  ) {
    instanceMetadata.PatientSex = patientStudyModule.patientSex
  }

  if (
    patientStudyModule.patientSize &&
    patientStudyModule.patientSize !== undefined
  ) {
    instanceMetadata.PatientSize = patientStudyModule.patientSize
  }

  return instanceMetadata
}

function convertInterfaceTimeToString(time) {
  const hours = `${time.hours || '00'}`.padStart(2, '0')
  const minutes = `${time.minutes || '00'}`.padStart(2, '0')
  const seconds = `${time.seconds || '00'}`.padStart(2, '0')

  const fractionalSeconds = `${time.fractionalSeconds || '000000'}`.padEnd(
    6,
    '0'
  )

  const timeString = `${hours}${minutes}${seconds}.${fractionalSeconds}`
  return timeString
}

function convertInterfaceDateToString(date) {
  const month = `${date.month}`.padStart(2, '0')
  const day = `${date.day}`.padStart(2, '0')
  const dateString = `${date.year}${month}${day}`
  return dateString
}

export { getPTImageIdInstanceMetadata }
