<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="地址" prop="address">
            <el-input placeholder="请输入地址" v-model="queryParams.address" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.QHSE_HAZARD_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button @click="handleAdd" type="primary"
              ><Icon icon="ep:plus" class="mr-5px" />新增</el-button
            >
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> {{ t('devicePerson.search') }}</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('devicePerson.reset') }}</el-button
            >
            <el-button @click="handleExport" type="success" plain :loading="exportLoading"
              ><Icon icon="ep:download" class="mr-5px" /> 导出</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap class="flex-1 overflow-hidden mt-15px">
        <el-table
          v-loading="loading"
          :data="list"
          :stripe="true"
          height="calc(85vh - 130px)"
          :show-overflow-tooltip="true"
        >
          <el-table-column :label="t('monitor.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>

          <el-table-column label="单位" align="center" prop="deptName" width="100" />

          <el-table-column label="地点" align="center" width="150" prop="address" />

          <el-table-column label="存在问题" align="center" prop="problem" width="150" />

          <el-table-column label="附件" align="center" prop="hazardFile">
            <template #default="{ row }">
              <el-link
                v-if="row.hazardFile"
                :underline="false"
                type="primary"
                size="small"
                @click="viewFile(row.hazardFile)"
                >查看</el-link
              >
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column label="整改情况" align="center" prop="rectifyDesc" width="150" />

          <el-table-column label="整改附件" align="center" prop="rectifyFile">
            <template #default="{ row }">
              <el-link
                v-if="row.rectifyFile"
                :underline="false"
                type="primary"
                size="small"
                @click="viewFile(row.rectifyFile)"
                >查看</el-link
              >
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="排查时间" align="center" min-width="150">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.QHSE_HAZARD_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>

          <el-table-column label="备注" align="center" prop="remark" width="120" />

          <el-table-column
            :label="t('devicePerson.operation')"
            align="center"
            fixed="right"
            min-width="150px"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 'todo'"
                link
                type="primary"
                @click="handleFix(scope.row)"
              >
                整改
              </el-button>
              <el-button
                v-if="scope.row.status === 'todo'"
                link
                type="primary"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 新增/编辑证书对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="600px"
    destroy-on-close
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="地点" prop="address">
        <el-input v-model="formData.address" placeholder="请输入地点" />
      </el-form-item>

      <el-form-item label="存在问题" prop="problem">
        <el-input
          type="textarea"
          :rows="2"
          v-model="formData.problem"
          placeholder="请输入存在问题"
        />
      </el-form-item>

      <el-form-item label="照片" prop="hazardFile">
        <UploadFile
          v-model="formData.hazardFile"
          :file-type="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'png', 'jpeg']"
          :limit="3"
          :file-size="100"
          class="min-w-80px"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="formData.remark"
          :rows="2"
          placeholder="请输入备注"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
    </template>
  </el-dialog>

  <!-- 整改 -->
  <el-dialog
    title="整改"
    v-model="fixdDialogVisible"
    width="600px"
    destroy-on-close
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="整改描述" prop="rectifyDesc">
        <el-input
          type="textarea"
          :rows="2"
          v-model="formData.rectifyDesc"
          placeholder="请输入整改描述"
        />
      </el-form-item>

      <el-form-item label="整改附件" prop="rectifyFile">
        <UploadFile
          v-model="formData.rectifyFile"
          :file-type="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'png', 'jpeg']"
          :limit="3"
          :file-size="100"
          class="min-w-80px"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog2">取 消</el-button>
      <el-button type="primary" @click="submitFix" :loading="submitLoading">确 定</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogFileView" title="附件" width="500">
    <div
      v-for="(file, index) in fileList"
      :key="index"
      class="flex items-center justify-between mt-5"
    >
      <span class="file-name-text">{{ extractFileName(file) }}</span>
      <div>
        <el-button link type="primary" @click="viewFileInfo(file)">
          <Icon icon="ep:view" class="mr-2px" />查看</el-button
        >
        <el-button link type="primary" @click="handleDownload(file)">
          <Icon icon="ep:download" class="mr-2px" />下载</el-button
        >
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer mt-10">
        <el-button type="primary" @click="dialogFileView = false"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <FilePreviewDialog
    v-model="filePreviewVisible"
    :title="filePreviewTitle"
    :urls="filePreviewUrls"
  />
</template>

<script setup lang="ts">
import { IotHiddenApi } from '@/api/pms/qhse/index'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { ElMessageBox, ElMessage } from 'element-plus'
const deptList2 = ref<Tree[]>([]) // 树形结构
import { formatDate } from '@/utils/formatTime'

import UploadFile from '@/components/UploadFile/src/UploadFile.vue'
import FilePreviewDialog from '@/components/FilePreview/src/FilePreviewDialog.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

import { selectedDeptsEmployee } from '@/api/system/user'

defineOptions({ name: 'IotQHSECertificate' })

const loading = ref(true) // 列表的加载中
const formLoading = ref(false) // 表单加载中
const submitLoading = ref(false) // 提交按钮加载中
const exportLoading = ref(false) // 导出按钮加载中
const isLeftContentCollapsed = ref(false)

const { t } = useI18n()

