<template>
  <div>
    <h1>线上问诊</h1>
    
    <!-- 搜索和操作栏 -->
    <a-card style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <a-input v-model:value="searchKeyword" placeholder="输入关键词搜索问诊记录或医生" style="width: 300px;">
          <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
        </a-input>
        
        <a-select v-model:value="statusFilter" placeholder="问诊状态" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="pending">待接诊</a-select-option>
          <a-select-option value="ongoing">问诊中</a-select-option>
          <a-select-option value="completed">已完成</a-select-option>
          <a-select-option value="canceled">已取消</a-select-option>
        </a-select>
        
        <a-select v-model:value="doctorFilter" placeholder="选择医生" style="width: 150px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="doctor in doctors" :key="doctor.id" :value="doctor.id">
            {{ doctor.name }}
          </a-select-option>
        </a-select>
        
        <a-range-picker v-model:value="dateRange" style="width: 300px;" />
        
        <a-button type="primary" @click="handleSearch" style="margin-left: auto;">
          <span class="iconfont icon-sousuo"></span> 搜索
        </a-button>
        
        <a-button type="default" @click="handleReset">重置</a-button>
        
        <a-button type="primary" @click="handleCreateConsultation">
          <span class="iconfont icon-xinzeng"></span> 发起问诊
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据统计卡片 -->
    <a-row gutter={24} style="margin-bottom: 16px;">
      <a-col :span="6">
        <a-statistic title="总问诊量" :value="totalConsultations" suffix="次" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="今日问诊" :value="todayConsultations" suffix="次" :valueStyle="{ color: '#1890ff' }" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="待处理" :value="pendingConsultations" suffix="次" :valueStyle="{ color: '#faad14' }" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="已完成" :value="completedConsultations" suffix="次" :valueStyle="{ color: '#52c41a' }" />
      </a-col>
    </a-row>
    
    <!-- 问诊类型分布图 -->
    <a-card title="问诊类型分布" style="margin-bottom: 16px;">
      <div style="height: 300px;" ref="typeChartRef"></div>
    </a-card>
    
    <!-- 在线医生列表 -->
    <a-card title="在线医生" style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px;">
        <div v-for="doctor in onlineDoctors" :key="doctor.id" class="doctor-card">
          <div class="doctor-avatar">
            <img :src="doctor.avatar" alt="{{ doctor.name }}" />
          </div>
          <div class="doctor-info">
            <div class="doctor-name">{{ doctor.name }}</div>
            <div class="doctor-title">{{ doctor.title }}</div>
            <div class="doctor-department">{{ doctor.department }}</div>
            <div class="doctor-stats">
              <span>接诊量: {{ doctor.consultCount }}次</span>
              <span>满意度: {{ doctor.satisfaction }}%</span>
            </div>
            <a-button type="primary" size="small" @click="handleConsultDoctor(doctor.id)">立即咨询</a-button>
          </div>
        </div>
      </div>
    </a-card>
    
    <!-- 问诊记录列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="consultationList"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
       :scroll="{ x: 'max-content' }"
      >
        <!-- 状态列 -->
        <template #bodyCell:status="{ record }">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </template>
        
        <!-- 优先级列 -->
        <template #bodyCell:priority="{ record }">
          <a-tag :color="getPriorityColor(record.priority)">{{ getPriorityText(record.priority) }}</a-tag>
        </template>
        
        <!-- 医生列 -->
        <template #bodyCell:doctor="{ record }">
          {{ record.doctorName || '-' }}
        </template>
        
        <!-- 操作列 -->
        <template #bodyCell:action="{ record }">
          <div style="display: flex; gap: 8px;">
            <a-button size="small" @click="handleViewConsultation(record)">查看详情</a-button>
            <a-button size="small" type="primary" @click="handleSendMessage(record.id)" v-if="record.status === 'ongoing'">发送消息</a-button>
            <a-button size="small" danger @click="handleCancelConsultation(record.id)" v-if="record.status === 'pending'">取消</a-button>
            <a-button size="small" @click="handleEvaluateConsultation(record.id)" v-if="record.status === 'completed' && !record.evaluated">评价</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 发起问诊模态框 -->
    <a-modal
      v-model:open="isCreateModalOpen"
      title="发起问诊"
      :footer="null"
      width={700}
    >
      <a-form
        :model="newConsultation"
        layout="vertical"
        style="max-width: 600px; margin: 0 auto;"
      >
        <a-form-item label="问诊类型" name="type" :rules="[{ required: true, message: '请选择问诊类型' }]">
          <a-select v-model:value="newConsultation.type" placeholder="请选择问诊类型">
            <a-select-option value="disease">疾病诊断</a-select-option>
            <a-select-option value="nutrition">营养管理</a-select-option>
            <a-select-option value="breeding">繁殖育种</a-select-option>
            <a-select-option value="management">养殖管理</a-select-option>
            <a-select-option value="other">其他问题</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="紧急程度" name="priority" :rules="[{ required: true, message: '请选择紧急程度' }]">
          <a-radio-group v-model:value="newConsultation.priority">
            <a-radio value="low">普通</a-radio>
            <a-radio value="medium">较急</a-radio>
            <a-radio value="high">紧急</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="问题描述" name="description" :rules="[{ required: true, message: '请描述您的问题' }]">
          <a-textarea v-model:value="newConsultation.description" placeholder="请详细描述您的问题，包括症状、持续时间、已采取的措施等" :rows="6" />
        </a-form-item>
        
        <a-form-item label="上传图片/视频（选填）" name="attachments">
          <a-upload
            name="file"
            :multiple="true"
            :showUploadList="true"
            :beforeUpload="beforeUpload"
            @change="handleUploadChange"
            accept="image/*,video/*"
          >
            <a-button>
              <span class="iconfont icon-upload"></span> 选择文件
            </a-button>
            <span style="margin-left: 8px; color: #999;">支持图片和视频，最多上传5个文件</span>
          </a-upload>
        </a-form-item>
        
        <a-form-item label="期望医生（选填）" name="doctorId">
          <a-select v-model:value="newConsultation.doctorId" placeholder="请选择期望的医生（不选择则系统自动分配）">
            <a-select-option value="">系统自动分配</a-select-option>
            <a-select-option v-for="doctor in onlineDoctors" :key="doctor.id" :value="doctor.id">
              {{ doctor.name }} ({{ doctor.department }})
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="联系方式" name="contact" :rules="[{ required: true, message: '请输入联系方式' }]">
          <a-input v-model:value="newConsultation.contact" placeholder="请输入您的手机号或其他联系方式" />
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isCreateModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleSubmitConsultation">提交问诊</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 问诊详情模态框 -->
    <a-modal
      v-model:open="isDetailModalOpen"
      title="问诊详情"
      :footer="null"
      width={900}
      class="consultation-detail-modal"
    >
      <div v-if="currentConsultation" class="consultation-detail">
        <div class="detail-header">
          <div class="detail-basic">
            <h3>{{ currentConsultation.title || '问诊详情' }}</h3>
            <div class="detail-meta">
              <span>问诊编号: {{ currentConsultation.id }}</span>
              <span>发起时间: {{ currentConsultation.createTime }}</span>
              <span>状态: <a-tag :color="getStatusColor(currentConsultation.status)">{{ getStatusText(currentConsultation.status) }}</a-tag></span>
              <span>紧急程度: <a-tag :color="getPriorityColor(currentConsultation.priority)">{{ getPriorityText(currentConsultation.priority) }}</a-tag></span>
            </div>
          </div>
          
          <div v-if="currentConsultation.doctor" class="doctor-detail">
            <div class="doctor-info">
              <img :src="currentConsultation.doctor.avatar" alt="{{ currentConsultation.doctor.name }}" class="doctor-avatar-small" />
              <div class="doctor-text">
                <div class="doctor-name">{{ currentConsultation.doctor.name }}</div>
                <div class="doctor-title">{{ currentConsultation.doctor.title }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 问题描述 -->
        <div class="detail-section">
          <h4>问题描述</h4>
          <div class="description-content">{{ currentConsultation.description }}</div>
        </div>
        
        <!-- 上传的附件 -->
        <div v-if="currentConsultation.attachments && currentConsultation.attachments.length > 0" class="detail-section">
          <h4>相关材料</h4>
          <a-upload-list
            :items="getUploadItems(currentConsultation.attachments)"
            :showRemoveIcon="false"
            :showDownloadIcon="true"
          />
        </div>
        
        <!-- 问诊记录 -->
        <div class="detail-section">
          <h4>问诊记录</h4>
          <div class="message-list">
            <div v-for="message in currentConsultation.messages" :key="message.id" class="message-item" :class="{ 'self-message': message.senderType === 'user' }">
              <div class="message-avatar">
                <img v-if="message.senderType === 'doctor'" :src="currentConsultation.doctor?.avatar" alt="医生" />
                <div v-else class="user-avatar">
                  <span class="iconfont icon-user"></span>
                </div>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <span class="message-sender">{{ message.senderType === 'doctor' ? currentConsultation.doctor?.name : '我' }}</span>
                  <span class="message-time">{{ message.sendTime }}</span>
                </div>
                <div class="message-text">{{ message.content }}</div>
                <div v-if="message.attachments && message.attachments.length > 0" class="message-attachments">
                  <a-upload-list
                    :items="getUploadItems(message.attachments)"
                    :showRemoveIcon="false"
                    :showDownloadIcon="true"
                    :maxCount="5"
                  />
                </div>
              </div>
            </div>
          </div>
          
          <!-- 发送消息区域 -->
          <div v-if="currentConsultation.status === 'ongoing'" class="message-input-area">
            <a-upload
              name="file"
              :multiple="false"
              :beforeUpload="beforeUpload"
              @change="handleMessageUploadChange"
              :showUploadList="false"
              accept="image/*,video/*"
            >
              <a-button icon="picture" size="small">图片</a-button>
            </a-upload>
            <a-input.TextArea v-model:value="newMessage" placeholder="输入消息..." :rows="3" />
            <div style="text-align: right; margin-top: 8px;">
              <a-button type="primary" @click="handleSendMessage(currentConsultation.id)">发送消息</a-button>
            </div>
          </div>
        </div>
        
        <!-- 诊断结果 -->
        <div v-if="currentConsultation.diagnosisResult" class="detail-section">
          <h4>诊断结果</h4>
          <div class="diagnosis-content">{{ currentConsultation.diagnosisResult }}</div>
        </div>
        
        <!-- 治疗方案 -->
        <div v-if="currentConsultation.treatmentPlan" class="detail-section">
          <h4>治疗方案</h4>
          <div class="treatment-content">{{ currentConsultation.treatmentPlan }}</div>
        </div>
        
        <!-- 评价 -->
        <div v-if="currentConsultation.status === 'completed' && !currentConsultation.evaluated" class="detail-section">
          <h4>评价问诊</h4>
          <div class="evaluation-form">
            <a-rate v-model:value="evaluationScore" />
            <a-textarea v-model:value="evaluationContent" placeholder="请输入您的评价内容" :rows="3" style="margin-top: 12px;" />
            <div style="text-align: right; margin-top: 8px;">
              <a-button type="primary" @click="handleSubmitEvaluation">提交评价</a-button>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    
    <!-- 确认对话框 -->
    <a-popconfirm
      v-model:open="isConfirmModalOpen"
      title="确认操作"
      :description="confirmMessage"
      ok-text="确认"
      cancel-text="取消"
      @confirm="handleConfirmAction"
    >
      <template #reference>
        <!-- 这里是空的，通过其他按钮触发 -->
      </template>
    </a-popconfirm>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'

// 搜索条件
const searchKeyword = ref('')
const statusFilter = ref('')
const doctorFilter = ref('')
const dateRange = ref([])

// 统计数据
const totalConsultations = ref(3256)
const todayConsultations = ref(67)
const pendingConsultations = ref(45)
const completedConsultations = ref(2890)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 选中的行
const selectedRowKeys = ref([])
const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys
}

