<template>
  <div class="app-container gzcb-page">
    <!-- 搜索区 -->
    <div class="filter-panel">
      <div class="filter-form">
        <el-select v-model="searchForm.urgeStatus" placeholder="催办状态" clearable style="width:140px">
          <el-option label="待催办" value="待催办" />
          <el-option label="催办中" value="催办中" />
          <el-option label="已完成" value="已完成" />
        </el-select>
        <el-input v-model="searchForm.receiver" placeholder="目标接收人" clearable style="width:140px" />
        <el-input v-model="searchForm.eventNo" placeholder="事件编号" clearable style="width:160px" />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-panel">
      <el-table :data="tableData" border stripe style="width:100%" v-loading="loading">
        <el-table-column prop="eventNo" label="事件编号" width="140" />
        <el-table-column prop="summary" label="事件摘要" show-overflow-tooltip />
        <el-table-column prop="receiver" label="目标接收人" width="110" />
        <el-table-column prop="receiverDept" label="接收部门" width="120" />
        <el-table-column prop="urgeCount" label="催办次数" width="90" />
        <el-table-column prop="lastUrgeTime" label="最近催办时间" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status !== '已完成'" type="primary" link size="small" @click="handleUrge(row)">催办</el-button>
            <el-button type="primary" link size="small" @click="handleViewRecords(row)">查看记录</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 催办弹窗 -->
    <el-dialog v-model="urgeVisible" title="工作催办" width="600px" :close-on-click-modal="false">
      <el-form :model="urgeForm" :rules="urgeRules" ref="urgeFormRef" label-width="100px">
        <div class="section-title">事件信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件编号">{{ urgeForm.eventNo }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件摘要">{{ urgeForm.summary }}</el-form-item>
          </el-col>
        </el-row>
        <div class="section-title">接收人信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名">{{ urgeForm.receiver }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门">{{ urgeForm.receiverDept }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话">{{ urgeForm.receiverPhone }}</el-form-item>
          </el-col>
        </el-row>
        <div class="section-title">催办内容</div>
        <el-form-item label="催办方式" prop="methods">
          <el-checkbox-group v-model="urgeForm.methods">
            <el-checkbox label="电话" />
            <el-checkbox label="短信" />
            <el-checkbox label="系统消息" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="催办内容" prop="content">
          <el-input v-model="urgeForm.content" type="textarea" :rows="4" placeholder="请输入催办内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="urgeVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUrge">发送催办</el-button>
      </template>
    </el-dialog>

    <!-- 查看记录弹窗 -->
    <el-dialog v-model="recordsVisible" title="催办记录" width="700px" :close-on-click-modal="false">
      <div v-if="currentRow">
        <p style="margin-bottom:12px;font-weight:600">事件编号：{{ currentRow.eventNo }} | 事件摘要：{{ currentRow.summary }}</p>
        <el-table :data="currentRow.records" border stripe style="width:100%">
          <el-table-column prop="urgeTime" label="催办时间" width="160" />
          <el-table-column prop="method" label="催办方式" width="120" />
          <el-table-column prop="content" label="催办内容" show-overflow-tooltip />
          <el-table-column prop="result" label="结果" width="100">
            <template #default="{ row }">
              <el-tag :type="row.result === '已反馈' ? 'success' : 'info'" size="small">{{ row.result }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="recordsVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Gzcb">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEventUrgePage, deleteEventUrge, doUrge, getUrgeDetails } from '@/api/dispatch'

// ==================== 数据状态 ====================
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const searchForm = ref({ urgeStatus: '', receiver: '', eventNo: '' })
const pagination = ref({ page: 1, pageSize: 10 })

// ==================== 加载数据 ====================
async function loadData() {
  loading.value = true
  try {
    const params = {}
    if (searchForm.value.urgeStatus) params.status = searchForm.value.urgeStatus
    if (searchForm.value.receiver) params.receiver = searchForm.value.receiver
    if (searchForm.value.eventNo) params.eventNo = searchForm.value.eventNo
    const res = await getEventUrgePage(pagination.value.page, pagination.value.pageSize, params)
    tableData.value = res.data?.rows || res.data?.records || res.data || []
    total.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})

// ==================== 搜索筛选 ====================
function handleSearch() {
  pagination.value.page = 1
  loadData()
}

function handleReset() {
  searchForm.value = { urgeStatus: '', receiver: '', eventNo: '' }
  pagination.value.page = 1
  loadData()
}

// ==================== 分页 ====================
function handleSizeChange(val) {
  pagination.value.pageSize = val
  pagination.value.page = 1
  loadData()
}

function handleCurrentChange(val) {
  pagination.value.page = val
  loadData()
}

// ==================== 标签样式 ====================
function statusTagType(status) {
  if (status === '待催办') return 'warning'
  if (status === '催办中') return 'primary'
  if (status === '已完成') return 'success'
  return 'info'
}

// ==================== 催办 ====================
const urgeVisible = ref(false)
const urgeFormRef = ref(null)
const currentUrgeId = ref(null)
const urgeForm = ref({ eventNo: '', summary: '', receiver: '', receiverDept: '', receiverPhone: '', methods: [], content: '' })
const urgeRules = {
  methods: [{ required: true, message: '请选择催办方式', trigger: 'change', type: 'array' }],
  content: [{ required: true, message: '请输入催办内容', trigger: 'blur' }]
}

function handleUrge(row) {
  currentUrgeId.value = row.id
  urgeForm.value = {
    eventNo: row.eventNo,
    summary: row.summary || '',
    receiver: row.receiver,
    receiverDept: row.receiverDept,
    receiverPhone: row.receiverPhone,
    methods: [],
    content: '关于【' + (row.summary || '') + '】的处置进度，请尽快反馈处理情况。'
  }
  urgeVisible.value = true
}

async function confirmUrge() {
  try {
    await urgeFormRef.value.validate()
  } catch {
    return
  }
  try {
    await doUrge({
      urgeId: currentUrgeId.value,
      method: urgeForm.value.methods.join('、'),
      content: urgeForm.value.content
    })
    ElMessage.success('催办已发送')
    urgeVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('催办失败：' + (error.message || '未知错误'))
  }
}

// ==================== 删除 ====================
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确定要删除该催办记录吗？', '删除确认', { type: 'warning' })
    await deleteEventUrge(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

// ==================== 查看记录 ====================
const recordsVisible = ref(false)
const currentRow = ref(null)

async function handleViewRecords(row) {
  currentRow.value = row
  recordsVisible.value = true
  // 尝试从服务器加载催办详情
  try {
    const res = await getUrgeDetails(row.id)
    if (res.data) {
      currentRow.value = { ...row, records: res.data.records || res.data || [] }
    }
  } catch {
    // 如果加载失败，使用行内的 records 数据
  }
}
</script>

<style scoped>
.gzcb-page {
  padding: 16px;
  background: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.filter-panel {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.table-panel {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}

.pagination-wrap {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
}

:deep(.el-form-item__label) {
  color: #909399;
}

:deep(.el-form-item__content) {
  color: #303133;
}
</style>
