<template>
  <div class="surgery-section">
    <div class="section-head" v-if="title || description">
      <div>
        <div class="section-title" v-if="title">{{ title }}</div>
        <div class="section-description" v-if="description">
          {{ description }}
        </div>
      </div>
    </div>

    <el-row :gutter="16">
      <el-col :xs="24" :md="12">
        <el-form-item label="手术日期">
          <el-date-picker
            v-model="form.surgeryDate"
            type="datetime"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择手术日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="手术名称">
          <el-input
            v-model="form.surgeryName"
            placeholder="例如：脑室腹腔分流术"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="主刀医生">
          <el-input
            :model-value="surgeonLabel || '请先选择归属医生'"
            disabled
            placeholder="主刀医生跟随归属医生"
          />
          <div class="field-hint">主刀医生与患者归属医生保持一致</div>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="术前测压">
          <el-input-number
            v-model="form.preOpPressure"
            :min="0"
            :controls="false"
            placeholder="可为空"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="原发病">
          <el-select
            v-model="form.primaryDisease"
            filterable
            placeholder="请选择原发病"
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryOptions.primaryDiseaseOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="脑积水类型">
          <el-select
            v-model="form.hydrocephalusTypes"
            multiple
            filterable
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择脑积水类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryOptions.hydrocephalusTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="上次分流时间">
          <el-date-picker
            v-model="form.previousShuntSurgeryDate"
            type="datetime"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DD HH:mm"
            placeholder="可为空"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="手术备注">
          <el-input
            v-model="form.notes"
            maxlength="200"
            show-word-limit
            placeholder="二次手术原因、术中特殊情况等"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="showAbandonSelector">
        <el-form-item label="弃用旧设备">
          <el-select
            v-model="form.abandonedDeviceIds"
            multiple
            clearable
            collapse-tags
            collapse-tags-tooltip
            placeholder="可选择本次手术后弃用的旧设备"
            style="width: 100%"
          >
            <el-option
              v-for="device in abandonableDevices"
              :key="device.id"
              :label="formatAbandonDeviceLabel(device)"
              :value="device.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-card shadow="never" class="block-card">
      <template #header>
        <div class="block-head">
          <div>
            <div class="block-title">术前 CT 影像/资料</div>
            <div class="block-subtitle">支持直接上传图片、视频、文件</div>
          </div>
          <el-button type="primary" plain @click="addMaterial"
            >新增资料</el-button
          >
        </div>
      </template>

      <div v-if="form.preOpMaterials.length === 0" class="empty-hint">
        暂未录入术前资料
      </div>

      <div
        v-for="(material, index) in form.preOpMaterials"
        :key="`material-${index}`"
        class="material-row"
      >
        <el-row :gutter="12">
          <el-col :xs="24" :md="5">
            <el-select
              v-model="material.type"
              placeholder="类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in MATERIAL_TYPE_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :md="5">
            <el-input v-model="material.name" placeholder="资料名称" />
          </el-col>
          <el-col :xs="24" :md="8">
            <el-input v-model="material.url" placeholder="资料地址 URL" />
          </el-col>
          <el-col :xs="24" :md="2">
            <AssetUploadButton
              button-text="上传"
              button-type="primary"
              plain
              accept="image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx"
              :hospital-id="uploadHospitalId"
              @uploaded="handleMaterialUploaded(index, $event)"
            />
          </el-col>
          <el-col :xs="24" :md="2" class="material-remove">
            <el-button
              type="danger"
              plain
              @click="removeMaterial(index)"
              :disabled="
                form.preOpMaterials.length === 1 &&
                !material.url &&
                !material.name
              "
            >
              删除
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card shadow="never" class="block-card">
      <template #header>
        <div class="block-head">
          <div>
            <div class="block-title">植入设备</div>
            <div class="block-subtitle">
              选型号后自动联动厂家和名称；支持一次手术录入多台设备
            </div>
          </div>
          <el-button
            v-if="allowDeviceStructureEdit"
            type="primary"
            @click="addDevice"
            >新增设备</el-button
          >
        </div>
      </template>

      <div
        v-for="(device, index) in form.devices"
        :key="`device-${index}`"
        class="device-card"
      >
        <div class="device-card-head">
          <div class="device-card-title">设备 {{ index + 1 }}</div>
          <el-button
            v-if="allowDeviceStructureEdit"
            type="danger"
            plain
            @click="removeDevice(index)"
            :disabled="form.devices.length <= 1"
          >
            删除设备
          </el-button>
        </div>

        <el-row :gutter="16">
          <el-col :xs="24" :md="12">
            <el-form-item label="植入物型号">
              <el-select
                v-model="device.implantCatalogId"
                filterable
                placeholder="请选择植入物型号"
                style="width: 100%"
                @change="handleCatalogChange(device)"
              >
                <el-option
                  v-for="item in catalogOptions"
                  :key="item.id"
                  :label="formatCatalogLabel(item)"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="植入物厂商">
              <el-input
                :model-value="
                  resolveCatalog(device.implantCatalogId)?.manufacturer || '-'
                "
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="植入物名称">
              <div class="catalog-name-box">
                <el-input
                  :model-value="
                    resolveCatalog(device.implantCatalogId)?.name || '-'
                  "
                  disabled
                />
                <el-tag
                  v-if="resolveCatalog(device.implantCatalogId)"
                  :type="
                    resolveCatalog(device.implantCatalogId)?.isValve === false
                      ? 'info'
                      : 'success'
                  "
                >
                  {{
                    resolveCatalog(device.implantCatalogId)?.isValve === false
                      ? '管子'
                      : '阀门'
                  }}
                </el-tag>
              </div>
              <div
                v-if="
                  resolveCatalog(device.implantCatalogId)?.isValve !== false &&
                  resolvePressureLevels(device.implantCatalogId).length
                "
                class="pressure-level-hint"
              >
                挡位：
                {{ resolvePressureLevels(device.implantCatalogId).join(' / ') }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="分流方式">
              <el-select
                v-model="device.shuntMode"
                filterable
                placeholder="请选择分流方式"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryOptions.shuntModeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="远端分流方向">
              <el-select
                v-model="device.distalShuntDirection"
                filterable
                placeholder="请选择远端方向"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryOptions.distalShuntDirectionOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="近端穿刺区域">
              <el-select
                v-model="device.proximalPunctureAreas"
                multiple
                filterable
                collapse-tags
                collapse-tags-tooltip
                :multiple-limit="2"
                placeholder="最多 2 项"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryOptions.proximalPunctureOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="resolveCatalog(device.implantCatalogId)?.isValve === true"
            :xs="24"
            :md="12"
          >
            <el-form-item label="阀门植入部位">
              <el-select
                v-model="device.valvePlacementSites"
                multiple
                filterable
                collapse-tags
                collapse-tags-tooltip
                :multiple-limit="2"
                placeholder="最多 2 项"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryOptions.valvePlacementOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="resolveCatalog(device.implantCatalogId)?.isValve === true"
            :xs="24"
            :md="12"
          >
            <el-form-item label="初始压力">
              <el-select
                v-if="resolvePressureLevels(device.implantCatalogId).length"
                v-model="device.initialPressure"
                clearable
                placeholder="请选择初始挡位"
                style="width: 100%"
              >
                <el-option
                  v-for="level in resolvePressureLevels(
                    device.implantCatalogId,
                  )"
                  :key="`${device.implantCatalogId}-initial-${level}`"
                  :label="String(level)"
                  :value="level"
                />
              </el-select>
              <div class="field-hint">
                当前压力创建后默认继承初始压力，后续以调压任务完成结果为准
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="植入物备注">
              <el-input
                v-model="device.implantNotes"
                maxlength="200"
                show-word-limit
                placeholder="记录术中情况、位置说明等"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="植入物标签">
              <div class="upload-field-row">
                <el-input
                  v-model="device.labelImageUrl"
                  placeholder="请输入图片地址 URL"
                />
                <AssetUploadButton
                  button-text="上传标签"
                  button-type="primary"
                  plain
                  accept="image/*"
                  :hospital-id="uploadHospitalId"
                  @uploaded="handleDeviceLabelUploaded(index, $event)"
                />
              </div>
              <el-image
                v-if="device.labelImageUrl"
                :src="device.labelImageUrl"
                fit="contain"
                class="label-preview"
                :preview-src-list="[device.labelImageUrl]"
                preview-teleported
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { MATERIAL_TYPE_OPTIONS } from '../patient-form-options';
import { createEmptyMedicalDictionaryOptions } from '../../../constants/medical-dictionaries';
import AssetUploadButton from '../../../components/AssetUploadButton.vue';