// 图表引用
const typeChartRef = ref(null)

// 模态框状态
const isCreateModalOpen = ref(false)
const isDetailModalOpen = ref(false)
const isConfirmModalOpen = ref(false)
const confirmMessage = ref('')
const confirmAction = ref('')
const confirmTargetId = ref('')

// 上传文件列表
const uploadFileList = ref([])
const messageUploadFileList = ref([])

// 新消息
const newMessage = ref('')

// 评价相关
const evaluationScore = ref(5)
const evaluationContent = ref('')

// 当前用户信息（模拟）
const currentUserId = ref('1')
const currentUserInfo = ref({
  name: '当前用户',
  contact: '13800138000'
})

// 医生列表
const doctors = ref([
  { id: '1', name: '张医生', department: '牛病防治科' },
  { id: '2', name: '李医生', department: '营养科' },
  { id: '3', name: '王医生', department: '繁殖科' },
  { id: '4', name: '刘医生', department: '养殖管理科' }
])

// 在线医生列表
const onlineDoctors = ref([
  {
    id: '1',
    name: '张医生',
    title: '主任医师',
    department: '牛病防治科',
    avatar: 'https://api.dicebear.com/6.x/avataaars/svg?seed=doctor1',
    consultCount: 1254,
    satisfaction: 98,
    online: true
  },
  {
    id: '2',
    name: '李医生',
    title: '副主任医师',
    department: '营养科',
    avatar: 'https://api.dicebear.com/6.x/avataaars/svg?seed=doctor2',
    consultCount: 897,
    satisfaction: 96,
    online: true
  },
  {
    id: '3',
    name: '王医生',
    title: '主治医师',
    department: '繁殖科',
    avatar: 'https://api.dicebear.com/6.x/avataaars/svg?seed=doctor3',
    consultCount: 678,
    satisfaction: 97,
    online: true
  },
  {
    id: '4',
    name: '刘医生',
    title: '副主任医师',
    department: '养殖管理科',
    avatar: 'https://api.dicebear.com/6.x/avataaars/svg?seed=doctor4',
    consultCount: 1023,
    satisfaction: 95,
    online: true
  }
])

