<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="查询内容" prop="searchKey">
        <el-input
          v-model="queryParams.searchKey"
          placeholder="姓名/身份证号/病人ID/门诊号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          style="width: 150px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="起始时间">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="性别" prop="genderEnum">
        <el-select
          v-model="queryParams.genderEnum"
          placeholder="请选择性别"
          clearable
          style="width: 100px"
        >
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
          <el-option label="未知" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="subjectStatusEnum">
        <el-select
          v-model="queryParams.subjectStatusEnum"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="已到达" :value="1" />
          <el-option label="已分诊" :value="2" />
          <el-option label="已看诊" :value="3" />
          <el-option label="已离开" :value="4" />
          <el-option label="已完成" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="医生" prop="doctorName">
        <el-select
          v-model="queryParams.doctorName"
          placeholder="请选择医生"
          clearable
          style="width: 160px"
        >
          <el-option
            v-for="item in doctorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table 
      :data="outpatienRecordsList" 
      border 
      style="width: 100%"
      :default-sort="{ prop: 'encounterTime', order: 'descending' }"
      v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
    >
      <el-table-column prop="name" label="患者" min-width="100" />
      <el-table-column prop="genderEnum_enumText" label="性别" width="80" align="center" />
      <el-table-column prop="idCard" label="身份证" min-width="160" :show-overflow-tooltip="true" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="patientBusNo" label="病人ID" width="100" align="center" />
      <el-table-column prop="encounterBusNo" label="门诊号" width="120" align="center" />
      <el-table-column prop="encounterTime" label="就诊时间" width="160" sortable />
      <el-table-column prop="doctorName" label="接诊医生" width="120" />
      <el-table-column prop="organizationName" label="医疗机构" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column prop="subjectStatusEnum_enumText" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag 
            :type="getStatusTagType(scope.row.subjectStatusEnum)" 
            size="small"
          >
            {{ scope.row.subjectStatusEnum_enumText }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 移除疾病描述列，因为当前数据中没有这个字段 -->
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="outpatienRecords">
import {computed, ref, reactive, toRefs, getCurrentInstance} from 'vue';
import {listDoctorNames, listOutpatienRecords} from './component/api';
import { useRoute } from 'vue-router';

const showSearch = ref(true);
const total = ref(0);
const dateRange = ref([]);
const outpatienRecordsList = ref([]);
const doctorList = ref([]);
const loading = ref(false);

const { proxy } = getCurrentInstance();
const route = useRoute();

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    doctorName: undefined,
    searchKey: undefined,
    phone: undefined,
    genderEnum: undefined,
    subjectStatusEnum: undefined,
  },
});
const { queryParams } = toRefs(data);

const doctorOptions = computed(() => {
  return doctorList.value.map((name, index) => ({
    value: index, // 使用索引作为 value
    label: name, // 使用名字作为 label
  }));
});

/** 查询门诊记录列表 */
function getList() {
  loading.value = true;
  // 如果路由中有患者ID参数，则自动填充到查询条件中
  if (route.query.patientId) {
    queryParams.value.searchKey = route.query.patientId;
  }
  if (route.query.patientName) {
    // 可以在页面标题或其他地方显示患者姓名
    console.log('当前查看患者:', route.query.patientName);
  }

  listOutpatienRecords(queryParams.value).then((response) => {
    outpatienRecordsList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
  
  // 只在医生列表为空时加载医生列表
  if (doctorList.value.length === 0) {
    listDoctorNames().then((response) => {
      doctorList.value = response.data;
    });
  }
}

/** 根据状态获取标签类型 */
function getStatusTagType(status) {
  // 状态值对应后端 EncounterSubjectStatus 枚举：1-已到达，2-已分诊，3-已看诊，4-已离开，5-已完成
  switch (status) {
    case 1:
      return 'warning'; // 已到达 - 黄色
    case 2:
      return 'primary'; // 已分诊 - 蓝色
    case 3:
      return 'success'; // 已看诊 - 绿色
    case 4:
      return 'info'; // 已离开 - 灰色
    case 5:
      return 'success'; // 已完成 - 绿色
    default:
      return '';
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  // 处理时间范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTimeSTime = dateRange.value[0];
    queryParams.value.startTimeETime = dateRange.value[1];
  } else {
    queryParams.value.startTimeSTime = '';
    queryParams.value.startTimeETime = '';
  }
  
  queryParams.value.pageNo = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm('queryRef');
  handleQuery();
}

getList();
</script>
