<template>
  <div class="danger-report-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">隐患上报管理</h2>
      <div class="header-actions">
<!--        <el-button @click="handleExport">-->
<!--          <Icon icon="mdi:download" class="mr-4px" />-->
<!--          导出Excel-->
<!--        </el-button>-->
        <el-button type="primary" @click="handleAdd">
          <Icon icon="mdi:plus" class="mr-4px" />
          新增隐患
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="发现人">
          <el-input v-model="searchForm.discoverer" placeholder="请输入发现人姓名" clearable />
        </el-form-item>
        <el-form-item label="安全员">
          <el-input v-model="searchForm.safetyOfficer" placeholder="请输入安全员姓名" clearable />
        </el-form-item>
        <el-form-item label="发现时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <Icon icon="mdi:magnify" class="mr-4px" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <Icon icon="mdi:refresh" class="mr-4px" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="discoverer" label="发现人" width="120" />
        <el-table-column prop="discoverTime" label="发现时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.discoverTime, 'yyyy-MM-dd HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="位置" width="200" />
        <el-table-column prop="description" label="问题描述" min-width="300" show-overflow-tooltip />
        <el-table-column prop="safetyOfficer" label="安全员" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="images" label="现场照片" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.images && row.images.length > 0"
              type="text"
              @click="handleViewImages(row)"
            >
              查看照片 ({{ row.images.length }})
            </el-button>
            <span v-else class="text-gray-400">无照片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">
              <Icon icon="mdi:pencil" class="mr-4px" />
              编辑
            </el-button>
            <el-button type="text" @click="handleView(row)">
              <Icon icon="mdi:eye" class="mr-4px" />
              查看
            </el-button>
            <el-button type="text" @click="handleDelete(row)" class="text-red-500">
              <Icon icon="mdi:delete" class="mr-4px" />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发现人" prop="discoverer">
              <el-input v-model="formData.discoverer" placeholder="请输入发现人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发现时间" prop="discoverTime">
              <el-date-picker
                v-model="formData.discoverTime"
                type="datetime"
                placeholder="请选择发现时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全员" prop="safetyOfficer">
              <el-select
                v-model="formData.safetyOfficer"
                placeholder="请选择安全员"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="officer in safetyOfficers"
                  :key="officer.value"
                  :label="officer.label"
                  :value="officer.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="待处理" value="pending" />
                <el-option label="处理中" value="processing" />
                <el-option label="已处理" value="completed" />
                <el-option label="已关闭" value="closed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入隐患位置" />
        </el-form-item>

        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述隐患问题"
          />
        </el-form-item>

        <el-form-item label="现场照片">
          <div class="upload-container">
            <el-upload
              ref="uploadRef"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :http-request="customUpload"
              list-type="picture-card"
              :limit="5"
              accept="image/*"
              drag
            >
              <div class="upload-area">
                <Icon icon="mdi:camera" class="upload-icon" />
                <div class="upload-text">
                  <div>拖拽或单击后粘贴图片</div>
                  <div class="upload-hint">单张20MB以内</div>
                </div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="隐患详情"
      width="600px"
    >
      <div v-if="viewData" class="view-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="发现人">{{ viewData.discoverer }}</el-descriptions-item>
          <el-descriptions-item label="发现时间">
            {{ formatTime(viewData.discoverTime, 'yyyy-MM-dd HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="安全员">{{ viewData.safetyOfficer }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(viewData.status)">
              {{ getStatusText(viewData.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="位置" :span="2">{{ viewData.location }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ viewData.description }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="viewData.images && viewData.images.length > 0" class="image-gallery">
          <h4>现场照片</h4>
          <el-image
            v-for="(image, index) in viewData.images"
            :key="index"
            :src="image.url"
            :preview-src-list="viewData.images.map(img => img.url)"
            :initial-index="index"
            fit="cover"
            class="gallery-image"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 图片查看对话框 -->
    <el-dialog
      v-model="imageDialogVisible"
      title="现场照片"
      width="800px"
    >
      <div v-if="selectedImages" class="image-viewer">
        <el-carousel :interval="4000" type="card" height="400px">
          <el-carousel-item v-for="(image, index) in selectedImages" :key="index">
            <el-image
              :src="image.url"
              fit="contain"
              style="width: 100%; height: 100%"
            />
          </el-carousel-item>
        </el-carousel>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatTime } from '@/utils'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import type { DangerReport, SearchForm, Pagination, SafetyOfficer, FormData, DangerImage } from './types'
import * as DangerReportApi from '@/api/safe/danger'
import * as DangerImageApi from '@/api/safe/danger/image'

defineOptions({ name: 'DangerReport' })

// 搜索表单
const searchForm = reactive<SearchForm>({
  discoverer: '',
  safetyOfficer: '',
  dateRange: [],
  status: ''
})

// 分页
const pagination = reactive<Pagination>({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref<DangerReport[]>([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const imageDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formData = reactive<FormData>({
  id: '',
  discoverer: '',
  discoverTime: new Date(),
  location: '',
  description: '',
  safetyOfficer: '',
  status: 'pending',
  images: []
})

// 表单验证规则
const formRules = {
  discoverer: [
    { required: true, message: '请输入发现人姓名', trigger: 'blur' }
  ],
  discoverTime: [
    { required: true, message: '请选择发现时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入位置', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' }
  ],
  safetyOfficer: [
    { required: true, message: '请选择安全员', trigger: 'change' }
  ]
}

// 文件上传相关
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>([])

// 查看相关
const viewData = ref<DangerReport | null>(null)
const selectedImages = ref<DangerImage[]>([])

// 安全员列表
const safetyOfficers: SafetyOfficer[] = [
  { label: '张三', value: '张三' },
  { label: '李四', value: '李四' },
  { label: '王五', value: '王五' },
  { label: '赵六', value: '赵六' }
]

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增隐患' : '编辑隐患'
})

// 方法
const getStatusType = (status: string) => {
  const statusMap: Record<string, 'warning' | 'primary' | 'success' | 'info'> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已处理',
    closed: '已关闭'
  }
  return statusMap[status as keyof typeof statusMap] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    discoverer: '',
    safetyOfficer: '',
    dateRange: [],
    status: ''
  })
  handleSearch()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.size,
      discoverer: searchForm.discoverer || undefined,
      safetyOfficer: searchForm.safetyOfficer || undefined,
      status: searchForm.status || undefined,
      discoverTime: searchForm.dateRange?.length === 2 ? searchForm.dateRange : undefined
    }

    const res = await DangerReportApi.getDangerReportPage(params)
    tableData.value = res.list
    pagination.total = res.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 分页
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  fileList.value = []
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  Object.assign(formData, {
    ...row,
    discoverTime: row.discoverTime ? new Date(row.discoverTime) : new Date()
  })
  fileList.value = (row.images || []).map((img: any, index: number) => ({
    name: img.name || `image_${index}.jpg`,
    url: img.url,
    status: 'success',
    uid: `existing_${index}`
  }))
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  viewData.value = row
  viewDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条隐患记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await DangerReportApi.deleteDangerReport(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查看图片
const handleViewImages = (row: any) => {
  selectedImages.value = row.images || []
  imageDialogVisible.value = true
}

// 导出Excel
const handleExport = async () => {
  try {
    const params = {
      discoverer: searchForm.discoverer || undefined,
      safetyOfficer: searchForm.safetyOfficer || undefined,
      status: searchForm.status || undefined,
      discoverTime: searchForm.dateRange?.length === 2 ? searchForm.dateRange : undefined
    }
    await DangerReportApi.exportDangerReport(params)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 表单相关
const resetForm = () => {
  Object.assign(formData, {
    id: '',
    discoverer: '',
    discoverTime: new Date(),
    location: '',
    description: '',
    safetyOfficer: '',
    status: 'pending',
    images: []
  })
  if (dialogType.value === 'add') {
    fileList.value = []
  }
  formRef.value?.clearValidate()
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 收集有效的图片信息
    const validImages = fileList.value
      .filter(file => file.url && file.url.trim() !== '')
      .map(file => ({
        url: file.url!,
        name: file.name || '未命名图片'
      }))

    const submitData = {
      ...formData,
      id: formData.id ? Number(formData.id) : undefined,
      discoverTime: formData.discoverTime ? formatTime(formData.discoverTime, 'yyyy-MM-dd HH:mm:ss') : formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
      images: validImages
    }

    // 调试日志
    console.log('提交的数据:', submitData)
    console.log('fileList:', fileList.value)
    console.log('validImages:', validImages)
    console.log('images:', submitData.images)

    if (dialogType.value === 'add') {
      await DangerReportApi.createDangerReport(submitData)
      ElMessage.success('新增成功')
    } else {
      await DangerReportApi.updateDangerReport(submitData as DangerReportApi.DangerReportUpdateReqVO)
      ElMessage.success('编辑成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 文件上传相关
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }

  return true
}

const handleRemove: UploadProps['onRemove'] = async (file, fileList) => {
  try {
    if (file.url && file.url.startsWith('http')) {
      const urlParts = file.url.split('/')
      const year = urlParts[urlParts.length - 4]
      const month = urlParts[urlParts.length - 3]
      const day = urlParts[urlParts.length - 2]
      const filename = urlParts[urlParts.length - 1]
      const datePath = `${year}/${month}/${day}`
      await DangerImageApi.deleteDangerImage({
        datePath,
        filename
      })
    }
  } catch (error) {
    console.error('删除文件失败:', error)
    ElMessage.error('删除文件失败')
  }
  debugger;
  // 前端 fileList 兜底同步删除
  const idx = fileList.value.findIndex(f => f.uid === file.uid)
  if (idx !== -1) {
    fileList.value.splice(idx, 1)
  }
}

const customUpload: UploadProps['httpRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  try {
    const response = await DangerImageApi.uploadDangerImage(file)
    // 检查 fileList 是否已存在该文件
    const exists = fileList.value.some(f => f.uid === file.uid)
    if (!exists) {
      fileList.value.push({
        name: response.name || file.name,
        url: response.url,
        status: 'success',
        uid: file.uid
      })
    }
    ElMessage.success('上传成功')
    onSuccess({
      url: response.url,
      name: response.name || file.name
    })
  } catch (error) {
    ElMessage.error('上传失败')
    onError({
      status: 500,
      method: 'POST',
      url: '',
      name: 'UploadError',
      message: error instanceof Error ? error.message : '上传失败'
    })
  }
}

// 生命周期
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.danger-report-container {
  padding: 20px;
}

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

.header-actions {
  display: flex;
  gap: 12px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.upload-container {
  width: 100%;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 32px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  text-align: center;
  color: #606266;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  text-align: right;
}

.view-content {
  padding: 20px 0;
}

.image-gallery {
  margin-top: 20px;
}

.image-gallery h4 {
  margin-bottom: 16px;
  color: #303133;
}

.gallery-image {
  width: 120px;
  height: 80px;
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 4px;
}

.image-viewer {
  text-align: center;
}

:deep(.el-carousel__item) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
</style>
