<template>
  <scroll-view scroll-y :class="['page-scroll', elderClass]">
    <view class="page-content">
      <!-- 患者选择 -->
      <view class="section-card">
        <text class="section-title">选择患者</text>
        <view class="patient-search">
          <input
            class="search-input"
            placeholder="搜索患者姓名"
            :value="patientSearch"
            @input="(e: any) => { patientSearch = e.detail.value; searchPatients() }"
          />
        </view>
        <view v-if="searchingPatient" class="loading-hint">
          <text class="loading-hint__text">搜索中...</text>
        </view>
        <view v-else-if="patientResults.length > 0" class="patient-list">
          <view
            v-for="p in patientResults"
            :key="p.id"
            :class="['patient-item', form.patient_id === p.id ? 'patient-item--selected' : '']"
            @tap="selectPatient(p)"
          >
            <text class="patient-item__name">{{ p.name }}</text>
            <text class="patient-item__info">{{ p.gender === 'male' ? '男' : p.gender === 'female' ? '女' : '' }}</text>
            <view v-if="form.patient_id === p.id" class="patient-item__check">
              <text class="check-icon">&#10003;</text>
            </view>
          </view>
        </view>
        <view v-else-if="patientSearch && !searchingPatient" class="empty-hint">
          <text class="empty-hint__text">未找到患者</text>
        </view>
      </view>

      <!-- 透析信息 -->
      <view class="section-card">
        <text class="section-title">透析信息</text>

        <view class="form-field">
          <text class="form-label">透析日期 <text class="required">*</text></text>
          <picker mode="date" :value="form.dialysis_date" @change="(e: any) => form.dialysis_date = e.detail.value">
            <view :class="['picker-display', form.dialysis_date ? '' : 'placeholder']">
              {{ form.dialysis_date || '请选择日期' }}
            </view>
          </picker>
        </view>

        <view class="form-field">
          <text class="form-label">透析方式 <text class="required">*</text></text>
          <picker :range="dialysisTypes" :range-key="'label'" @change="(e: any) => form.dialysis_type = dialysisTypes[e.detail.value].value">
            <view :class="['picker-display', form.dialysis_type ? '' : 'placeholder']">
              {{ currentDialysisTypeLabel || '请选择透析方式' }}
            </view>
          </picker>
        </view>

        <view class="form-row">
          <view class="form-field form-field--half">
            <text class="form-label">开始时间</text>
            <picker mode="time" :value="form.start_time" @change="(e: any) => form.start_time = e.detail.value">
              <view :class="['picker-display', form.start_time ? '' : 'placeholder']">
                {{ form.start_time || '选择时间' }}
              </view>
            </picker>
          </view>
          <view class="form-field form-field--half">
            <text class="form-label">结束时间</text>
            <picker mode="time" :value="form.end_time" @change="(e: any) => form.end_time = e.detail.value">
              <view :class="['picker-display', form.end_time ? '' : 'placeholder']">
                {{ form.end_time || '选择时间' }}
              </view>
            </picker>
          </view>
        </view>
      </view>

      <!-- 体征输入 -->
      <view class="section-card">
        <text class="section-title">体征数据</text>

        <view class="form-field">
          <text class="form-label">透前体重 (kg)</text>
          <input
            type="digit"
            class="form-input"
            placeholder="请输入"
            :value="form.pre_weight ?? ''"
            @input="(e: any) => updateNumericField('pre_weight', e.detail.value)"
          />
        </view>

        <view class="form-field">
          <text class="form-label">干体重 (kg)</text>
          <input
            type="digit"
            class="form-input"
            placeholder="请输入"
            :value="form.dry_weight ?? ''"
            @input="(e: any) => updateNumericField('dry_weight', e.detail.value)"
          />
        </view>

        <view class="form-field">
          <text class="form-label">超滤目标 (ml)</text>
          <input
            type="digit"
            class="form-input"
            placeholder="请输入"
            :value="form.ultrafiltration_volume ?? ''"
            @input="(e: any) => updateNumericField('ultrafiltration_volume', e.detail.value)"
          />
        </view>

        <view class="form-row">
          <view class="form-field form-field--half">
            <text class="form-label">透前收缩压</text>
            <input
              type="digit"
              class="form-input"
              placeholder="mmHg"
              :value="form.pre_bp_systolic ?? ''"
              @input="(e: any) => updateNumericField('pre_bp_systolic', e.detail.value)"
            />
          </view>
          <view class="form-field form-field--half">
            <text class="form-label">透前舒张压</text>
            <input
              type="digit"
              class="form-input"
              placeholder="mmHg"
              :value="form.pre_bp_diastolic ?? ''"
              @input="(e: any) => updateNumericField('pre_bp_diastolic', e.detail.value)"
            />
          </view>
        </view>
      </view>

      <!-- 备注 -->
      <view class="section-card">
        <text class="section-title">备注</text>
        <textarea
          class="form-textarea"
          placeholder="并发症记录或其他备注（选填）"
          :value="form.complication_notes"
          @input="(e: any) => form.complication_notes = e.detail.value"
          :maxlength="1000"
        />
      </view>

      <!-- 提交 -->
      <view class="submit-wrap">
        <view :class="['action-btn', submitting ? 'disabled' : '']" @tap="submitting ? undefined : handleSubmit">
          <text class="action-btn-text">{{ submitting ? '提交中...' : '提交记录' }}</text>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useElderClass } from '@/composables/useElderClass'
import { createDialysisRecord } from '@/services/doctor/dialysis'
import { listPatients } from '@/services/doctor/patient'
import type { PatientItem } from '@/services/doctor/patient'

const DIALYSIS_TYPES = [
  { label: '血液透析', value: 'hemodialysis' },
  { label: '腹膜透析', value: 'peritoneal' },
] as const

