<script lang="ts" setup>
/**
 * 患者管理页面
 *
 * @description 医生名下患者管理功能
 *              - 患者列表展示
 *              - 搜索筛选功能
 *              - 查看患者详情
 *              - 群发消息功能
 * @author 系统
 * @date 2024
 */
import { ref, onMounted } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Avatar,
  Button,
  Card,
  Col,
  Empty,
  Input,
  message,
  Pagination,
  Row,
  Select,
  SelectOption,
  Spin,
  Table,
  Tag,
} from 'ant-design-vue';
import {
  ManOutlined,
  SearchOutlined,
  SendOutlined,
  UserOutlined,
  WomanOutlined,
} from '@ant-design/icons-vue';

import {
  getPatientListApi,
  type PatientItem,
  type PageResponse,
} from './api';
import PatientDetailModal from './components/PatientDetailModal.vue';
import SendMessageModal from './components/SendMessageModal.vue';

// ==================== 响应式数据 ====================

/**
 * 患者列表数据
 */
const patientList = ref<PatientItem[]>([]);

/**
 * 分页信息
 */
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

/**
 * 加载状态
 */
const loading = ref(false);

/**
 * 搜索关键字
 */
const searchName = ref('');

/**
 * 性别筛选
 */
const searchSex = ref<number | undefined>(undefined);

/**
 * 选中的患者ID列表（用于群发消息）
 */
const selectedPatientIds = ref<number[]>([]);

// ==================== Modal 配置 ====================

/**
 * 患者详情弹窗
 */
const [PatientDetailModals, PatientDetailModalApi] = useVbenModal({
  connectedComponent: PatientDetailModal,
});

/**
 * 群发消息弹窗
 */
const [SendMessageModals, SendMessageModalApi] = useVbenModal({
  connectedComponent: SendMessageModal,
});

// ==================== 方法定义 ====================

/**
 * 获取患者列表
 * @description 根据搜索条件获取患者列表
 */
