<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <div class="bg-white rounded-sm px-2 py-2">
        <!-- 搜索工作栏 -->
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="PTW编号" prop="ptwNo">
            <el-input placeholder="请输入PTW编号" v-model="queryParams.ptwNo" />
          </el-form-item>

          <el-form-item label="PTW序号" prop="ptwXh">
            <el-input placeholder="请输入PTW序号" v-model="queryParams.ptwXh" />
          </el-form-item>

          <el-form-item>
            <el-button @click="handleAdd" type="primary" v-hasPermi="['rq:qhse-ptw:create']"
              ><Icon icon="ep:plus" class="mr-5px" />新增</el-button
            >
            <el-button @click="handleQuery" v-hasPermi="['rq:qhse-ptw:query']"
              ><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"
              v-hasPermi="['rq:qhse-ptw:export']"
              ><Icon icon="ep:download" class="mr-5px" /> 导出</el-button
            >
          </el-form-item>
        </el-form>
      </div>

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

          <zm-table-column label="PTW编号" align="center" prop="ptwNo" fixed="left" />
          <zm-table-column label="PTW序号" align="center" prop="ptwXh" fixed="left" />

          <zm-table-column label="时间" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ formatDate(row.ptwTime).substring(0, 10) }}
            </template>
          </zm-table-column>

          <zm-table-column label="作业票类型" align="center" width="120">
            <template #default="{ row }">
              <dict-tag :type="DICT_TYPE.QHSE_PTW_TYPE" :value="row.ptwType" />
            </template>
          </zm-table-column>

          <zm-table-column label="作业分级" align="center">
            <template #default="{ row }">
              <dict-tag :type="DICT_TYPE.QHSE_PTW_GRADE" :value="row.ptwGrade" />
            </template>
          </zm-table-column>

          <zm-table-column
            label="作业地点"
            align="center"
            prop="workLocation"
            show-overflow-tooltip />
          <zm-table-column
            label="作业内容"
            align="center"
            prop="workContent"
            show-overflow-tooltip />

          <zm-table-column
            label="作业人员"
            align="center"
            prop="workPerson"
            show-overflow-tooltip />

          <zm-table-column label="监护人" align="center" prop="guardian" show-overflow-tooltip />
          <zm-table-column
            label="作业负责人"
            align="center"
            prop="workDuty"
            show-overflow-tooltip />
          <zm-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip />

          <zm-table-column label="附件" align="center" min-width="90">
            <template #default="{ row }">
              <el-button
                text
                v-if="row.file"
                :underline="false"
                type="primary"
                size="small"
                @click="viewFile(row.file)"
                >查看</el-button
              >
              <span v-else>-</span>
            </template>
          </zm-table-column>

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

          <zm-table-column
            label="备注"
            align="center"
            prop="remark"
            :show-overflow-tooltip="true" />

          <zm-table-column
            :label="t('devicePerson.operation')"
            align="center"
            fixed="right"
            min-width="120px"
            action>
            <template #default="scope">
              <el-button
                v-hasPermi="['rq:qhse-ptw:update']"
                link
                type="primary"
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                v-hasPermi="['rq:qhse-ptw:delete']"
                link
                type="danger"
                @click="handleDelete(scope.row.id)">
                删除
              </el-button>
            </template>
          </zm-table-column>
        </zm-table>

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

  <!-- 新增/编辑证书对话框 -->
  <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="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          :check-strictly="false"
          node-key="id"
          filterable
          placeholder="请选择所属队伍" />
      </el-form-item>
      <el-form-item label="JSA编号" prop="ptwNo">
        <el-input v-model="formData.ptwNo" disabled placeholder="选择JSA编号" style="width: 300px">
          <template #append>
            <el-link @click="selectJSA" :underline="false">选择</el-link>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="序号" prop="ptwXh">
        <el-input v-model="formData.ptwXh" placeholder="请输入序号" />
      </el-form-item>

      <el-form-item label="作业内容" prop="workContent">
        <el-input
          type="textarea"
          :rows="2"
          v-model="formData.workContent"
          placeholder="请输入作业内容" />
      </el-form-item>

      <!-- 作业票类型 -->
      <el-form-item label="作业票类型" prop="ptwType">
        <el-select v-model="formData.ptwType" placeholder="请选择作业票类型">
          <el-option
            v-for="item in getDictOptions(DICT_TYPE.QHSE_PTW_TYPE)"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item
        label="作业分级"
        prop="ptwGrade"
        v-if="
          formData.ptwType === 'donghuo' ||
          formData.ptwType === 'gaochu' ||
          formData.ptwType === 'diaozhuang'
        ">
        <el-select v-model="formData.ptwGrade" placeholder="请选择作业分级">
          <el-option
            v-for="item in getDictOptions(DICT_TYPE.QHSE_PTW_GRADE)"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="作业地点" prop="workLocation">
        <el-input v-model="formData.workLocation" placeholder="请输入作业地点" />
      </el-form-item>

      <el-form-item label="作业时间" prop="ptwTime">
        <el-date-picker
          v-model="formData.ptwTime"
          type="date"
          value-format="x"
          placeholder="请选择作业时间"
          style="width: 100%" />
      </el-form-item>

      <el-form-item label="作业人员" prop="workPerson">
        <el-input
          v-model="formData.workPerson"
          disabled
          placeholder="请选择作业人员"
          style="width: 300px">
          <template #append>
            <el-link @click="selectworkPerson('workPerson')" :underline="false">选择</el-link>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="监护人" prop="guardian">
        <el-input
          v-model="formData.guardian"
          disabled
          placeholder="请选择监护人"
          style="width: 300px">
          <template #append>
            <el-link @click="selectworkPerson('guardian')" :underline="false">选择</el-link>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="作业负责人" prop="workDuty">
        <el-input
          v-model="formData.workDuty"
          disabled
          placeholder="请选择作业负责人"
          style="width: 300px">
          <template #append>
            <el-link @click="selectworkPerson('workDuty')" :underline="false">选择</el-link>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="附件" prop="file">
        <UploadFile
          v-model="formData.file"
          :file-type="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'png', 'jpeg', 'bmp']"
          :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>
  </Dialog>

  <!-- 文件查看对话框 -->
  <Dialog v-model="dialogFileView" title="附件">
    <div
      v-for="(file, index) in fileList"
      :key="index"
      class="mt-5 flex min-w-0 items-center justify-between gap-5">
      <span class="file-name-text flex-1 min-w-0">{{ extractFileName(file) }}</span>
      <div class="flex shrink-0 items-center gap-5 flex-nowrap">
        <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>
  </Dialog>

  <!-- 选择作业人员对话框 -->
  <Dialog :title="personDialog" v-model="personDialogVisible" width="60%">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="所属人员" prop="userName">
          <el-input
            v-model="queryParams2.userName"
            placeholder="请输入所属人员"
            clearable
            @keyup.enter="handleQuery2"
            class="!w-200px" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery2"
            ><Icon icon="ep:search" class="mr-5px" /> {{ t('devicePerson.search') }}</el-button
          >
          <el-button @click="resetQuery2"
            ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('devicePerson.reset') }}</el-button
          >
        </el-form-item>
      </el-form>
    </ContentWrap>
    <div class="pb-10">
      <el-table
        v-loading="loading"
        :data="certList"
        :stripe="true"
        :show-overflow-tooltip="true"
        ref="measureTableRef">
        <el-table-column width="50" align="center">
          <template #default="scope">
            <el-radio
              :model-value="selectedPerson"
              :label="scope.row.id"
              @change="handleRadioChange(scope.row)">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <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="type">
          <template #default="scope">
            {{ getCertificateTypeText(scope.row.type) }}
          </template>
        </el-table-column>

        <el-table-column label="证书类别" align="center" width="150" prop="classify">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.type === 'organization'"
              :type="DICT_TYPE.ORG_CERT"
              :value="scope.row.classify" />
            <dict-tag v-else :type="DICT_TYPE.PERSON_CERT" :value="scope.row.classify" />
          </template>
        </el-table-column>
        <el-table-column
          label="证书名称"
          width="150"
          align="center"
          prop="certName"
          show-overflow-tooltip />

        <el-table-column label="所属人" align="center" prop="userName" />
        <el-table-column label="所在部门" align="center" prop="deptName" />

        <el-table-column label="颁发机构" align="center" prop="certOrg" width="120" />

        <el-table-column label="证书标准" align="center" prop="certStandard" width="120" />

        <el-table-column label="颁发时间" align="center" prop="certIssue">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.certIssue) }}
          </template>
        </el-table-column>

        <el-table-column label="有效期" align="center">
          <template #default="scope">
            {{ formatDateCorrectly(scope.row.certExpire) }}
          </template>
        </el-table-column>

        <el-table-column label="到期提醒" align="center">
          <template #default="scope"> {{ scope.row.noticeBefore }}天前提醒 </template>
        </el-table-column>

        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total2"
        v-model:page="queryParams2.pageNo"
        v-model:limit="queryParams2.pageSize"
        @pagination="getCertList" />
    </div>

    <template #footer>
      <el-button @click="confirmSelectMeasure" type="primary">确 定</el-button>
      <el-button @click="((personDialogVisible = false), (selectedPerson = undefined))"
        >取 消</el-button
      >
    </template>
  </Dialog>

  <!-- 选择JSA 对话框 -->
  <Dialog title="选择JSA序号" v-model="dialogJSA" width="60%">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams3" ref="queryFormRef" :inline="true">
        <el-form-item label="JSA序号" prop="jsaXh">
          <el-input
            v-model="queryParams3.jsaXh"
            placeholder="请输入JSA序号"
            clearable
            @keyup.enter="handleQuery3"
            class="!w-200px" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery3"
            ><Icon icon="ep:search" class="mr-5px" /> {{ t('devicePerson.search') }}</el-button
          >
          <el-button @click="resetQuery3"
            ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('devicePerson.reset') }}</el-button
          >
        </el-form-item>
      </el-form>
    </ContentWrap>
    <div class="pb-10">
      <el-table v-loading="loading" :data="JSAList" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column width="50" align="center">
          <template #default="scope">
            <el-radio
              :model-value="selectedJSA"
              :label="getJsaSelectionKey(scope.row)"
              @change="handleRadioChange2(scope.row)">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column label="JSA序号" align="center" prop="jsaXh" />
        <el-table-column label="编号" align="center" prop="jsaNo" />

        <el-table-column label="日期" align="center" prop="jsaTime">
          <template #default="{ row }">
            {{ formatDate(row.jsaTime).substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="工作任务" align="center" prop="jobTask" />

        <el-table-column label="工作地点" align="center" prop="jobAddress" />

        <el-table-column label="工作负责人" align="center" prop="jobDuty" />

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

        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total3"
        v-model:page="queryParams3.pageNo"
        v-model:limit="queryParams3.pageSize"
        @pagination="getJSAList" />
    </div>

    <template #footer>
      <el-button @click="confirmSelectJSA" type="primary">确 定</el-button>
      <el-button @click="((dialogJSA = false), (selectedJSA = undefined))">取 消</el-button>
    </template>
  </Dialog>

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

<script setup lang="ts">
import { QHSEPtwApi, IotMeasureCertApi, QHSEJsaApi } from '@/api/pms/qhse/index'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { handleTree, defaultProps } 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 { useUserStore } from '@/store/modules/user'
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'
import FilePreviewDialog from '@/components/FilePreview/src/FilePreviewDialog.vue'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { getUserProfile } from '@/api/system/user/profile'
const userStore = useUserStore()
defineOptions({ name: 'IotQHSEPTW' })

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,
  ptwXh: '',
  ptwNo: ''
})