// 新问诊表单数据
const newConsultation = reactive({
  type: 'disease',
  priority: 'medium',
  description: '',
  doctorId: '',
  contact: currentUserInfo.value.contact,
  attachments: []
})

// 当前问诊详情
const currentConsultation = ref(null)

// 问诊记录列表
const consultationList = ref([
  {
    id: '1',
    type: 'disease',
    status: 'completed',
    priority: 'high',
    doctorId: '1',
    doctorName: '张医生',
    createTime: '2023-10-01 09:30',
    lastUpdateTime: '2023-10-01 11:45',
    evaluated: true,
    satisfaction: 5
  },
  {
    id: '2',
    type: 'nutrition',
    status: 'ongoing',
    priority: 'medium',
    doctorId: '2',
    doctorName: '李医生',
    createTime: '2023-10-02 14:20',
    lastUpdateTime: '2023-10-02 15:30',
    evaluated: false
  },
  {
    id: '3',
    type: 'breeding',
    status: 'pending',
    priority: 'medium',
    doctorId: '',
    doctorName: '',
    createTime: '2023-10-03 10:15',
    lastUpdateTime: '2023-10-03 10:15',
    evaluated: false
  },
  {
    id: '4',
    type: 'management',
    status: 'completed',
    priority: 'low',
    doctorId: '4',
    doctorName: '刘医生',
    createTime: '2023-10-04 16:45',
    lastUpdateTime: '2023-10-04 18:00',
    evaluated: true,
    satisfaction: 4
  },
  {
    id: '5',
    type: 'other',
    status: 'canceled',
    priority: 'low',
    doctorId: '',
    doctorName: '',
    createTime: '2023-10-05 08:30',
    lastUpdateTime: '2023-10-05 09:00',
    evaluated: false
  },
  {
    id: '6',
    type: 'disease',
    status: 'completed',
    priority: 'high',
    doctorId: '1',
    doctorName: '张医生',
    createTime: '2023-10-06 11:20',
    lastUpdateTime: '2023-10-06 13:15',
    evaluated: true,
    satisfaction: 5
  },
  {
    id: '7',
    type: 'nutrition',
    status: 'pending',
    priority: 'medium',
    doctorId: '',
    doctorName: '',
    createTime: '2023-10-07 13:45',
    lastUpdateTime: '2023-10-07 13:45',
    evaluated: false
  },
  {
    id: '8',
    type: 'breeding',
    status: 'ongoing',
    priority: 'high',
    doctorId: '3',
    doctorName: '王医生',
    createTime: '2023-10-08 15:10',
    lastUpdateTime: '2023-10-08 16:30',
    evaluated: false
  },
  {
    id: '9',
    type: 'management',
    status: 'completed',
    priority: 'low',
    doctorId: '4',
    doctorName: '刘医生',
    createTime: '2023-10-09 09:30',
    lastUpdateTime: '2023-10-09 10:45',
    evaluated: false
  },
  {
    id: '10',
    type: 'disease',
    status: 'pending',
    priority: 'medium',
    doctorId: '',
    doctorName: '',
    createTime: '2023-10-10 10:00',
    lastUpdateTime: '2023-10-10 10:00',
    evaluated: false
  }
])