const props = defineProps({
  form: {
    type: Object,
    required: true,
  },
  catalogOptions: {
    type: Array,
    default: () => [],
  },
  dictionaryOptions: {
    type: Object,
    default: () => createEmptyMedicalDictionaryOptions(),
  },
  surgeonLabel: {
    type: String,
    default: '',
  },
  abandonableDevices: {
    type: Array,
    default: () => [],
  },
  showAbandonSelector: {
    type: Boolean,
    default: false,
  },
  allowDeviceStructureEdit: {
    type: Boolean,
    default: true,
  },
  title: {
    type: String,
    default: '',
  },
  description: {
    type: String,
    default: '',
  },
  uploadHospitalId: {
    type: Number,
    default: null,
  },
});

const createMaterial = () => ({
  type: 'IMAGE',
  name: '',
  url: '',
});

const createDevice = () => ({
  implantCatalogId: null,
  shuntMode: '',
  proximalPunctureAreas: [],
  valvePlacementSites: [],
  distalShuntDirection: '',
  initialPressure: '',
  implantNotes: '',
  labelImageUrl: '',
});

const addMaterial = () => {
  props.form.preOpMaterials.push(createMaterial());
};

const handleMaterialUploaded = (index, asset) => {
  const current = props.form.preOpMaterials[index];
  if (!current) {
    return;
  }
  current.type = asset.type || current.type;
  current.name = asset.originalName || current.name;
  current.url = asset.url || current.url;
};

