<template>
  <div>
    <!-- Approval Workbench Popup (non-modal, bottom-right) -->
    <div 
      v-if="visible" 
      class="approval-popup"
      @click.stop
    >
      <div class="approval-popup-header">
        <span class="approval-popup-title">审核工作台</span>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="handleClose"
          class="approval-popup-close"
        ></el-button>
      </div>
      
      <!-- 筛选区域 -->
      <div class="approval-popup-filters">
        <el-select
          v-model="typeFilter"
          placeholder="全部类型"
          size="small"
          clearable
          style="width: 100%"
          @change="handleTypeFilterChange"
        >
          <el-option label="全部类型" value=""></el-option>
          <el-option label="转警" value="transfer"></el-option>
          <el-option label="转事件" value="convert"></el-option>
        </el-select>
      </div>
      
      <!-- 内容区域 -->
      <div class="approval-popup-body">
        <div v-loading="loading" class="approval-list">
          <div 
            v-for="item in approvalList" 
            :key="`${item.type}-${item.id}`"
            class="approval-item"
            @click="handleSelect(item)"
          >
            <div class="approval-header">
              <div class="approval-type-badge">
                <el-tag 
                  :type="item.type === 'transfer' ? 'warning' : 'success'"
                  size="mini"
                >
                  {{ item.type === 'transfer' ? '转警' : '转事件' }}
                </el-tag>
                <span class="approval-alert-no">{{ item.alertNo || '未知警情' }}</span>
              </div>
              <el-tag size="mini" type="warning">待审核</el-tag>
            </div>
            <div class="approval-info">
              <div v-if="item.type === 'transfer'" class="approval-row">
                <span class="approval-label">目标单位：</span>
                <span class="approval-value">{{ item.targetOrg || '暂无' }}</span>
              </div>
              <div v-if="item.type === 'transfer'" class="approval-row">
                <span class="approval-label">联系人：</span>
                <span class="approval-value">{{ item.contact || '暂无' }}</span>
              </div>
              <div v-if="item.type === 'transfer'" class="approval-row">
                <span class="approval-label">转警说明：</span>
                <span class="approval-value">{{ item.transferDesc || '暂无' }}</span>
              </div>
              <div v-if="item.type === 'convert'" class="approval-row">
                <span class="approval-label">转事件原因：</span>
                <span class="approval-value">{{ item.convertReason || '暂无' }}</span>
              </div>
              <div class="approval-row">
                <span class="approval-label">申请时间：</span>
                <span class="approval-value">{{ formatDateTime(item.applyTime) }}</span>
              </div>
            </div>
            <div class="approval-actions" @click.stop>
              <el-button
                type="text"
                size="mini"
                @click="handleApprove(item)"
              >
                审核通过
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="handleReject(item)"
              >
                审核驳回
              </el-button>
            </div>
          </div>
          <el-empty v-if="!loading && approvalList.length === 0" description="暂无待审核申请" :image-size="80"></el-empty>
        </div>
      </div>
    </div>

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

    <!-- 审核通过对话框 -->
    <el-dialog
      :title="`审核通过${currentItem && currentItem.type === 'transfer' ? '转警' : '转事件'}申请`"
      :visible.sync="approveDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="approveForm"
        :model="approveForm"
        label-width="100px"
      >
        <el-form-item label="审核意见">
          <el-input
            v-model="approveForm.reviewComment"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleApproveSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 审核驳回对话框 -->
    <el-dialog
      :title="`审核驳回${currentItem && currentItem.type === 'transfer' ? '转警' : '转事件'}申请`"
      :visible.sync="rejectDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="rejectForm"
        :model="rejectForm"
        label-width="100px"
      >
        <el-form-item label="驳回意见">
          <el-input
            v-model="rejectForm.reviewComment"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回意见（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleRejectSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer
      :title="detailDrawerTitle"
      :visible.sync="detailDrawerVisible"
      size="500px"
      :with-header="true"
    >
      <div v-if="selectedItem" class="approval-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="类型">
            <el-tag :type="selectedItem.type === 'transfer' ? 'warning' : 'success'" size="small">
              {{ selectedItem.type === 'transfer' ? '转警' : '转事件' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="警情编号">
            {{ selectedItem.alertNo || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'transfer'" label="目标单位">
            {{ selectedItem.targetOrg || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'transfer'" label="联系人">
            {{ selectedItem.contact || '暂无' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'transfer'" label="联系电话">
            <span class="phone-number">{{ selectedItem.mobile || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'transfer'" label="转警说明">
            <div class="summary-text">{{ selectedItem.transferDesc || '暂无' }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'convert'" label="转事件原因">
            <div class="summary-text">{{ selectedItem.convertReason || '暂无' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDateTime(selectedItem.applyTime) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'transfer'" label="申请人">
            {{ selectedItem.operatorName || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedItem.type === 'convert'" label="操作人">
            {{ selectedItem.operatorName || '未知' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { 
  listTransfers, 
  getTransfer, 
  approveTransfer, 
  rejectTransfer,
  listConverts, 
  getConvert, 
  approveConvert, 
  rejectConvert,
  getAlert 
} from '@/api/duty/alert'
import { formatDateTime as formatDateTimeHelper } from '../utils/dateHelpers'

export default {
  name: 'ApprovalWorkbenchPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      approvalList: [], // 合并后的待审核列表
      loading: false,
      typeFilter: '', // 类型筛选：'' | 'transfer' | 'convert'
      // 审核通过对话框
      approveDialogVisible: false,
      approveForm: {
        reviewComment: ''
      },
      currentItem: null,
      // 审核驳回对话框
      rejectDialogVisible: false,
      rejectForm: {
        reviewComment: ''
      },
      // 详情抽屉
      detailDrawerVisible: false,
      selectedItem: null,
      submitting: false
    }
  },
  computed: {
    detailDrawerTitle() {
      if (!this.selectedItem) return '详情'
      return this.selectedItem.type === 'transfer' ? '转警详情' : '转事件详情'
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadApprovals()
      } else {
        // 关闭时重置
        this.typeFilter = ''
        this.approvalList = []
      }
    },
    // 监听抽屉关闭事件，重置 selectedItem
    detailDrawerVisible(newVal) {
      if (!newVal) {
        this.selectedItem = null
      }
    }
  },
  methods: {
    /**
     * 加载待审核列表
     */
    async loadApprovals() {
      this.loading = true
      try {
        // 并行查询转警和转事件的待审核列表
        const [transferRes, convertRes] = await Promise.all([
          this.typeFilter === '' || this.typeFilter === 'transfer' 
            ? listTransfers({ status: 'pending_review', pageNum: 1, pageSize: 100 })
            : Promise.resolve({ code: 200, rows: [], total: 0 }),
          this.typeFilter === '' || this.typeFilter === 'convert'
            ? listConverts({ reviewStatus: 'pending', pageNum: 1, pageSize: 100 })
            : Promise.resolve({ code: 200, rows: [], total: 0 })
        ])
        
        const transfers = transferRes.code === 200 ? (transferRes.rows || []) : []
        const converts = convertRes.code === 200 ? (convertRes.rows || []) : []
        
        // 获取警情编号（转警）
        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
          })
        )
        
        // 获取警情编号（转事件）
        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
          })
        )
        
        // 合并列表并添加类型标识
        const transferItems = transfersWithAlertNo.map(transfer => ({
          type: 'transfer',
          id: transfer.id,
          alertId: transfer.alertId,
          alertNo: transfer.alertNo,
          targetOrg: transfer.targetOrg,
          contact: transfer.contact,
          mobile: transfer.mobile,
          transferDesc: transfer.transferDesc,
          applyTime: transfer.transferTime || transfer.createTime,
          operatorName: transfer.operatorName || transfer.createBy,
          raw: transfer
        }))
        
        const convertItems = convertsWithAlertNo.map(convert => ({
          type: 'convert',
          id: convert.id,
          alertId: convert.alertId,
          alertNo: convert.alertNo,
          convertReason: convert.convertReason,
          applyTime: convert.convertTime || convert.createTime,
          operatorName: convert.operatorName || convert.createBy,
          raw: convert
        }))
        
        // 合并并按时间倒序排序
        this.approvalList = [...transferItems, ...convertItems].sort((a, b) => {
          const timeA = new Date(a.applyTime).getTime()
          const timeB = new Date(b.applyTime).getTime()
          return timeB - timeA // 最新的在前
        })
      } catch (error) {
        console.error('获取待审核列表失败:', error)
        this.$message.error('获取待审核列表失败，请稍后重试')
        this.approvalList = []
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 处理类型筛选变化
     */
    handleTypeFilterChange() {
      this.loadApprovals()
    },
    
    /**
     * 选择申请项（查看详情）
     */
    async handleSelect(item) {
      // 加载完整详情
      try {
        let res
        if (item.type === 'transfer') {
          res = await getTransfer(item.id)
        } else {
          res = await getConvert(item.id)
        }
        
        if (res.code === 200 && res.data) {
          const data = res.data
          // 如果有 alertId，获取警情编号
          if (data.alertId) {
            try {
              const alertRes = await getAlert(data.alertId)
              if (alertRes.code === 200 && alertRes.data) {
                data.alertNo = alertRes.data.alertNo
              }
            } catch (error) {
              console.warn('获取警情信息失败:', error)
            }
          }
          
          // 构建详情对象
          this.selectedItem = {
            type: item.type,
            id: data.id,
            alertId: data.alertId,
            alertNo: data.alertNo,
            targetOrg: data.targetOrg,
            contact: data.contact,
            mobile: data.mobile,
            transferDesc: data.transferDesc,
            convertReason: data.convertReason,
            applyTime: item.type === 'transfer' 
              ? (data.transferTime || data.createTime)
              : (data.convertTime || data.createTime),
            operatorName: data.operatorName || data.createBy,
            raw: data
          }
          
          this.detailDrawerVisible = true
          // 使用 $nextTick 确保抽屉先打开，然后再关闭弹窗
          this.$nextTick(() => {
            this.handleClose()
          })
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败，请稍后重试')
      }
    },
    
    /**
     * 审核通过
     */
    handleApprove(item) {
      this.currentItem = item
      this.approveForm = {
        reviewComment: ''
      }
      this.approveDialogVisible = true
    },
    
    /**
     * 提交审核通过
     */
    async handleApproveSubmit() {
      if (!this.currentItem) return
      
      this.submitting = true
      try {
        const data = this.approveForm.reviewComment ? { reviewComment: this.approveForm.reviewComment } : null
        let res
        
        if (this.currentItem.type === 'transfer') {
          res = await approveTransfer(this.currentItem.id, data)
        } else {
          res = await approveConvert(this.currentItem.id, data)
        }
        
        if (res.code === 200) {
          const typeName = this.currentItem.type === 'transfer' ? '转警' : '转事件'
          this.$message.success(`${typeName}申请已审核通过`)
          this.approveDialogVisible = false
          // 在清空 currentItem 之前保存 alertId 和 itemType
          const alertId = this.currentItem.alertId
          const itemType = this.currentItem.type
          this.currentItem = null
          // 刷新列表
          this.loadApprovals()
          // 通知父组件刷新警情列表
          this.$emit('approved', { alertId, type: 'approve', itemType })
        } else {
          this.$message.error(res.msg || '审核操作失败')
        }
      } catch (error) {
        console.error('审核操作失败:', error)
        this.$message.error('审核操作失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    /**
     * 审核驳回
     */
    handleReject(item) {
      this.currentItem = item
      this.rejectForm = {
        reviewComment: ''
      }
      this.rejectDialogVisible = true
    },
    
    /**
     * 提交审核驳回
     */
    async handleRejectSubmit() {
      if (!this.currentItem) return
      
      this.submitting = true
      try {
        const data = this.rejectForm.reviewComment ? { reviewComment: this.rejectForm.reviewComment } : null
        let res
        
        if (this.currentItem.type === 'transfer') {
          res = await rejectTransfer(this.currentItem.id, data)
        } else {
          res = await rejectConvert(this.currentItem.id, data)
        }
        
        if (res.code === 200) {
          const typeName = this.currentItem.type === 'transfer' ? '转警' : '转事件'
          this.$message.success(`${typeName}申请已驳回`)
          this.rejectDialogVisible = false
          // 在清空 currentItem 之前保存 alertId 和 itemType
          const alertId = this.currentItem.alertId
          const itemType = this.currentItem.type
          this.currentItem = null
          // 刷新列表
          this.loadApprovals()
          // 通知父组件刷新警情列表
          this.$emit('approved', { alertId, type: 'reject', itemType })
        } else {
          this.$message.error(res.msg || '驳回操作失败')
        }
      } catch (error) {
        console.error('驳回操作失败:', error)
        this.$message.error('驳回操作失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.$emit('close')
    },
    
    /**
     * 格式化日期时间
     */
    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>
.approval-popup {
  position: fixed;
  bottom: 100px;
  right: 30px;
  width: 600px;
  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;
}

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

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

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

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

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

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

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

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

.approval-type-badge {
  display: flex;
  align-items: center;
  gap: 8px;
}

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

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

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

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

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

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

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

.approval-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;
}
</style>