// 表格列定义
const columns = [
  {
    title: '问诊编号',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '问诊类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
    render: (type) => getTypeText(type)
  },
  {
    title: '医生',
    dataIndex: 'doctor',
    key: 'doctor',
    width: 120
  },
  {
    title: '发起时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdateTime',
    key: 'lastUpdateTime',
    width: 150
  },
  {
    title: '紧急程度',
    dataIndex: 'priority',
    key: 'priority',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待接诊'
    case 'ongoing': return '问诊中'
    case 'completed': return '已完成'
    case 'canceled': return '已取消'
    default: return status
  }
}

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 'pending': return 'orange'
    case 'ongoing': return 'blue'
    case 'completed': return 'green'
    case 'canceled': return 'gray'
    default: return 'default'
  }
}

// 获取优先级文本
const getPriorityText = (priority) => {
  switch (priority) {
    case 'low': return '普通'
    case 'medium': return '较急'
    case 'high': return '紧急'
    default: return priority
  }
}

// 获取优先级颜色
const getPriorityColor = (priority) => {
  switch (priority) {
    case 'low': return 'green'
    case 'medium': return 'orange'
    case 'high': return 'red'
    default: return 'default'
  }
}

// 获取类型文本
const getTypeText = (type) => {
  switch (type) {
    case 'disease': return '疾病诊断'
    case 'nutrition': return '营养管理'
    case 'breeding': return '繁殖育种'
    case 'management': return '养殖管理'
    case 'other': return '其他问题'
    default: return type
  }
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索条件:', {
    keyword: searchKeyword.value,
    status: statusFilter.value,
    doctorId: doctorFilter.value,
    dateRange: dateRange.value
  })
  // 这里应该有实际的搜索逻辑
  // 模拟搜索后的总数
  pagination.total = consultationList.value.length
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  doctorFilter.value = ''
  dateRange.value = []
  selectedRowKeys.value = []
}

