<template>
  <div>
    <!-- Convert Management Popup (non-modal, bottom-right) -->
    <div 
      v-if="visible" 
      class="convert-popup"
      @click.stop
    >
      <div class="convert-popup-header">
        <span class="convert-popup-title">转事件管理</span>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="handleClose"
          class="convert-popup-close"
        ></el-button>
      </div>
      
      <!-- 筛选区域 -->
      <div class="convert-popup-filters">
        <el-select
          v-model="statusFilter"
          placeholder="全部状态"
          size="small"
          clearable
          style="width: 100%"
          @change="handleStatusFilterChange"
        >
          <el-option label="全部状态" value=""></el-option>
          <el-option label="待审核" value="pending"></el-option>
          <el-option label="已审核" value="approved"></el-option>
          <el-option label="已驳回" value="rejected"></el-option>
        </el-select>
      </div>
      
      <!-- 内容区域 -->
      <div class="convert-popup-body">
        <div v-loading="loading" class="convert-list">
          <div 
            v-for="convert in convertList" 
            :key="convert.id"
            class="convert-item"
            @click="handleSelect(convert)"
          >
            <div class="convert-header">
              <span class="convert-alert-no">{{ convert.alertNo || '未知警情' }}</span>
              <el-tag 
                size="mini" 
                :type="getConvertStatusTagType(convert.reviewStatus)"
              >
                {{ getConvertStatusLabel(convert.reviewStatus) }}
              </el-tag>
            </div>
            <div class="convert-info">
              <div class="convert-row">
                <span class="convert-label">转事件时间：</span>
                <span class="convert-value">{{ formatDateTime(convert.convertTime) }}</span>
              </div>
              <div class="convert-row">
                <span class="convert-label">转事件原因：</span>
                <span class="convert-value">{{ convert.convertReason || '暂无' }}</span>
              </div>
              <div v-if="convert.eventId" class="convert-row">
                <span class="convert-label">事件ID：</span>
                <span class="convert-value">{{ convert.eventId }}</span>
              </div>
            </div>
          </div>
          <el-empty v-if="!loading && convertList.length === 0" description="暂无转事件记录" :image-size="80"></el-empty>
        </div>
        
        <!-- 分页 -->
        <div v-if="total >= pageSize" class="convert-pagination">
          <el-pagination
            small
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- Click outside backdrop (invisible, non-blocking) -->
    <div 
      v-if="visible"
      class="convert-popup-backdrop"
      @click="handleClose"
    ></div>

    <!-- 转事件详情抽屉 -->
    <el-drawer
      title="转事件详情"
      :visible.sync="detailDrawerVisible"
      size="500px"
      :with-header="true"
    >
      <div v-if="selectedConvert" class="convert-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="警情编号">
            {{ selectedConvert.alertNo || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getConvertStatusTagType(selectedConvert.reviewStatus)" size="small">
              {{ getConvertStatusLabel(selectedConvert.reviewStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="转事件时间">
            {{ formatDateTime(selectedConvert.convertTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="转事件原因">
            <div class="summary-text">{{ selectedConvert.convertReason || '暂无' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="操作人">
            {{ selectedConvert.operatorName || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedConvert.eventId" label="事件ID">
            {{ selectedConvert.eventId }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedConvert.remark" label="备注">
            <div class="summary-text">{{ selectedConvert.remark }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listConverts, getConvert, getAlert } from '@/api/duty/alert'
import { formatDateTime as formatDateTimeHelper } from '../utils/dateHelpers'

export default {
  name: 'ConvertManagementPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      convertList: [],
      loading: false,
      statusFilter: '', // 状态筛选
      currentPage: 1,
      pageSize: 20,
      total: 0,
      // 详情抽屉
      detailDrawerVisible: false,
      selectedConvert: null
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadConverts()
      } else {
        // 关闭时重置（但不重置 selectedConvert，因为抽屉可能还在显示）
        this.currentPage = 1
        this.statusFilter = ''
        // 不在这里重置 selectedConvert，让抽屉自己管理
      }
    },
    // 监听抽屉关闭事件，重置 selectedConvert
    detailDrawerVisible(newVal) {
      if (!newVal) {
        // 抽屉关闭时重置
        this.selectedConvert = null
      }
    }
  },
  methods: {
    /**
     * 加载转事件列表
     */
    async loadConverts() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        if (this.statusFilter) {
          params.reviewStatus = this.statusFilter
        }
        
        const res = await listConverts(params)
        
        if (res.code === 200) {
          const converts = res.rows || []
          // 需要获取每个转事件记录对应的警情编号
          // 由于后端可能没有直接返回 alertNo，我们需要通过 alertId 查询
          const convertsWithAlertNo = await Promise.all(
            converts.map(async (convert) => {
              if (convert.alertId) {
                try {
                  const alertRes = await getAlert(convert.alertId)
                  if (alertRes.code === 200 && alertRes.data) {
                    return {
                      ...convert,
                      alertNo: alertRes.data.alertNo
                    }
                  }
                } catch (error) {
                  console.warn(`获取警情 ${convert.alertId} 信息失败:`, error)
                }
              }
              return convert
            })
          )
          this.convertList = convertsWithAlertNo
          this.total = res.total || 0
        }
      } catch (error) {
        console.error('获取转事件列表失败:', error)
        this.$message.error('获取转事件列表失败，请稍后重试')
        this.convertList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 处理状态筛选变化
     */
    handleStatusFilterChange() {
      this.currentPage = 1
      this.loadConverts()
    },
    
    /**
     * 处理分页变化
     */
    handlePageChange(page) {
      this.currentPage = page
      this.loadConverts()
    },
    
    /**
     * 选择转事件记录（查看详情）
     */
    async handleSelect(convert) {
      // 加载完整详情
      try {
        const res = await getConvert(convert.id)
        if (res.code === 200 && res.data) {
          // 如果有 alertId，获取警情编号
          if (res.data.alertId) {
            try {
              const alertRes = await getAlert(res.data.alertId)
              if (alertRes.code === 200 && alertRes.data) {
                res.data.alertNo = alertRes.data.alertNo
              }
            } catch (error) {
              console.warn('获取警情信息失败:', error)
            }
          }
          this.selectedConvert = res.data
          this.detailDrawerVisible = true
          // 使用 $nextTick 确保抽屉先打开，然后再关闭弹窗
          this.$nextTick(() => {
            this.handleClose()
          })
        }
      } catch (error) {
        console.error('获取转事件详情失败:', error)
        this.$message.error('获取转事件详情失败，请稍后重试')
      }
    },
    
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.$emit('close')
    },
    
    /**
     * 获取转事件状态标签
     */
    getConvertStatusLabel(status) {
      const statusMap = {
        'pending': '待审核',
        'approved': '已审核',
        'rejected': '已驳回'
      }
      return statusMap[status] || status || '未知'
    },
    
    /**
     * 获取转事件状态标签类型
     */
    getConvertStatusTagType(status) {
      const typeMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger'
      }
      return typeMap[status] || ''
    },
    
    /**
     * 格式化日期时间
     */
    formatDateTime(dateTimeString) {
      if (!dateTimeString) return '未知'
      // 如果是字符串，直接返回（后端返回的格式已经是 yyyy-MM-dd HH:mm:ss）
      if (typeof dateTimeString === 'string') {
        return dateTimeString.replace('T', ' ').substring(0, 19)
      }
      // 如果是 Date 对象，使用导入的 formatDateTimeHelper 函数
      return formatDateTimeHelper(dateTimeString)
    }
  }
}
</script>

<style lang="scss" scoped>
.convert-popup {
  position: fixed;
  bottom: 100px;
  right: 30px;
  width: 500px;
  height: 500px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 2001;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.convert-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
  flex-shrink: 0;
}

.convert-popup-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.convert-popup-close {
  padding: 0;
  color: #909399;
}

.convert-popup-filters {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.convert-popup-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.convert-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 8px;
}

.convert-item {
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:hover {
    border-color: #409eff;
    background: #f0f9ff;
  }
}

.convert-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

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

.convert-info {
  margin-bottom: 8px;
}

.convert-row {
  display: flex;
  margin-bottom: 4px;
  font-size: 13px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.convert-label {
  color: #909399;
  min-width: 90px;
}

.convert-value {
  color: #606266;
  flex: 1;
  word-break: break-word;
}

.convert-pagination {
  padding: 12px 16px;
  border-top: 1px solid #ebeef5;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
}

.convert-popup-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background: transparent;
}

.convert-detail {
  padding: 20px;
}

.summary-text {
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>