<template>
  <el-drawer
    title="警情详情"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
    @opened="handleOpened"
  >
    <div v-if="loading" class="drawer-loading">
      <i class="el-icon-loading"></i>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="alertData" class="alert-drawer-content">
      <!-- Header Section -->
      <div class="drawer-header">
        <div class="alert-title">
          <span class="alert-no">{{ alertData.alertNo }}</span>
          <el-tag :type="getStatusInfo().tag" size="medium">
            {{ getStatusInfo().label }}
          </el-tag>
        </div>
        <div class="drawer-actions" v-if="shouldShowActions">
          <el-button 
            type="primary" 
            icon="el-icon-edit" 
            size="small"
            @click="handleEdit"
          >
            编辑
          </el-button>
          <el-dropdown 
            trigger="click" 
            @command="handleAction"
          >
            <el-button 
              size="small"
              icon="el-icon-setting"
            >
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                v-if="alertData.status === 'draft'"
                command="submit"
                :disabled="submitting"
              >
                <i class="el-icon-check"></i> 提交
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="canTransfer"
                command="transfer"
              >
                <i class="el-icon-share"></i> 转警
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="canConvert"
                command="convert"
              >
                <i class="el-icon-s-promotion"></i> 转事件
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="alertData.status !== 'closed' && alertData.status !== 'draft'"
                command="close"
                :disabled="closing"
              >
                <i class="el-icon-close"></i> 关闭
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- Basic Information -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="警情编号">
          {{ alertData.alertNo }}
        </el-descriptions-item>
        <el-descriptions-item label="警情状态">
          <el-tag :type="getStatusInfo().tag" size="small">
            {{ getStatusInfo().label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="初判等级">
          <el-tag 
            :type="getLevelTagType(alertData.initialLevel)" 
            size="small"
          >
            {{ getLevelLabel(alertData.initialLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发生时间">
          {{ formatFullDateTime(alertData.occurredAt) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- Source Information -->
      <el-divider content-position="left">来源信息</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="来源渠道">
          {{ getChannelDisplayName(alertData.sourceChannel) }}
        </el-descriptions-item>
        <el-descriptions-item 
          v-if="alertData.callerNumber" 
          label="来电号码"
        >
          <span class="phone-number">{{ alertData.callerNumber }}</span>
        </el-descriptions-item>
        <!-- 结构化显示扩展信息 -->
        <template v-if="parsedExtInfo && Object.keys(parsedExtInfo).length > 0">
          <!-- 转办渠道扩展信息 -->
          <template v-if="isTransferChannel">
            <el-descriptions-item v-if="parsedExtInfo.transferUnit" label="转办单位">
              {{ parsedExtInfo.transferUnit }}
            </el-descriptions-item>
            <el-descriptions-item v-if="parsedExtInfo.transferPerson" label="转办人">
              {{ parsedExtInfo.transferPerson }}
            </el-descriptions-item>
            <el-descriptions-item v-if="parsedExtInfo.transferTime" label="转办时间">
              {{ formatFullDateTime(parsedExtInfo.transferTime) }}
            </el-descriptions-item>
          </template>
          <!-- 监测渠道扩展信息 -->
          <template v-if="isMonitoringChannel">
            <el-descriptions-item v-if="parsedExtInfo.deviceId" label="设备ID">
              {{ parsedExtInfo.deviceId }}
            </el-descriptions-item>
            <el-descriptions-item v-if="parsedExtInfo.monitoringData" label="监测数据">
              <div class="ext-info-text">{{ parsedExtInfo.monitoringData }}</div>
            </el-descriptions-item>
          </template>
          <!-- 媒体渠道扩展信息 -->
          <template v-if="isMediaChannel">
            <el-descriptions-item v-if="parsedExtInfo.mediaSource" label="媒体来源">
              {{ parsedExtInfo.mediaSource }}
            </el-descriptions-item>
            <el-descriptions-item v-if="parsedExtInfo.mediaUrl" label="链接">
              <a :href="parsedExtInfo.mediaUrl" target="_blank" class="ext-info-link">
                {{ parsedExtInfo.mediaUrl }}
              </a>
            </el-descriptions-item>
            <el-descriptions-item v-if="parsedExtInfo.publishTime" label="发布时间">
              {{ formatFullDateTime(parsedExtInfo.publishTime) }}
            </el-descriptions-item>
          </template>
        </template>
      </el-descriptions>

      <!-- Content Section -->
      <el-divider content-position="left">警情内容</el-divider>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="警情摘要">
          <div class="summary-text">{{ alertData.summary || '暂无' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="发生地点">
          <div class="location-info">
            <span>{{ alertData.location || '未指定' }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="alertData.remark" label="备注">
          <div class="summary-text">{{ alertData.remark }}</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- Transfer Information Section (if transfer record exists) -->
      <div v-if="transferRecord">
        <el-divider content-position="left">转警信息</el-divider>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="转警状态">
            <el-tag :type="getTransferStatusTagType(transferRecord.status)" size="small">
              {{ getTransferStatusLabel(transferRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="目标单位">
            {{ transferRecord.targetOrg || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ transferRecord.contact || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <span class="phone-number">{{ transferRecord.mobile || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="转警说明">
            <div class="summary-text">{{ transferRecord.transferDesc || '暂无' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="转警时间">
            {{ formatFullDateTime(transferRecord.transferTime) }}
          </el-descriptions-item>
          <el-descriptions-item 
            v-if="transferRecord.feedback" 
            label="反馈内容"
          >
            <div class="summary-text">{{ transferRecord.feedback }}</div>
          </el-descriptions-item>
          <el-descriptions-item 
            v-if="transferRecord.feedbackTime" 
            label="反馈时间"
          >
            {{ formatFullDateTime(transferRecord.feedbackTime) }}
          </el-descriptions-item>
          <el-descriptions-item 
            v-if="transferRecord.remark" 
            label="备注"
          >
            <div class="summary-text">{{ transferRecord.remark }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- Map Section (if coordinates available) -->
      <div v-if="hasLocation() && mapReady" class="drawer-map-section">
        <el-divider content-position="left">位置信息</el-divider>
        <div class="map-container">
          <Amap
            container-id="alert-detail-map"
            width="100%"
            height="300px"
            :center="[alertData.longitude, alertData.latitude]"
            :zoom="15"
            :markers="[{
              lat: alertData.latitude,
              lng: alertData.longitude,
              title: '发生地点',
              content: alertData.location
            }]"
          />
        </div>
      </div>

      <!-- Operation Logs -->
      <el-divider content-position="left">操作记录</el-divider>
      <div v-if="logs.length === 0" class="no-logs">
        <el-empty description="暂无操作记录" :image-size="80"></el-empty>
      </div>
      <el-timeline v-else>
        <el-timeline-item
          v-for="log in logs"
          :key="log.id"
        >
          <div class="log-item">
            <span class="log-time">{{ formatFullDateTime(log.createdAt) }}</span>
            <el-tag :type="getActionTagType(log.action)" size="small">
              {{ getActionLabel(log.action) }}
            </el-tag>
            <span class="log-operator">{{ log.operatorName || '未知' }}</span>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>
    
    <div v-else class="drawer-error">
      <el-alert
        title="加载失败"
        type="error"
        :closable="false"
        show-icon
      >
        <template slot="default">
          <p>无法加载警情详情，请稍后重试</p>
          <el-button size="mini" @click="$emit('retry')">重试</el-button>
        </template>
      </el-alert>
    </div>
  </el-drawer>
</template>

<script>
import Amap from '@/components/Amap'
import { getAlert, getAlertLogs, getTransferByAlertId, getConvertByAlertId } from '@/api/duty/alert'
import {
  getLevelLabel,
  getLevelTagType,
  formatFullDateTime,
  formatExtInfo,
  getActionLabel,
  getActionTagType
} from '../utils/alertFormatters'
import { getStatusInfo } from '../utils/alertTransformers'

export default {
  name: 'AlertDetailsDrawer',
  components: {
    Amap
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    alertId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      drawerVisible: false,
      loading: false,
      alertData: null,
      logs: [],
      mapReady: false,
      submitting: false,
      closing: false,
      transferRecord: null, // 转警记录
      convertRecord: null // 转事件记录
    }
  },
  computed: {
    /**
     * 解析来源扩展信息（从 JSON 字符串转换为对象）
     */
    parsedExtInfo() {
      if (!this.alertData || !this.alertData.sourceExtInfo) {
        return null
      }
      try {
        const extInfo = typeof this.alertData.sourceExtInfo === 'string' 
          ? JSON.parse(this.alertData.sourceExtInfo) 
          : this.alertData.sourceExtInfo
        return extInfo && Object.keys(extInfo).length > 0 ? extInfo : null
      } catch (error) {
        console.warn('解析来源扩展信息失败:', error)
        return null
      }
    },
    /**
     * 判断是否为转办渠道
     */
    isTransferChannel() {
      if (!this.alertData) return false
      const channel = this.alertData.sourceChannel
      return ['superior', 'subordinate', 'other_dept'].includes(channel)
    },
    /**
     * 判断是否为监测渠道
     */
    isMonitoringChannel() {
      return this.alertData && this.alertData.sourceChannel === 'monitor'
    },
    /**
     * 判断是否为媒体渠道
     */
    isMediaChannel() {
      return this.alertData && this.alertData.sourceChannel === 'media'
    },
    
    /**
     * 是否应该显示操作按钮
     */
    shouldShowActions() {
      // 已关闭的警情不显示操作按钮
      if (this.alertData && this.alertData.status === 'closed') {
        return false
      }
      
      // 如果警情状态是 converted（已转事件），不显示操作按钮
      if (this.alertData && this.alertData.status === 'converted') {
        return false
      }
      
      // 如果有转事件记录且状态不是 rejected，不显示操作按钮
      if (this.convertRecord && this.convertRecord.reviewStatus !== 'rejected') {
        return false
      }
      
      // 如果有转警记录且状态不是 rejected，不显示操作按钮
      if (this.transferRecord && this.transferRecord.status !== 'rejected') {
        return false
      }
      
      // 没有转警/转事件记录，或者都被驳回，正常显示操作按钮
      return true
    },
    
    /**
     * 是否可以转警（仅当状态为 received 且没有未完成的转警/转事件记录时）
     */
    canTransfer() {
      if (!this.alertData || this.alertData.status !== 'received') {
        return false
      }
      
      // 如果有转警记录且状态不是 rejected，则不能转警
      if (this.transferRecord && this.transferRecord.status !== 'rejected') {
        return false
      }
      
      // 如果有转事件记录且状态不是 rejected，则不能转警
      if (this.convertRecord && this.convertRecord.reviewStatus !== 'rejected') {
        return false
      }
      
      return true
    },
    
    /**
     * 是否可以转事件（仅当状态为 received 且没有未完成的转警/转事件记录时）
     */
    canConvert() {
      if (!this.alertData || this.alertData.status !== 'received') {
        return false
      }
      
      // 如果有转警记录且状态不是 rejected，则不能转事件
      if (this.transferRecord && this.transferRecord.status !== 'rejected') {
        return false
      }
      
      // 如果有转事件记录且状态不是 rejected，则不能转事件
      if (this.convertRecord && this.convertRecord.reviewStatus !== 'rejected') {
        return false
      }
      
      return true
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
      if (newVal && this.alertId) {
        this.loadDetails()
      }
    },
    alertId(newVal) {
      if (newVal && this.drawerVisible) {
        this.loadDetails()
      }
    },
    drawerVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false)
        this.reset()
      }
    }
  },
  methods: {
    /**
     * 加载警情详情
     */
    async loadDetails() {
      if (!this.alertId) return
      
      this.loading = true
      this.mapReady = false
      try {
        // 并行加载警情详情、操作日志、转警记录和转事件记录
        const [alertRes, logsRes, transferRes, convertRes] = await Promise.all([
          getAlert(this.alertId),
          getAlertLogs(this.alertId).catch(() => ({ code: 200, data: [] })), // 日志加载失败不影响主流程
          getTransferByAlertId(this.alertId).catch(() => ({ code: 200, data: null })), // 转警记录可能不存在
          getConvertByAlertId(this.alertId).catch(() => ({ code: 200, data: null })) // 转事件记录可能不存在
        ])
        
        if (alertRes.code === 200) {
          this.alertData = alertRes.data
        } else {
          this.$message.error(alertRes.msg || '加载失败')
          this.alertData = null
        }
        
        // 加载操作日志
        if (logsRes.code === 200 && logsRes.data) {
          this.logs = Array.isArray(logsRes.data) ? logsRes.data : []
        } else {
          this.logs = []
        }
        
        // 加载转警记录
        if (transferRes.code === 200 && transferRes.data) {
          this.transferRecord = transferRes.data
        } else {
          this.transferRecord = null
        }
        
        // 加载转事件记录
        if (convertRes.code === 200 && convertRes.data) {
          this.convertRecord = convertRes.data
        } else {
          this.convertRecord = null
        }
      } catch (error) {
        console.error('加载警情详情失败:', error)
        this.$message.error('加载失败，请稍后重试')
        this.alertData = null
        this.logs = []
        this.transferRecord = null
        this.convertRecord = null
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 处理抽屉关闭
     */
    handleClose(done) {
      this.reset()
      done()
    },
    
    /**
     * 处理抽屉打开
     */
    handleOpened() {
      // 等待抽屉完全打开后再初始化地图，确保容器有正确的尺寸
      this.$nextTick(() => {
        setTimeout(() => {
          this.mapReady = true
        }, 100) // 额外延迟100ms确保动画完成
      })
    },
    
    /**
     * 重置组件状态
     */
    reset() {
      this.alertData = null
      this.logs = []
      this.mapReady = false
      this.submitting = false
      this.closing = false
      this.transferRecord = null
      this.convertRecord = null
    },
    
    /**
     * 检查是否有位置信息
     */
    hasLocation() {
      return this.alertData && 
             this.alertData.longitude && 
             this.alertData.latitude
    },
    
    /**
     * 获取状态标签和类型（使用增强的状态显示逻辑）
     */
    getStatusInfo(statusCodeOrAlert) {
      // 如果有 alertData，传入完整的 alert 对象（包含 transferRecord 和 convertRecord）
      if (this.alertData) {
        const fullAlert = {
          ...this.alertData,
          transferRecord: this.transferRecord,
          convertRecord: this.convertRecord
        }
        return getStatusInfo(fullAlert)
      }
      // 向后兼容：如果只有 statusCode
      return getStatusInfo(statusCodeOrAlert)
    },
    
    /**
     * 获取渠道显示名称
     */
    getChannelDisplayName(sourceChannel) {
      const channelMap = {
        '122': '122',
        '12345': '12345',
        '110': '110',
        'superior': '上级转办',
        'subordinate': '下级上报',
        'other_dept': '其他部门转办',
        'monitor': '监测',
        'media': '媒体',
        'manual': '手工录入'
      }
      return channelMap[sourceChannel] || sourceChannel || '未知'
    },
    
    // 格式化函数已移至 alertFormatters.js
    getLevelLabel,
    getLevelTagType,
    formatFullDateTime,
    formatExtInfo,
    getActionLabel,
    getActionTagType,
    
    /**
     * 获取转警状态标签
     */
    getTransferStatusLabel(status) {
      const statusMap = {
        'pending_review': '待审核',
        'pending_feedback': '待反馈',
        'feedback_received': '已反馈',
        'processed': '已处理',
        'rejected': '已驳回'
      }
      return statusMap[status] || status || '未知'
    },
    
    /**
     * 获取转警状态标签类型
     */
    getTransferStatusTagType(status) {
      const typeMap = {
        'pending_review': 'warning',
        'pending_feedback': 'info',
        'feedback_received': 'success',
        'processed': 'success',
        'rejected': 'danger'
      }
      return typeMap[status] || ''
    },
    
    /**
     * 处理编辑
     */
    handleEdit() {
      this.$emit('edit', this.alertData)
    },
    
    /**
     * 处理操作菜单命令
     */
    handleAction(command) {
      this.$emit('action', command, this.alertData)
    }
  }
}
</script>

<style lang="scss" scoped>
.drawer-loading {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.drawer-loading i {
  font-size: 24px;
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.alert-drawer-content {
  padding: 20px;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.alert-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.alert-no {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.drawer-actions {
  display: flex;
  gap: 8px;
}

.phone-number {
  font-family: monospace;
  color: #409eff;
}

.ext-info {
  background: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
  margin: 0;
}

.ext-info-text {
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.ext-info-link {
  color: #409eff;
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
  }
}

.summary-text {
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap; /* 保留换行和空白字符，用于显示多次反馈的分隔符 */
  word-break: break-word;
}

/* 穿透 Element UI 样式，确保反馈内容正确换行 */
::v-deep .el-descriptions-item__content .summary-text {
  white-space: pre-wrap;
}

.location-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.drawer-map-section {
  margin-top: 20px;
}

.map-container {
  border-radius: 4px;
  overflow: hidden;
}

.no-logs {
  text-align: center;
  padding: 40px 20px;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.log-time {
  color: #909399;
  font-size: 12px;
  min-width: 150px;
}

.log-operator {
  color: #606266;
  font-size: 14px;
}

.drawer-error {
  padding: 20px;
}
</style>