const removeMaterial = (index) => {
  if (props.form.preOpMaterials.length === 1) {
    props.form.preOpMaterials.splice(index, 1, createMaterial());
    return;
  }
  props.form.preOpMaterials.splice(index, 1);
};

const addDevice = () => {
  props.form.devices.push(createDevice());
};

const handleDeviceLabelUploaded = (index, asset) => {
  const current = props.form.devices[index];
  if (!current) {
    return;
  }
  current.labelImageUrl = asset.url || current.labelImageUrl;
};

const removeDevice = (index) => {
  if (props.form.devices.length <= 1) {
    return;
  }
  props.form.devices.splice(index, 1);
};

const resolveCatalog = (catalogId) => {
  return props.catalogOptions.find((item) => item.id === catalogId) || null;
};

const resolvePressureLevels = (catalogId) => {
  const pressureLevels = resolveCatalog(catalogId)?.pressureLevels;
  return Array.isArray(pressureLevels) ? pressureLevels : [];
};

const formatCatalogLabel = (catalog) => {
  return `${catalog.modelCode} ｜ ${catalog.manufacturer} ｜ ${catalog.name}`;
};

const handleCatalogChange = (device) => {
  const catalog = resolveCatalog(device.implantCatalogId);
  if (catalog?.isValve === false) {
    device.valvePlacementSites = [];
    device.initialPressure = '';
    return;
  }

  if (!catalog?.isPressureAdjustable) {
    device.initialPressure = '';
    return;
  }

  const pressureLevels = resolvePressureLevels(device.implantCatalogId);
  if (pressureLevels.length === 0) {
    return;
  }

  if (!pressureLevels.includes(device.initialPressure)) {
    device.initialPressure = pressureLevels[0];
  }
};

const formatAbandonDeviceLabel = (device) => {
  const implantLabel =
    device.implantModel || device.implantName || '未命名设备';
  const placementLabel =
    Array.isArray(device.valvePlacementSites) &&
    device.valvePlacementSites.length
      ? device.valvePlacementSites.join('、')
      : '部位未录入';
  return `${implantLabel} ｜ ${placementLabel} ｜ 当前压力 ${
    device.currentPressure ?? '-'
  }`;
};
</script>

<style scoped>
.section-head {
  margin-bottom: 16px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1f2a37;
}

.section-description {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.block-card {
  margin-top: 12px;
  border-radius: 14px;
  border-color: #d9e4f3;
  background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
}

.block-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.block-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2a37;
}

.block-subtitle {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.field-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
}

.empty-hint {
  padding: 12px 0;
  color: #6b7280;
  font-size: 13px;
}

.material-row + .material-row {
  margin-top: 12px;
}

.upload-field-row {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 10px;
  align-items: center;
}

.material-remove {
  display: flex;
  justify-content: flex-end;
}

.label-preview {
  width: 180px;
  height: 120px;
  margin-top: 12px;
  border-radius: 12px;
  border: 1px solid #dbe7f5;
  display: block;
  background: #edf4fb;
}

.label-preview :deep(.el-image__inner) {
  object-fit: contain;
}

.device-card {
  padding: 16px;
  border: 1px solid #dbe7f5;
  border-radius: 14px;
  background: #fff;
}

.device-card + .device-card {
  margin-top: 16px;
}

.device-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.device-card-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2a37;
}

.catalog-name-box {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 8px;
  align-items: center;
  width: 100%;
}

.pressure-level-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .block-head,
  .device-card-head {
    flex-direction: column;
    align-items: flex-start;
  }

  .material-remove {
    justify-content: flex-start;
    margin-top: 8px;
  }

  .upload-field-row {
    grid-template-columns: 1fr;
  }
}
</style>