async function fetchPatientList() {
  loading.value = true;
  try {
    const res = await getPatientListApi({
      name: searchName.value || undefined,
      sex: searchSex.value,
      pageSize: pagination.value.pageSize,
    });
    patientList.value = res.items || [];
    pagination.value.total = res.total || 0;
    pagination.value.current = res.page || 1;
  } catch (error) {
    console.error('获取患者列表失败:', error);
    message.error('获取患者列表失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 搜索患者
 * @description 触发搜索
 */
function handleSearch() {
  pagination.value.current = 1;
  fetchPatientList();
}

/**
 * 重置搜索条件
 */
function handleReset() {
  searchName.value = '';
  searchSex.value = undefined;
  pagination.value.current = 1;
  fetchPatientList();
}

/**
 * 分页变化
 * @param page 页码
 * @param pageSize 每页数量
 */
function handlePageChange(page: number, pageSize: number) {
  pagination.value.current = page;
  pagination.value.pageSize = pageSize;
  fetchPatientList();
}

/**
 * 打开患者详情弹窗
 * @param patient 患者信息
 */
function openPatientDetail(patient: PatientItem) {
  PatientDetailModalApi.setData({
    patientId: patient.patient_id,
    patientName: patient.patient,
  });
  PatientDetailModalApi.open();
}

/**
 * 打开群发消息弹窗
 */
function openSendMessageModal() {
  if (selectedPatientIds.value.length === 0) {
    message.warning('请先选择要发送消息的患者');
    return;
  }
  SendMessageModalApi.setData({
    patientIds: selectedPatientIds.value,
    onSuccess: () => {
      selectedPatientIds.value = [];
    },
  });
  SendMessageModalApi.open();
}

/**
 * 选择/取消选择患者
 * @param patientId 患者ID
 */
function toggleSelectPatient(patientId: number) {
  const index = selectedPatientIds.value.indexOf(patientId);
  if (index > -1) {
    selectedPatientIds.value.splice(index, 1);
  } else {
    selectedPatientIds.value.push(patientId);
  }
}

/**
 * 全选/取消全选
 */
function toggleSelectAll() {
  if (selectedPatientIds.value.length === patientList.value.length) {
    selectedPatientIds.value = [];
  } else {
    selectedPatientIds.value = patientList.value.map((p) => p.patient_id);
  }
}

/**
 * 获取性别文字
 * @param sex 性别值
 */
function getSexText(sex: number): string {
  return sex === 1 ? '男' : sex === 2 ? '女' : '未知';
}

/**
 * 获取性别颜色
 * @param sex 性别值
 */
function getSexColor(sex: number): string {
  return sex === 1 ? '#1890ff' : sex === 2 ? '#eb2f96' : '#999';
}

// ==================== 生命周期 ====================

onMounted(() => {
  fetchPatientList();
});
</script>

<template>
  <Page title="患者管理" auto-content-height>
    <!-- 搜索区域 -->
    <Card class="mb-4">
      <Row :gutter="16" align="middle">
        <Col :span="6">
          <Input
            v-model:value="searchName"
            placeholder="请输入患者姓名"
            allow-clear
            @pressEnter="handleSearch"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </Input>
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchSex"
            placeholder="选择性别"
            allow-clear
            class="w-full"
          >
            <SelectOption :value="1">男</SelectOption>
            <SelectOption :value="2">女</SelectOption>
          </Select>
        </Col>
        <Col :span="8">
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button class="ml-2" @click="handleReset">重置</Button>
        </Col>
        <Col :span="6" class="text-right">
          <Button
            type="primary"
            :disabled="selectedPatientIds.length === 0"
            @click="openSendMessageModal"
          >
            <template #icon><SendOutlined /></template>
            群发消息 ({{ selectedPatientIds.length }})
          </Button>
        </Col>
      </Row>
    </Card>

    <!-- 患者列表 -->
    <Card>
      <Spin :spinning="loading">
        <div v-if="patientList.length === 0" class="py-12 text-center">
          <Empty description="暂无患者数据" />
        </div>

        <div v-else>
          <!-- 全选操作 -->
          <div class="mb-4 flex items-center justify-between">
            <Button size="small" @click="toggleSelectAll">
              {{
                selectedPatientIds.length === patientList.length
                  ? '取消全选'
                  : '全选'
              }}
            </Button>
            <span class="text-gray-500">
              共 {{ pagination.total }} 位患者
            </span>
          </div>

          <!-- 患者卡片列表 -->
          <Row :gutter="[16, 16]">
            <Col
              v-for="patient in patientList"
              :key="patient.patient_id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="4"
            >
              <Card
                hoverable
                :class="{
                  'patient-card': true,
                  selected: selectedPatientIds.includes(patient.patient_id),
                }"
                @click="toggleSelectPatient(patient.patient_id)"
              >
                <div class="patient-card-content">
                  <!-- 头像 -->
                  <Avatar
                    :size="64"
                    :src="patient.avatar"
                    class="patient-avatar"
                  >
                    <template #icon><UserOutlined /></template>
                  </Avatar>

                  <!-- 基本信息 -->
                  <div class="patient-info">
                    <h4 class="patient-name">{{ patient.patient }}</h4>
                    <div class="patient-tags">
                      <Tag :color="getSexColor(patient.sex)">
                        <template #icon>
                          <ManOutlined v-if="patient.sex === 1" />
                          <WomanOutlined v-else-if="patient.sex === 2" />
                        </template>
                        {{ getSexText(patient.sex) }}
                      </Tag>
                      <Tag v-if="patient.age" color="blue"
                        >{{ patient.age }}岁</Tag
                      >
                    </div>
                    <p class="patient-mobile" v-if="patient.mobile">
                      {{ patient.mobile }}
                    </p>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="patient-actions" @click.stop>
                    <Button
                      type="link"
                      size="small"
                      @click="openPatientDetail(patient)"
                    >
                      查看详情
                    </Button>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>

          <!-- 分页 -->
          <div class="mt-4 text-right">
            <Pagination
              v-model:current="pagination.current"
              v-model:pageSize="pagination.pageSize"
              :total="pagination.total"
              show-size-changer
              show-quick-jumper
              @change="handlePageChange"
            />
          </div>
        </div>
      </Spin>
    </Card>

    <!-- 弹窗组件 -->
    <PatientDetailModals />
    <SendMessageModals />
  </Page>
</template>

<style lang="scss" scoped>
.patient-card {
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;

  &.selected {
    border-color: #1890ff;
    background-color: #e6f7ff;

    .dark & {
      background-color: rgba(24, 144, 255, 0.1);
    }
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.patient-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.patient-avatar {
  margin-bottom: 12px;
}

.patient-info {
  width: 100%;
}

.patient-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;

  .dark & {
    color: #e5e7eb;
  }
}

.patient-tags {
  display: flex;
  justify-content: center;
  gap: 4px;
  margin-bottom: 8px;
}

.patient-mobile {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.patient-actions {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
  width: 100%;

  .dark & {
    border-top-color: #374151;
  }
}
</style>

