<template>
  <el-dialog title="补打挂号" v-model="dialogVisible" width="900px" append-to-body destroy-on-close>
    <div v-loading="loading">
      <!-- 搜索区域 -->
      <el-form :model="searchForm" :inline="true" style="margin-bottom: 20px">
        <el-form-item label="就诊卡号：">
          <el-input
            v-model="searchForm.cardNo"
            placeholder="请输入就诊卡号"
            style="width: 240px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 挂号记录列表 -->
      <el-table
        v-if="registrationList.length > 0"
        :data="registrationList"
        border
        max-height="300"
        highlight-current-row
        @row-click="handleRowClick"
        style="margin-bottom: 20px"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="患者姓名" prop="patientName" width="120" align="center" />
        <el-table-column label="就诊卡号" prop="identifierNo" width="150" align="center">
          <template #default="scope">
            <!-- 优化就诊卡号显示，尝试多种可能的字段 -->
            {{ getCardNoDisplay(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="就诊科室" prop="organizationName" align="center" />
        <el-table-column label="医生" prop="practitionerName" width="120" align="center" />
        <el-table-column label="挂号费" prop="price" width="100" align="center">
          <template #default="scope">
            {{ (scope.row.price || scope.row.registrationFee) ? parseFloat(scope.row.price || scope.row.registrationFee).toFixed(2) + ' 元' : '0.00 元' }}
          </template>
        </el-table-column>
        <el-table-column label="诊疗费" prop="activityPrice" width="100" align="center">
          <template #default="scope">
            {{ (scope.row.activityPrice || scope.row.diagnosisFee) ? parseFloat(scope.row.activityPrice || scope.row.diagnosisFee).toFixed(2) + ' 元' : '0.00 元' }}
          </template>
        </el-table-column>
        <el-table-column label="总金额" prop="totalPrice" width="100" align="center">
          <template #default="scope">
            {{ scope.row.totalPrice ? scope.row.totalPrice.toFixed(2) + ' 元' : '0.00 元' }}
          </template>
        </el-table-column>
        <el-table-column label="挂号时间" prop="registerTime" width="180" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="!loading && registrationList.length === 0 && hasSearched" description="未找到挂号记录" />

      <!-- 补打挂号表单 -->
      <el-divider>补打信息</el-divider>
      <el-form :model="form" :rules="rules" ref="reprintFormRef" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="就诊卡号：" prop="cardNo">
              <el-input v-model="form.cardNo" placeholder="就诊卡号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="name">
              <el-input v-model="form.name" placeholder="姓名" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="就诊科室：" prop="organizationName">
              <el-input v-model="form.organizationName" placeholder="就诊科室" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生：" prop="practitionerName">
              <el-input v-model="form.practitionerName" placeholder="医生" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="挂号费：" prop="price">
              <el-input v-model="form.price" placeholder="挂号费" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="诊疗费：" prop="activityPrice">
              <el-input v-model="form.activityPrice" placeholder="诊疗费" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额：" prop="totalPrice">
              <el-input v-model="form.totalPrice" placeholder="总金额" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="就诊时间：" prop="visitTime">
              <el-date-picker
                v-model="form.visitTime"
                type="datetime"
                placeholder="就诊时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :disabled="loading || !form.cardNo">确 定</el-button>
        <el-button @click="handleCancel" :disabled="loading">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch } from 'vue';
import { getOutpatientRegistrationCurrent, getOutpatientRegistrationList, reprintRegistration } from './outpatientregistration';
import { parseTime } from '@/utils/his';
import { formatDateStr } from '@/utils/index';

const { proxy } = getCurrentInstance();

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['close']);

const dialogVisible = ref(false);
const loading = ref(false);
const hasSearched = ref(false);
const registrationList = ref([]);
const reprintFormRef = ref(null);

const searchForm = reactive({
  cardNo: '',
});

const form = reactive({
  cardNo: '',
  name: '',
  organizationName: '',
  practitionerName: '',
  price: '',
  activityPrice: '',
  totalPrice: '',
  visitTime: '',
  encounterId: '',
});

const rules = {
  cardNo: [{ required: true, message: '就诊卡号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  organizationName: [{ required: true, message: '就诊科室不能为空', trigger: 'blur' }],
  practitionerName: [{ required: true, message: '医生不能为空', trigger: 'blur' }],
};

// 监听open属性变化
watch(
  () => props.open,
  (newVal) => {
    dialogVisible.value = newVal;
    if (newVal) {
      // 打开对话框时重置表单
      resetForm();
      resetSearch();
    }
  }
);

// 监听dialogVisible变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emit('close');
  }
});

// 获取就诊卡号用于显示
function getCardNoDisplay(row) {
  // 调试信息，打印所有可能的卡号字段
  console.log('解析卡号字段:', {
    identifierNo: row.identifierNo,
    cardNo: row.cardNo,
    patientId: row.patientId,
    encounterNo: row.encounterNo,
    visitNo: row.visitNo,
    patient: row.patient ? {
      identifierNo: row.patient.identifierNo,
      cardNo: row.patient.cardNo
    } : null
  });
  
  // 尝试所有可能的卡号字段
  const cardNo = 
    row.identifierNo || 
    row.cardNo || 
    (row.patient && (row.patient.identifierNo || row.patient.cardNo)) ||
    row.encounterNo ||
    row.visitNo ||
    '-';
  
  return cardNo;
}