// 发起问诊
const handleCreateConsultation = () => {
  // 重置新问诊表单
  Object.assign(newConsultation, {
    type: 'disease',
    priority: 'medium',
    description: '',
    doctorId: '',
    contact: currentUserInfo.value.contact,
    attachments: []
  })
  uploadFileList.value = []
  isCreateModalOpen.value = true
}

// 提交问诊
const handleSubmitConsultation = () => {
  console.log('提交问诊:', newConsultation)
  // 这里应该有实际的提交逻辑
  // 模拟提交成功
  isCreateModalOpen.value = false
  alert('问诊提交成功，请等待医生接诊')
}

// 查看问诊详情
const handleViewConsultation = (record) => {
  // 模拟获取问诊详情
  const doctor = onlineDoctors.value.find(d => d.id === record.doctorId)
  const consultationDetail = {
    ...JSON.parse(JSON.stringify(record)),
    title: getTypeText(record.type),
    description: record.type === 'disease' 
      ? '我家的牛最近出现了腹泻症状，已经持续3天了，食欲也下降了。我尝试过给它喂一些止泻药，但是效果不明显。请医生帮忙诊断一下是什么原因，应该如何治疗？' 
      : '这是问诊的详细描述内容...',
    doctor: doctor,
    attachments: record.id === '1' ? ['症状照片1.jpg', '症状照片2.jpg'] : [],
    messages: [
      {
        id: '1',
        senderType: 'user',
        content: '张医生您好，我家的牛最近出现了腹泻症状，已经持续3天了，食欲也下降了。',
        sendTime: '2023-10-01 09:30',
        attachments: []
      },
      {
        id: '2',
        senderType: 'doctor',
        content: '您好，请详细描述一下牛的症状，包括大便的颜色、形状，是否有发热、呕吐等其他症状？最近的饲料有什么变化吗？',
        sendTime: '2023-10-01 09:45',
        attachments: []
      },
      {
        id: '3',
        senderType: 'user',
        content: '大便呈水样，黄色，没有发热和呕吐的症状。最近我们更换了一批新的饲料，可能和这个有关？',
        sendTime: '2023-10-01 10:00',
        attachments: ['牛的症状照片.jpg']
      },
      {
        id: '4',
        senderType: 'doctor',
        content: '根据您的描述和照片，初步判断可能是饲料变化引起的消化不良。建议您先停喂新饲料，改喂易消化的饲料。同时可以给牛服用一些益生菌和止泻药物。如果症状持续加重，建议您及时联系当地兽医进行进一步检查。',
        sendTime: '2023-10-01 10:30',
        attachments: []
      },
      {
        id: '5',
        senderType: 'user',
        content: '好的，谢谢张医生，我会按照您的建议进行处理。',
        sendTime: '2023-10-01 11:00',
        attachments: []
      }
    ],
    diagnosisResult: record.status === 'completed' ? '饲料变化引起的消化不良' : '',
    treatmentPlan: record.status === 'completed' ? '1. 停喂新饲料，改喂易消化的饲料；2. 服用益生菌调理肠胃；3. 适当服用止泻药物；4. 观察症状变化，如持续加重及时就医。' : ''
  }
  currentConsultation.value = consultationDetail
  newMessage.value = ''
  messageUploadFileList.value = []
  isDetailModalOpen.value = true
}