const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: '',
  deptId: '',
  address: ''
})
const queryFormRef = ref(null) // 搜索的表单

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 整改对话框
let fixdDialogVisible = ref(false)

// 文件预览
const filePreviewVisible = ref(false)
const filePreviewTitle = ref('文件预览')
const filePreviewUrls = ref<string[]>([])

// 表单相关
const formRef = ref()
const formData = ref({
  remark: '', // 备注
  deptId: '', // 部门id
  address: '',
  problem: '',
  hazardFile: '',
  rectifyDesc: '',
  rectifyFile: '',
  status: ''
})

// 表单验证规则
const formRules = {
  deptId: [{ required: true, message: '所在部门不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
  problem: [{ required: true, message: '存在问题不能为空', trigger: 'blur' }],
  rectifyDesc: [{ required: true, message: '整改描述不能为空', trigger: 'blur' }],
  rectifyFile: [{ required: true, message: '整改附件不能为空', trigger: 'blur' }],
  hazardFile: [{ required: true, message: '照片不能为空', trigger: 'blur' }]
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotHiddenApi.getHiddenList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleExport = async () => {
  try {
    exportLoading.value = true
    const response = await IotHiddenApi.exportHidden(queryParams)
    downloadFile(response)
    exportLoading.value = false
  } catch (error) {
    ElMessage.error('导出失败，请重试')
    console.error('导出错误:', error)
  } finally {
    exportLoading.value = false
  }
}

/** 首页处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.deptId = ''
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 显示新增对话框
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增隐患排查'
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '修改'

  formData.value = {
    ...row,
    // 确保日期字段正确处理
    issueDate: row.issueDate ? ensureMillisecondTimestamp(row.issueDate) : null,
    validityPeriod: row.validityPeriod ? ensureMillisecondTimestamp(row.validityPeriod) : null
  }

  dialogVisible.value = true
}

let currentFixId = ref('')
const handleFix = (row) => {
  fixdDialogVisible.value = true
  currentFixId.value = row.id
}

// 查看证书图片
const viewHazardFile = (value: string) => {
  filePreviewTitle.value = '隐患附件'
  filePreviewUrls.value = normalizeUrls(value)
  filePreviewVisible.value = true
}

const viewRectifyFile = (value: string) => {
  filePreviewTitle.value = '整改附件'
  filePreviewUrls.value = normalizeUrls(value)
  filePreviewVisible.value = true
}

const normalizeUrls = (value: string) => {
  if (!value) return []
  return value
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean)
}

// 确保时间戳是毫秒级的
const ensureMillisecondTimestamp = (timestamp) => {
  let time = Number(timestamp)
  if (time < 10000000000) {
    // 秒级时间戳转为毫秒级
    return time * 1000
  }
  return time
}

//删除证书
const handleDelete = async (id: number) => {
  ElMessageBox.confirm('确定要删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await IotHiddenApi.deleteHidden(id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    remark: '', // 备注
    deptId: '', // 部门id
    address: '',
    problem: '',
    hazardFile: '',
    rectifyDesc: '',
    rectifyFile: '',
    status: ''
  }
  formRef.value?.clearValidate()
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

const closeDialog2 = () => {
  fixdDialogVisible.value = false
  resetForm()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

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

    // 准备提交数据
    const submitData = {
      ...formData.value
    }

    if (isEdit.value) {
      // 编辑
      await IotHiddenApi.updateHidden(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      await IotHiddenApi.createHidden(submitData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  } finally {
    submitLoading.value = false
  }
}

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

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

    // 准备提交数据
    const submitData = {
      ...formData.value
    }

    await IotHiddenApi.rectifyHidden({
      id: currentFixId.value,
      rectifyDesc: submitData.rectifyDesc,
      rectifyFile: submitData.rectifyFile
    })

    fixdDialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  } finally {
    submitLoading.value = false
  }
}

// 下载文件函数
const handleDownload = async (url) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    const downloadUrl = window.URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = url.split('/').pop() // 自动获取文件名‌:ml-citation{ref="3" data="citationList"}
    link.click()

    URL.revokeObjectURL(downloadUrl)
  } catch (error) {
    console.error('下载失败:', error)
  }
}

let userList = ref([])
const handleDeptChange = async (value) => {
  const res = await selectedDeptsEmployee({
    deptIds: value
  })

  userList.value = res
  console.log('value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', userList.value)
}

let dialogFileView = ref(false)
let fileList = ref([])
const viewFile = (file) => {
  fileList.value = file.split(',')
  dialogFileView.value = true
  // window.open(file)
}

const viewFileInfo = (file) => {
  window.open(
    'http://doc.deepoil.cc:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(file))
  )
}

const extractFileName = (url: string): string => {
  try {
    // 移除查询参数和哈希
    const cleanUrl = url.split('?')[0].split('#')[0]
    // 获取最后一个斜杠后的内容
    const parts = cleanUrl.split('/')
    const fileName = parts[parts.length - 1]
    // URL 解码
    return decodeURIComponent(fileName) || url
  } catch {
    // 如果解析失败，返回原始 URL
    return url
  }
}

onMounted(async () => {
  getList()
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>

<style scoped>
::deep(.el-tree--highlight-current) {
  height: 200px !important;
}
::deep(.el-transfer-panel__body) {
  height: 700px !important;
}
.image-preview {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
