<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@iconify/vue'
import { healthMetricApi } from '@/api/care.js'
import { customerApi } from '@/api/crm.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const customers = ref([])

const searchForm = reactive({ customer_id: '', metric_type: '', date_from: '', date_to: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  customer_id: '', metric_type: '', value: '', unit: '', recorded_at: '', note: ''
})

const metricTypeMap = {
  blood_pressure: '血压',
  weight: '体重',
  temperature: '体温',
  heart_rate: '心率',
  blood_sugar: '血糖',
  lochia: '恶露',
  fundus: '宫底高度',
  other: '其他'
}

const metricUnitMap = {
  blood_pressure: 'mmHg',
  weight: 'kg',
  temperature: '°C',
  heart_rate: '次/分',
  blood_sugar: 'mmol/L',
  lochia: '',
  fundus: 'cm',
  other: ''
}

const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  metric_type: [{ required: true, message: '请选择指标类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入指标值', trigger: 'blur' }],
  recorded_at: [{ required: true, message: '请选择记录时间', trigger: 'change' }]
}

function onMetricTypeChange(type) {
  form.unit = metricUnitMap[type] || ''
}

async function fetchList() {
  loading.value = true
  try {
    const res = await healthMetricApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } catch {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

async function fetchCustomers() {
  try {
    const res = await customerApi.getList({ per_page: 500, status: 3 })
    customers.value = res.data?.list || res.data?.data || []
  } catch {}
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { customer_id: '', metric_type: '', date_from: '', date_to: '' })
  handleSearch()
}

function handleAdd() {
  Object.assign(form, { customer_id: '', metric_type: '', value: '', unit: '', recorded_at: '', note: '' })
  dialogVisible.value = true
}

// healthMetricApi 后端无 DELETE 路由，删除仅本地移除
function handleDelete(row) {
  ElMessageBox.confirm(`确定删除该健康指标记录吗？`, '删除确认', { type: 'warning' }).then(() => {
    tableData.value = tableData.value.filter(r => r.id !== row.id)
    ElMessage.success('已移除')
  }).catch(() => {})
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await healthMetricApi.create(form)
      ElMessage.success('记录成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchCustomers() })
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- 搜索栏 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.customer_id" placeholder="选择客户" clearable filterable style="width:180px">
        <el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" />
      </el-select>
      <el-select v-model="searchForm.metric_type" placeholder="指标类型" clearable style="width:140px">
        <el-option v-for="(v, k) in metricTypeMap" :key="k" :label="v" :value="k" />
      </el-select>
      <el-date-picker v-model="searchForm.date_from" type="date" value-format="YYYY-MM-DD" placeholder="开始日期" style="width:150px" />
      <el-date-picker v-model="searchForm.date_to" type="date" value-format="YYYY-MM-DD" placeholder="结束日期" style="width:150px" />
      <el-button type="primary" @click="handleSearch">
        <Icon icon="solar:magnifer-bold-duotone" class="mr-1" />查询
      </el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 表格区 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-2">
          <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <span class="font-semibold text-gray-700">健康指标记录</span>
        </div>
        <el-button type="primary" @click="handleAdd">
          <Icon icon="solar:add-circle-bold-duotone" class="mr-1" />新增记录
        </el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="客户" min-width="100">
            <template #default="{ row }">{{ row.customer_name || '-' }}</template>
          </el-table-column>
          <el-table-column label="指标类型" width="110" align="center">
            <template #default="{ row }">{{ metricTypeMap[row.metric_type] || row.metric_type || '-' }}</template>
          </el-table-column>
          <el-table-column label="指标值" width="130" align="center">
            <template #default="{ row }">
              <span class="font-medium text-rose-600">{{ row.value }}</span>
              <span class="text-xs text-gray-400 ml-1">{{ row.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注" min-width="160" show-overflow-tooltip />
          <el-table-column prop="created_by_name" label="记录人" width="100" />
          <el-table-column prop="recorded_at" label="记录时间" min-width="160" />
          <el-table-column label="操作" width="80" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total,sizes,prev,pager,next,jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增健康指标" width="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="客户" prop="customer_id">
          <el-select v-model="form.customer_id" filterable style="width:100%" placeholder="请选择客户">
            <el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="指标类型" prop="metric_type">
          <el-select v-model="form.metric_type" style="width:100%" @change="onMetricTypeChange">
            <el-option v-for="(v, k) in metricTypeMap" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
        <el-form-item label="指标值" prop="value">
          <el-input v-model="form.value" placeholder="请输入数值" style="width:100%">
            <template #append>{{ form.unit || '单位' }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="记录时间" prop="recorded_at">
          <el-date-picker
            v-model="form.recorded_at"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择记录时间"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.note" type="textarea" :rows="2" placeholder="补充说明（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