// 搜索挂号记录
async function handleSearch() {
  if (!searchForm.cardNo) {
    proxy.$modal.msgWarning('请输入就诊卡号');
    return;
  }
  
  loading.value = true;
  hasSearched.value = true;
  registrationList.value = [];
  
  try {
    // 简化搜索逻辑，直接使用就诊卡号作为searchKey查询
    const endDate = new Date();
    const startDate = new Date();
    startDate.setFullYear(startDate.getFullYear() - 1);
    
    const queryParams = {
      pageNo: 1,
      pageSize: 100,
      registerTimeSTime: formatDateStr(startDate, 'YYYY-MM-DD') + ' 00:00:00',
      registerTimeETime: formatDateStr(endDate, 'YYYY-MM-DD') + ' 23:59:59',
      searchKey: searchForm.cardNo // 直接使用就诊卡号作为搜索关键字
    };
    
    console.log('搜索参数:', queryParams);
    
    // 调用API查询挂号记录
    const response = await getOutpatientRegistrationCurrent(queryParams);
    
    if (response.code === 200) {
      let records = response.data.records || response.data || [];
      
      console.log('查询到的挂号记录数量:', records.length);
      
      // 记录原始数据用于调试
      if (records.length > 0) {
        console.log('查询到的记录详情:', records.map(r => ({
          id: r.id || r.encounterId,
          identifierNo: r.identifierNo,
          cardNo: r.cardNo,
          patientName: r.patientName || r.name,
          patient: r.patient
        })));
      }
      
      // 显示所有查询到的记录，不进行严格过滤
      registrationList.value = records;
      
      if (records.length === 0) {
        proxy.$modal.msgWarning('未查询到相关挂号记录，请检查就诊卡号是否正确');
      }
    } else {
      proxy.$modal.msgWarning('查询失败: ' + (response.msg || '接口返回异常'));
    }
  } catch (error) {
    console.error('查询挂号记录异常:', error);
    proxy.$modal.msgError('查询出错: ' + (error.message || '网络异常'));
  } finally {
    loading.value = false;
  }
}

// 点击表格行，自动填充表单
function handleRowClick(row) {
  console.log('点击的记录:', row);
  
  // 使用getCardNoDisplay函数获取就诊卡号，确保与表格显示一致
  const cardNo = getCardNoDisplay(row);
  form.cardNo = cardNo !== '-' ? cardNo : '';
  
  // 其他表单字段填充
  form.name = row.patientName || row.name || (row.patient ? row.patient.name : '') || '';
  form.organizationName = row.organizationName || '';
  form.practitionerName = row.practitionerName || '';
  
  // 价格相关字段
  form.price = row.price ? parseFloat(row.price).toFixed(2) : (row.registrationFee ? parseFloat(row.registrationFee).toFixed(2) : '0.00');
  form.activityPrice = row.activityPrice ? parseFloat(row.activityPrice).toFixed(2) : (row.diagnosisFee ? parseFloat(row.diagnosisFee).toFixed(2) : '0.00');
  form.totalPrice = row.totalPrice ? parseFloat(row.totalPrice).toFixed(2) : '0.00';
  
  // 就诊时间设置为当前时间
  const now = new Date();
  form.visitTime = formatDateTime(now);
  form.encounterId = row.encounterId || row.id || '';
  
  console.log('填充的表单数据:', form);
}

// 格式化日期时间
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 提交补打挂号
function handleSubmit() {
  reprintFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const submitData = {
        encounterId: form.encounterId,
        cardNo: form.cardNo,
        name: form.name,
        organizationName: form.organizationName,
        practitionerName: form.practitionerName,
        price: parseFloat(form.price),
        activityPrice: parseFloat(form.activityPrice),
        totalPrice: parseFloat(form.totalPrice),
        visitTime: form.visitTime,
      };
      reprintRegistration(submitData)
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess('补打挂号成功');
            emit('close', 'success');
            dialogVisible.value = false;
          } else {
            proxy.$modal.msgError(res.msg || '补打挂号失败');
          }
        })
        .catch((error) => {
          console.error('补打挂号失败:', error);
          proxy.$modal.msgError('补打挂号失败');
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 取消
function handleCancel() {
  dialogVisible.value = false;
}

// 重置表单
function resetForm() {
  Object.assign(form, {
    cardNo: '',
    name: '',
    organizationName: '',
    practitionerName: '',
    price: '',
    activityPrice: '',
    totalPrice: '',
    visitTime: '',
    encounterId: '',
  });
  if (reprintFormRef.value) {
    reprintFormRef.value.clearValidate();
  }
}

// 重置搜索
function resetSearch() {
  searchForm.cardNo = '';
  registrationList.value = [];
  hasSearched.value = false;
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>