// 直接向医生咨询
const handleConsultDoctor = (doctorId) => {
  const doctor = onlineDoctors.value.find(d => d.id === doctorId)
  if (doctor) {
    // 重置新问诊表单，并预设医生
    Object.assign(newConsultation, {
      type: 'disease',
      priority: 'medium',
      description: '',
      doctorId: doctorId,
      contact: currentUserInfo.value.contact,
      attachments: []
    })
    uploadFileList.value = []
    isCreateModalOpen.value = true
  }
}

// 发送消息
const handleSendMessage = (consultationId) => {
  if (!newMessage.value.trim() && messageUploadFileList.value.length === 0) {
    alert('消息内容不能为空')
    return
  }
  
  if (currentConsultation.value && currentConsultation.value.id === consultationId) {
    const newMsg = {
      id: Date.now().toString(),
      senderType: 'user',
      content: newMessage.value,
      sendTime: new Date().toLocaleString('zh-CN'),
      attachments: messageUploadFileList.value.map(file => file.name)
    }
    
    if (!currentConsultation.value.messages) {
      currentConsultation.value.messages = []
    }
    currentConsultation.value.messages.push(newMsg)
    currentConsultation.value.lastUpdateTime = new Date().toLocaleString('zh-CN')
    
    // 模拟医生回复
    setTimeout(() => {
      const doctorReply = {
        id: Date.now().toString(),
        senderType: 'doctor',
        content: '收到您的消息，我会尽快回复您的问题。',
        sendTime: new Date().toLocaleString('zh-CN'),
        attachments: []
      }
      currentConsultation.value.messages.push(doctorReply)
    }, 2000)
    
    newMessage.value = ''
    messageUploadFileList.value = []
  }
}

// 取消问诊 - 弹出确认对话框
const handleCancelConsultation = (id) => {
  confirmMessage.value = '确定要取消该问诊吗？'
  confirmAction.value = 'cancel'
  confirmTargetId.value = id
  isConfirmModalOpen.value = true
}

// 评价问诊
const handleEvaluateConsultation = (id) => {
  // 直接打开详情模态框并滚动到评价区域
  const record = consultationList.value.find(item => item.id === id)
  if (record) {
    handleViewConsultation(record)
    setTimeout(() => {
      const evaluationElement = document.querySelector('.evaluation-form')
      if (evaluationElement) {
        evaluationElement.scrollIntoView({ behavior: 'smooth' })
      }
    }, 100)
  }
}

// 提交评价
const handleSubmitEvaluation = () => {
  if (currentConsultation.value) {
    console.log('提交评价:', {
      consultationId: currentConsultation.value.id,
      score: evaluationScore.value,
      content: evaluationContent.value
    })
    // 这里应该有实际的提交评价逻辑
    // 模拟提交成功
    currentConsultation.value.evaluated = true
    currentConsultation.value.satisfaction = evaluationScore.value
    alert('评价提交成功，感谢您的反馈！')
    
    // 重置评价表单
    evaluationScore.value = 5
    evaluationContent.value = ''
  }
}