const queryParams2 = reactive({
  pageNo: 1,
  pageSize: 10,
  userName: ''
})

const queryParams3 = reactive({
  pageNo: 1,
  pageSize: 10,
  jsaXh: ''
})
const queryFormRef = ref(null) // 搜索的表单

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

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

// 表单相关
const formRef = ref()
const formData = ref({
  deptId: '',
  workDuty: '',
  workPerson: '',
  guardian: '',
  workLocation: '',
  workContent: '',
  ptwXh: '',
  ptwNo: '',
  ptwGrade: '',
  ptwType: '',
  file: '',
  remark: '',
  ptwTime: '',
  jsaId: ''
})

// 表单验证规则
const formRules = {
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  workDuty: [{ required: true, message: '作业负责人不能为空', trigger: 'blur' }],
  workPerson: [{ required: true, message: '作业人员不能为空', trigger: 'blur' }],
  guardian: [{ required: true, message: '监护人不能为空', trigger: 'blur' }],
  workLocation: [{ required: true, message: '作业地点不能为空', trigger: 'blur' }],
  workContent: [{ required: true, message: '作业内容不能为空', trigger: 'blur' }],
  ptwXh: [{ required: true, message: '序号不能为空', trigger: 'blur' }],
  ptwNo: [{ required: true, message: '作业票编号不能为空', trigger: 'blur' }],
  ptwGrade: [{ required: true, message: '作业票等级不能为空', trigger: 'blur' }],
  ptwType: [{ required: true, message: '作业票类型不能为空', trigger: 'blur' }],
  file: [{ required: true, message: '附件不能为空', trigger: 'blur' }],
  ptwTime: [{ required: true, message: '作业票时间不能为空', trigger: 'blur' }]
}

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

