<template>
  <el-dialog
    v-model="visible"
    title="处理告警"
    width="520px"
    append-to-body
    center
    class="large-screen-dialog"
  >
    <div class="handle-warning-content">
      <div class="elderly-info-section" v-if="!isReportOnly">
        <p><strong>长者姓名：</strong>{{ currentElderly?.name || '' }}</p>
      </div>
      <el-form ref="handleWarningFormRef" :model="form" label-width="120px">
        <!-- 处理方式：当为 reportOnly 模式时只显示固定文案 -->
        <el-form-item
          v-if="!isReportOnly"
          label="处理方式"
          :rules="[{ required: true, message: '请选择处理方式', trigger: 'change' }]"
        >
          <el-radio-group v-model="form.handleType" size="large">
            <el-radio label="phone">电话回访</el-radio>
            <el-radio label="report">上报告警情况</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-else label="处理方式">
          <div class="fixed-mode">上报告警情况</div>
        </el-form-item>

        <!-- 电话回访时，展示电话信息 -->
        <el-form-item v-if="form.handleType === 'phone' && !isReportOnly" label="联系电话">
          <div class="phone-block">
            <div class="phone-line">
              <span class="label">长者电话：</span>
              <a
                v-if="currentElderly?.elderPhone"
                :href="`tel:${currentElderly?.elderPhone}`"
                class="tel-link"
                >{{ currentElderly?.elderPhone }}</a
              >
              <span v-else class="muted">暂无</span>
            </div>
            <div class="phone-line">
              <span class="label">家属电话：</span>
              <a
                v-if="currentElderly?.relativePhone"
                :href="`tel:${currentElderly?.relativePhone}`"
                class="tel-link"
                >{{ currentElderly?.relativePhone }}</a
              >
              <span v-else class="muted">暂无</span>
            </div>
            <div class="tip">请拨打回访并在必要时补充上报信息。</div>
          </div>
        </el-form-item>

        <!-- 上报信息 - 电话回访和上报模式都显示 -->
        <el-form-item
          label="上报信息"
          prop="message"
          :rules="[{ required: form.handleType === 'report' || isReportOnly, message: '请输入上报信息', trigger: 'blur' }]"
        >
          <el-input
            v-model="form.message"
            type="textarea"
            :rows="4"
            :placeholder="form.handleType === 'phone' ? '选填：补充上报信息（如有需要）' : '请输入上报信息'"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="closeDialog" size="large">取消</el-button>
      <el-button type="primary" @click="submit" size="large">确认处理</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, nextTick, watch } from 'vue'

interface Elderly {
  id: number
  name: string
  elderPhone?: string
  relativePhone?: string
}

interface Props {
  visible: boolean
  currentElderly: Elderly | null
  mode?: 'default' | 'reportOnly'
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  submit: [data: any]
}>()

const handleWarningFormRef = ref()

const form = reactive({
  handleType: 'phone' as 'phone' | 'report',
  // eventType: '',
  message: ''
})

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isReportOnly = computed(() => props.mode === 'reportOnly')

// 每次打开对话框时重置表单，并根据模式设置默认处理方式
watch(
  () => props.visible,
  (val) => {
    if (val) {
      // form.eventType = ''
      form.message = '已沟通，已解决'
      form.handleType = isReportOnly.value ? 'report' : 'phone'
      nextTick(() => {
        if (handleWarningFormRef.value) {
          handleWarningFormRef.value.clearValidate()
        }
      })
    }
  }
)

const closeDialog = () => {
  visible.value = false
}

const submit = async () => {
  if (!handleWarningFormRef.value) return

  try {
    // 验证表单
    const valid = await handleWarningFormRef.value.validate()
    if (!valid) return

    emit('submit', {
      elderId: props.currentElderly?.id,
      handleType: isReportOnly.value ? 'report' : form.handleType,
      message: form.message
    })

    closeDialog()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const initForm = () => {
  form.handleType = 'phone'
  // form.eventType = ''
  form.message = ''

  nextTick(() => {
    if (handleWarningFormRef.value) {
      handleWarningFormRef.value.clearValidate()
    }
  })
}

defineExpose({
  initForm
})
</script>

<style lang="scss" scoped>
.handle-warning-content {
  .elderly-info-section {
    padding: 15px;
    margin-bottom: 20px;
    background: rgb(255 255 255 / 5%);
    border-radius: 8px;

    p {
      margin: 0;
      font-size: 16px;
      color: #fff;

      strong {
        color: #1a73e8;
      }
    }
  }

  .fixed-mode {
    color: #fff;
    font-size: 16px;
  }

  .phone-block {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .phone-line {
      display: flex;
      align-items: center;
      gap: 6px;

      .label {
        color: #cfd3dc;
      }

      .tel-link {
        color: var(--el-color-primary);
        text-decoration: none;
      }

      .muted {
        color: #909399;
      }
    }

    .tip {
      margin-top: 4px;
      font-size: 12px;
      color: #909399;
    }
  }
}
</style>