// 确认操作
const handleConfirmAction = () => {
  if (confirmAction.value === 'cancel') {
    console.log('取消问诊:', confirmTargetId.value)
    // 这里应该有实际的取消逻辑
    // 模拟取消成功
    alert(`成功取消问诊ID: ${confirmTargetId.value}`)
  }
  isConfirmModalOpen.value = false
}

// 文件上传前处理
const beforeUpload = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    alert('文件大小不能超过 20MB!')
    return Upload.LIST_IGNORE
  }
  return false // 阻止自动上传
}

// 文件上传变化处理
const handleUploadChange = ({ fileList }) => {
  uploadFileList.value = fileList
}

// 消息文件上传变化处理
const handleMessageUploadChange = ({ fileList }) => {
  messageUploadFileList.value = fileList
}

// 获取上传文件项
const getUploadItems = (files) => {
  return files.map((file, index) => ({
    uid: `${index}`,
    name: file,
    status: 'done',
    url: `#${file}`,
  }))
}

// 初始化问诊类型分布图表
const initTypeChart = () => {
  if (!typeChartRef.value) return
  
  const chart = echarts.init(typeChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '问诊类型',
        type: 'pie',
        radius: '60%',
        data: [
          { value: 45, name: '疾病诊断' },
          { value: 20, name: '营养管理' },
          { value: 15, name: '繁殖育种' },
          { value: 12, name: '养殖管理' },
          { value: 8, name: '其他问题' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initTypeChart()
  }, 100)
})

// 初始化数据
pagination.total = consultationList.value.length
</script>

<style scoped>
  .doctor-card {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    width: 300px;
  }
  
  .doctor-avatar img {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
  
  .doctor-info {
    flex: 1;
  }
  
  .doctor-name {
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 4px;
  }
  
  .doctor-title {
    color: #1890ff;
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .doctor-department {
    color: #666;
    font-size: 14px;
    margin-bottom: 8px;
  }
  
  .doctor-stats {
    display: flex;
    gap: 16px;
    font-size: 12px;
    color: #999;
    margin-bottom: 8px;
  }
  
  .consultation-detail-modal .ant-modal-body {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .detail-basic h3 {
    margin-bottom: 12px;
    color: #333;
  }
  
  .detail-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    font-size: 14px;
    color: #666;
  }
  
  .doctor-detail {
    text-align: right;
  }
  
  .doctor-avatar-small {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 8px;
  }
  
  .doctor-info {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  
  .doctor-text .doctor-name {
    font-weight: bold;
    font-size: 14px;
  }
  
  .doctor-text .doctor-title {
    font-size: 12px;
    color: #1890ff;
  }
  
  .detail-section {
    margin-bottom: 24px;
  }
  
  .detail-section h4 {
    margin-bottom: 12px;
    color: #333;
    font-size: 16px;
  }
  
  .description-content,
  .diagnosis-content,
  .treatment-content {
    padding: 16px;
    background-color: #f5f5f5;
    border-radius: 6px;
    line-height: 1.6;
    color: #333;
  }
  
  .message-list {
    max-height: 400px;
    overflow-y: auto;
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 6px;
  }
  
  .message-item {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .message-item.self-message {
    flex-direction: row-reverse;
  }
  
  .message-avatar img,
  .user-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #e8e8e8;
  }
  
  .message-content {
    max-width: 70%;
  }
  
  .message-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    font-size: 12px;
    color: #999;
  }
  
  .message-text {
    padding: 8px 12px;
    background-color: #fff;
    border-radius: 6px;
    border: 1px solid #e8e8e8;
    line-height: 1.5;
  }
  
  .self-message .message-text {
    background-color: #e6f7ff;
    border-color: #91d5ff;
  }
  
  .message-attachments {
    margin-top: 8px;
  }
  
  .message-input-area {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #e8e8e8;
  }
  
  .evaluation-form {
    padding: 16px;
    background-color: #f5f5f5;
    border-radius: 6px;
  }
</style>