const downloadFile = (response) => {
  // 创建 blob 对象
  const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })

  // 获取文件名
  let fileName = 'PTW.xlsx'
  const disposition = response.headers ? response.headers['content-disposition'] : ''
  if (disposition) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
    const matches = filenameRegex.exec(disposition)
    if (matches != null && matches[1]) {
      fileName = matches[1].replace(/['"]/g, '')
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

const handleExport = async () => {
  try {
    exportLoading.value = true
    const response = await QHSEPtwApi.exportPtw(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()
  formData.value.deptId = userStore.getUser.deptId
  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
}

// 确保时间戳是毫秒级的
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 QHSEPtwApi.deletePtw(id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    deptId: '',
    workDuty: '',
    workPerson: '',
    guardian: '',
    workLocation: '',
    workContent: '',
    ptwXh: '',
    ptwGrade: '',
    ptwType: '',
    file: '',
    remark: '',
    jsaId: ''
  }
  formRef.value?.clearValidate()
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}
let userInfo = ref()
// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

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

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

    // submitData.deptName = userInfo.value.dept.name

    if (isEdit.value) {
      // 编辑
      await QHSEPtwApi.updatePtw(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      submitData.deptId = userStore.getUser.deptId

      await QHSEPtwApi.createPtw(submitData)
      ElMessage.success('新增成功')
    }

    dialogVisible.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 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())

  const users = await getUserProfile()
  userInfo.value = users
  console.log('xxxxxxxxxxxxxxxxxx', userInfo.value)
})

let personDialogVisible = ref(false)
let certList = ref([])
const selectedPerson = ref<number | undefined>(undefined)
const selectedPersonRow = ref<any>()

const getCertificateTypeText = (type: string) => {
  const map: Record<string, string> = {
    personal: '个人证书',
    organization: '组织证书',
    other: '其他'
  }
  return map[type] || type
}

// 正确格式化日期的函数
const formatDateCorrectly = (timestamp) => {
  if (!timestamp) return ''

  // 如果是秒级时间戳，转换为毫秒级
  let time = Number(timestamp)
  if (time < 10000000000) {
    // 小于这个数通常表示秒级时间戳
    time = time * 1000
  }

  return formatDate(time).substring(0, 10)
}

let total2 = ref(0)
const getCertList = async () => {
  loading.value = true
  try {
    const data = await IotMeasureCertApi.getIotMeasureCertPage(queryParams2)
    certList.value = data.list
    total2.value = data.total
  } finally {
    loading.value = false
  }
}

let personType = ref('')
const confirmSelectMeasure = () => {
  if (!selectedPerson.value) {
    ElMessage.warning('请先选择一个计量器具')
    return
  }

  // 将选中的仪器信息填入表单
  if (personType.value == 'workPerson') {
    formData.value.workPerson = selectedPersonRow.value?.userName || ''
  }

  if (personType.value == 'guardian') {
    formData.value.guardian = selectedPersonRow.value?.userName || ''
  }

  if (personType.value == 'workDuty') {
    formData.value.workDuty = selectedPersonRow.value?.userName || ''
  }

  // 关闭选择仪器对话框
  personDialogVisible.value = false
  selectedPerson.value = undefined
  selectedPersonRow.value = undefined
}

let personDialog = ref('')
const selectworkPerson = (type) => {
  personType.value = type
  if (type == 'workPerson') {
    personDialog.value = '选择作业人员'
  } else if (type == 'guardian') {
    personDialog.value = '选择监护人'
  } else if (type == 'workDuty') {
    personDialog.value = '选择作业负责人'
  }
  selectedPerson.value = undefined
  selectedPersonRow.value = undefined
  personDialogVisible.value = true
  getCertList()
}

const handleRadioChange = (row: any) => {
  selectedPerson.value = row.id
  selectedPersonRow.value = row
  // selectedMeasure.value = row
}

/** 搜索按钮操作 */
const handleQuery2 = () => {
  queryParams2.pageNo = 1
  getCertList()
}

/** 重置按钮操作 */
const resetQuery2 = () => {
  queryParams2.userName = ''
  queryFormRef.value?.resetFields()
  handleQuery2()
}

// JSA序号***********************************88
let dialogJSA = ref(false)
let JSAList = ref([])
let total3 = ref(0)
const getJSAList = async () => {
  loading.value = true
  try {
    const data = await QHSEJsaApi.getJsaList(queryParams3)
    JSAList.value = data.list
    total3.value = data.total
  } finally {
    loading.value = false
  }
}
// 选择JSA序号
const selectJSA = () => {
  dialogJSA.value = true
  selectedJSA.value = undefined
  selectedJSARow.value = undefined
  jsaId.value = 0
  getJSAList()
}

/** 搜索按钮操作 */
const handleQuery3 = () => {
  queryParams3.pageNo = 1
  getJSAList()
}

/** 重置按钮操作 */
const resetQuery3 = () => {
  queryParams3.jsaXh = ''
  queryFormRef.value?.resetFields()
  handleQuery3()
}

let selectedJSA = ref<string | undefined>(undefined)
let selectedJSARow = ref<any>()
const getJsaSelectionKey = (row: any) => `${row?.jsaXh || ''}__${row?.jsaNo || ''}`
const confirmSelectJSA = () => {
  if (!selectedJSA.value) {
    ElMessage.warning('请先选择一个JSA')
    return
  }

  // 将选中的仪器信息填入表单
  formData.value.ptwNo = selectedJSARow.value?.jsaNo || ''
  formData.value.jsaId = jsaId.value

  // 关闭选择仪器对话框
  dialogJSA.value = false
  selectedJSA.value = undefined
  selectedJSARow.value = undefined
  jsaId.value = 0
}
let jsaId = ref(0)
const handleRadioChange2 = (row: any) => {
  console.log('row', row)
  selectedJSA.value = getJsaSelectionKey(row)
  selectedJSARow.value = row
  jsaId.value = row.id
}
</script>

<style scoped>
.file-name-text {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
::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>