const dialysisTypes = DIALYSIS_TYPES

const { elderClass } = useElderClass()

const form = reactive({
  patient_id: '',
  dialysis_date: '',
  dialysis_type: '',
  start_time: '',
  end_time: '',
  pre_weight: undefined as number | undefined,
  dry_weight: undefined as number | undefined,
  ultrafiltration_volume: undefined as number | undefined,
  pre_bp_systolic: undefined as number | undefined,
  pre_bp_diastolic: undefined as number | undefined,
  complication_notes: '',
})

const patientSearch = ref('')
const patientResults = ref<PatientItem[]>([])
const searchingPatient = ref(false)
const submitting = ref(false)

const currentDialysisTypeLabel = computed(() => {
  const found = DIALYSIS_TYPES.find((t) => t.value === form.dialysis_type)
  return found ? found.label : ''
})

let searchTimer: ReturnType<typeof setTimeout> | null = null

function searchPatients() {
  if (searchTimer) clearTimeout(searchTimer)
  if (!patientSearch.value.trim()) {
    patientResults.value = []
    return
  }
  searchTimer = setTimeout(async () => {
    searchingPatient.value = true
    try {
      const res = await listPatients({ search: patientSearch.value.trim(), page_size: 10 })
      patientResults.value = res.data || []
    } catch {
      patientResults.value = []
    } finally {
      searchingPatient.value = false
    }
  }, 300)
}

function selectPatient(p: PatientItem) {
  form.patient_id = form.patient_id === p.id ? '' : p.id
}

function updateNumericField(field: keyof typeof form, raw: string) {
  const val = raw.trim() === '' ? undefined : Number(raw)
  ;(form as any)[field] = isNaN(val as number) ? undefined : val
}

async function handleSubmit() {
  if (!form.patient_id) {
    uni.showToast({ title: '请选择患者', icon: 'none' })
    return
  }
  if (!form.dialysis_date) {
    uni.showToast({ title: '请选择透析日期', icon: 'none' })
    return
  }
  if (!form.dialysis_type) {
    uni.showToast({ title: '请选择透析方式', icon: 'none' })
    return
  }

  submitting.value = true
  try {
    await createDialysisRecord({
      patient_id: form.patient_id,
      dialysis_date: form.dialysis_date,
      dialysis_type: form.dialysis_type,
      start_time: form.start_time || undefined,
      end_time: form.end_time || undefined,
      pre_weight: form.pre_weight,
      dry_weight: form.dry_weight,
      ultrafiltration_volume: form.ultrafiltration_volume,
      pre_bp_systolic: form.pre_bp_systolic,
      pre_bp_diastolic: form.pre_bp_diastolic,
      complication_notes: form.complication_notes.trim() || undefined,
    })
    uni.showToast({ title: '创建成功', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 800)
  } catch {
    uni.showToast({ title: '创建失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.page-scroll { min-height: 100vh; background: $bg; }
.page-content { padding: 24px 0 160px; }

.section-card {
  @include card;
}

.section-title {
  font-size: var(--tk-font-body);
  font-weight: 600;
  color: $tx;
  margin-bottom: 16px;
  display: block;
}

// Search
.patient-search { margin-bottom: 12px; }

.search-input {
  height: 48px;
  border: 1px solid $bd;
  border-radius: $r-sm;
  padding: 0 16px;
  font-size: var(--tk-font-body);
  color: $tx;
  background: $card;
  box-sizing: border-box;
}

.loading-hint, .empty-hint {
  @include flex-center;
  padding: 24px 0;
}

.loading-hint__text, .empty-hint__text {
  font-size: var(--tk-font-body-sm);
  color: $tx3;
}

.patient-list {
  max-height: 320px;
  overflow-y: auto;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 16px 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
  border-radius: $r-xs;

  &:active { background: $bd-l; }

  &--selected {
    background: $pri-l;
  }

  &__name {
    flex: 1;
    font-size: var(--tk-font-body);
    color: $tx;
    font-weight: 500;
  }

  &__info {
    font-size: var(--tk-font-body-sm);
    color: $tx3;
    margin-right: 12px;
  }

  &__check {
    width: 32px;
    height: 32px;
    @include flex-center;
    background: $pri;
    border-radius: 50%;
  }
}

.check-icon {
  color: $card;
  font-size: var(--tk-font-body-sm);
}

// Form
.form-field {
  margin-bottom: 16px;
}

.form-field--half {
  flex: 1;
}

.form-row {
  display: flex;
  gap: 12px;
}

.form-label {
  display: block;
  font-size: var(--tk-font-body-sm);
  color: $tx2;
  margin-bottom: 8px;
}

.required { color: $dan; }

.form-input {
  height: 48px;
  border: 1px solid $bd;
  border-radius: $r-sm;
  padding: 0 16px;
  font-size: var(--tk-font-body);
  color: $tx;
  background: $card;
  box-sizing: border-box;
}

.picker-display {
  height: 48px;
  border: 1px solid $bd;
  border-radius: $r-sm;
  padding: 0 16px;
  font-size: var(--tk-font-body);
  color: $tx;
  background: $card;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.picker-display.placeholder {
  color: $tx3;
}

.form-textarea {
  width: 100%;
  min-height: 120px;
  border: 1px solid $bd;
  border-radius: $r-sm;
  padding: 12px;
  font-size: var(--tk-font-body);
  color: $tx;
  box-sizing: border-box;
  background: $card;
}

// Submit
.submit-wrap {
  margin: 0 24px;
}

.action-btn {
  @include btn-primary;
}

.action-btn.disabled { opacity: 0.5; }

.action-btn-text {
  color: $card;
  font-size: var(--tk-font-body-lg);
  font-weight: 600;
}
</style>
