<template>
  <div>
    <!-- Transfer Management Popup (non-modal, bottom-right) -->
    <div 
      v-if="visible" 
      class="transfer-popup"
      @click.stop
    >
      <div class="transfer-popup-header">
        <span class="transfer-popup-title">转警管理</span>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="handleClose"
          class="transfer-popup-close"
        ></el-button>
      </div>
      
      <!-- 筛选区域 -->
      <div class="transfer-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_review"></el-option>
          <el-option label="待反馈" value="pending_feedback"></el-option>
          <el-option label="已反馈" value="feedback_received"></el-option>
          <el-option label="已处理" value="processed"></el-option>
          <el-option label="已驳回" value="rejected"></el-option>
        </el-select>
      </div>
      
      <!-- 内容区域 -->
      <div class="transfer-popup-body">
        <div v-loading="loading" class="transfer-list">
          <div 
            v-for="transfer in transferList" 
            :key="transfer.id"
            class="transfer-item"
            @click="handleSelect(transfer)"
          >
            <div class="transfer-header">
              <span class="transfer-alert-no">{{ transfer.alertNo || '未知警情' }}</span>
              <el-tag 
                size="mini" 
                :type="getTransferStatusTagType(transfer.status)"
              >
                {{ getTransferStatusLabel(transfer.status) }}
              </el-tag>
            </div>
            <div class="transfer-info">
              <div class="transfer-row">
                <span class="transfer-label">目标单位：</span>
                <span class="transfer-value">{{ transfer.targetOrg || '暂无' }}</span>
              </div>
              <div class="transfer-row">
                <span class="transfer-label">联系人：</span>
                <span class="transfer-value">{{ transfer.contact || '暂无' }}</span>
              </div>
              <div class="transfer-row">
                <span class="transfer-label">转警时间：</span>
                <span class="transfer-value">{{ formatDateTime(transfer.transferTime) }}</span>
              </div>
            </div>
            <div class="transfer-actions" @click.stop>
              <el-button
                v-if="transfer.status === 'pending_feedback' || transfer.status === 'feedback_received'"
                type="text"
                size="mini"
                @click="handleFeedback(transfer)"
              >
                {{ transfer.status === 'pending_feedback' ? '录入反馈' : '追加反馈' }}
              </el-button>
              <el-button
                v-if="transfer.status === 'feedback_received'"
                type="text"
                size="mini"
                @click="handleProcess(transfer)"
              >
                标记处理
              </el-button>
            </div>
          </div>
          <el-empty v-if="!loading && transferList.length === 0" description="暂无转警记录" :image-size="80"></el-empty>
        </div>
        
        <!-- 分页 -->
        <div v-if="total >= pageSize" class="transfer-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="transfer-popup-backdrop"
      @click="handleClose"
    ></div>

    <!-- 反馈录入对话框 -->
    <el-dialog
      :title="currentFeedbackTransfer && currentFeedbackTransfer.status === 'feedback_received' ? '追加反馈' : '录入反馈'"
      :visible.sync="feedbackDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="feedbackForm"
        :model="feedbackForm"
        :rules="feedbackRules"
        label-width="100px"
      >
        <el-form-item label="反馈内容" prop="feedback">
          <el-input
            v-model="feedbackForm.feedback"
            type="textarea"
            :rows="4"
            placeholder="请输入反馈内容"
          />
        </el-form-item>
        <el-form-item label="反馈时间" prop="feedbackTime">
          <el-date-picker
            v-model="feedbackForm.feedbackTime"
            type="datetime"
            placeholder="选择反馈时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="feedbackDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleFeedbackSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 处理确认对话框 -->
    <el-dialog
      title="标记为已处理"
      :visible.sync="processDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="processForm"
        :model="processForm"
        label-width="100px"
      >
        <el-form-item label="处理备注">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleProcessSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 转警详情抽屉 -->
    <el-drawer
      title="转警详情"
      :visible.sync="detailDrawerVisible"
      size="500px"
      :with-header="true"
    >
      <div v-if="selectedTransfer" class="transfer-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="警情编号">
            {{ selectedTransfer.alertNo || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="转警状态">
            <el-tag :type="getTransferStatusTagType(selectedTransfer.status)" size="small">
              {{ getTransferStatusLabel(selectedTransfer.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="目标单位">
            {{ selectedTransfer.targetOrg || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ selectedTransfer.contact || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <span class="phone-number">{{ selectedTransfer.mobile || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="转警说明">
            <div class="summary-text">{{ selectedTransfer.transferDesc || '暂无' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="转警时间">
            {{ formatDateTime(selectedTransfer.transferTime) }}
          </el-descriptions-item>
          <el-descriptions-item 
            v-if="selectedTransfer.feedback" 
            label="反馈内容"
          >
            <div class="summary-text">{{ selectedTransfer.feedback }}</div>
          </el-descriptions-item>
          <el-descriptions-item 
            v-if="selectedTransfer.feedbackTime" 
            label="反馈时间"
          >
            {{ formatDateTime(selectedTransfer.feedbackTime) }}
          </el-descriptions-item>
          <el-descriptions-item 
            v-if="selectedTransfer.remark" 
            label="备注"
          >
            <div class="summary-text">{{ selectedTransfer.remark }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listTransfers, getTransfer, recordFeedback, markProcessed, getAlert } from '@/api/duty/alert'
import { formatDateTime as formatDateTimeHelper } from '../utils/dateHelpers'

export default {
  name: 'TransferManagementPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      transferList: [],
      loading: false,
      statusFilter: '', // 状态筛选
      currentPage: 1,
      pageSize: 20,
      total: 0,
      // 反馈对话框
      feedbackDialogVisible: false,
      feedbackForm: {
        feedback: '',
        feedbackTime: null
      },
      feedbackRules: {
        feedback: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }]
      },
      currentFeedbackTransfer: null,
      // 处理对话框
      processDialogVisible: false,
      processForm: {
        remark: ''
      },
      currentProcessTransfer: null,
      // 详情抽屉
      detailDrawerVisible: false,
      selectedTransfer: null,
      submitting: false
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadTransfers()
      } else {
        // 关闭时重置（但不重置 selectedTransfer，因为抽屉可能还在显示）
        this.currentPage = 1
        this.statusFilter = ''
        // 不在这里重置 selectedTransfer，让抽屉自己管理
      }
    },
    // 监听抽屉关闭事件，重置 selectedTransfer
    detailDrawerVisible(newVal) {
      if (!newVal) {
        // 抽屉关闭时重置
        this.selectedTransfer = null
      }
    }
  },
  methods: {
    /**
     * 加载转警列表
     */
    async loadTransfers() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        if (this.statusFilter) {
          params.status = this.statusFilter
        }
        
        const res = await listTransfers(params)
        
        if (res.code === 200) {
          const transfers = res.rows || []
          // 需要获取每个转警记录对应的警情编号
          // 由于后端可能没有直接返回 alertNo，我们需要通过 alertId 查询
          const transfersWithAlertNo = await Promise.all(
            transfers.map(async (transfer) => {
              if (transfer.alertId) {
                try {
                  const alertRes = await getAlert(transfer.alertId)
                  if (alertRes.code === 200 && alertRes.data) {
                    return {
                      ...transfer,
                      alertNo: alertRes.data.alertNo
                    }
                  }
                } catch (error) {
                  console.warn(`获取警情 ${transfer.alertId} 信息失败:`, error)
                }
              }
              return transfer
            })
          )
          this.transferList = transfersWithAlertNo
          this.total = res.total || 0
        }
      } catch (error) {
        console.error('获取转警列表失败:', error)
        this.$message.error('获取转警列表失败，请稍后重试')
        this.transferList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 处理状态筛选变化
     */
    handleStatusFilterChange() {
      this.currentPage = 1
      this.loadTransfers()
    },
    
    /**
     * 处理分页变化
     */
    handlePageChange(page) {
      this.currentPage = page
      this.loadTransfers()
    },
    
    /**
     * 选择转警记录（查看详情）
     */
    async handleSelect(transfer) {
      // 加载完整详情
      try {
        const res = await getTransfer(transfer.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.selectedTransfer = res.data
          this.detailDrawerVisible = true
          // 使用 $nextTick 确保抽屉先打开，然后再关闭弹窗
          this.$nextTick(() => {
            this.handleClose()
          })
        }
      } catch (error) {
        console.error('获取转警详情失败:', error)
        this.$message.error('获取转警详情失败，请稍后重试')
      }
    },
    
    /**
     * 录入反馈
     */
    handleFeedback(transfer) {
      this.currentFeedbackTransfer = transfer
      this.feedbackForm = {
        feedback: '',
        feedbackTime: null
      }
      this.feedbackDialogVisible = true
    },
    
    /**
     * 提交反馈
     */
    async handleFeedbackSubmit() {
      this.$refs.feedbackForm.validate(async (valid) => {
        if (!valid) return
        
        if (!this.currentFeedbackTransfer) return
        
        this.submitting = true
        try {
          const data = {
            feedback: this.feedbackForm.feedback,
            feedbackTime: this.feedbackForm.feedbackTime || new Date().toISOString().replace('T', ' ').substring(0, 19)
          }
          const res = await recordFeedback(this.currentFeedbackTransfer.id, data)
          
          if (res.code === 200) {
            this.$message.success('反馈已录入')
            this.feedbackDialogVisible = false
            this.currentFeedbackTransfer = null
            // 刷新列表
            this.loadTransfers()
          } else {
            this.$message.error(res.msg || '反馈录入失败')
          }
        } catch (error) {
          console.error('反馈录入失败:', error)
          this.$message.error('反馈录入失败，请稍后重试')
        } finally {
          this.submitting = false
        }
      })
    },
    
    /**
     * 标记为已处理
     */
    handleProcess(transfer) {
      this.currentProcessTransfer = transfer
      this.processForm = {
        remark: ''
      }
      this.processDialogVisible = true
    },
    
    /**
     * 提交处理
     */
    async handleProcessSubmit() {
      if (!this.currentProcessTransfer) return
      
      this.submitting = true
      try {
        const data = this.processForm.remark ? { remark: this.processForm.remark } : null
        const res = await markProcessed(this.currentProcessTransfer.id, data)
        
        if (res.code === 200) {
          this.$message.success('转警记录已标记为已处理')
          this.processDialogVisible = false
          this.currentProcessTransfer = null
          // 刷新列表
          this.loadTransfers()
        } else {
          this.$message.error(res.msg || '标记操作失败')
        }
      } catch (error) {
        console.error('标记操作失败:', error)
        this.$message.error('标记操作失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.$emit('close')
    },
    
    /**
     * 获取转警状态标签
     */
    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] || ''
    },
    
    /**
     * 格式化日期时间
     */
    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>
.transfer-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;
}

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

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

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

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

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

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

.transfer-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;
  }
}

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

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

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

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

.transfer-label {
  color: #909399;
  min-width: 70px;
}

.transfer-value {
  color: #606266;
  flex: 1;
}

.transfer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

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

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

.transfer-detail {
  padding: 20px;
}

.phone-number {
  color: #409eff;
  font-weight: 500;
}

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

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