<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <ContentWrap style="border: none">
        <!-- 搜索工作栏 -->
        <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="source">
            <el-select
              v-model="queryParams.source"
              placeholder="请选择来源"
              clearable
              style="width: 150px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.QHSE_HAZARD_SOURCE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px">
              <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" v-hasPermi="['rq:iot-hazard:create']"
              ><Icon icon="ep:plus" class="mr-5px" />新增</el-button
            >
            <el-button @click="handleQuery" v-hasPermi="['rq:iot-hazard: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:iot-hazard:export']"
              ><Icon icon="ep:download" class="mr-5px" /> 导出</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap class="flex-1 overflow-hidden mt-15px" style="border: none">
        <div class="stats-cards">
          <div
            class="stats-card"
            style="background: linear-gradient(180deg, #fff 0%, #e8f2ff 100%)">
            <div class="stats-card__header">
              <Icon icon="eos-icons:counting" color="#2563eb" />

              <div class="stats-card__title">隐患总数</div>
            </div>
            <div class="stats-card__body py-10">
              <CountTo
                :duration="2600"
                :end-val="hiddenCount"
                :start-val="0"
                class="stats-card__count text-3xl text-center! text-[#2563eb]!" />
            </div>
          </div>

          <div
            class="stats-card"
            style="background: linear-gradient(180deg, #fff4f4 0%, #ffe8e8 100%)">
            <div class="stats-card__header">
              <Icon icon="ep:info-filled" color="#de3b3b" />
              <div class="stats-card__title">未整改数</div>
            </div>
            <div class="stats-card__body py-10">
              <CountTo
                :duration="2600"
                :end-val="todo"
                :start-val="0"
                class="stats-card__count text-3xl text-center! text-[#ff5b61]!" />
            </div>
          </div>

          <div
            class="stats-card"
            style="background: linear-gradient(180deg, #fff 0%, #e8f2ff 100%)">
            <div class="stats-card__header">
              <Icon icon="material-symbols:android-cell-4-bar" color="#2563eb" />

              <div class="stats-card__title">整改率</div>
            </div>
            <div class="stats-card__body py-10">
              <CountTo
                :duration="2600"
                :end-val="((hiddenCount - todo) / hiddenCount) * 100 || 0"
                :start-val="0"
                class="stats-card__count text-3xl text-center! text-[#2563eb]!" />
              <span class="text-[#2563eb]!">%</span>
            </div>
          </div>

          <!-- 饼图 -->
          <div
            class="stats-card pie-chart-card"
            style="background: linear-gradient(180deg, #fff 0%, #e8f2ff 100%)">
            <div class="pie-chart-title">隐患来源分布</div>
            <div ref="pieChartRef" class="pie-chart-container"></div>
          </div>
        </div>
        <zm-table
          :loading="loading"
          :data="list"
          :stripe="true"
          height="calc(44.6vh)"
          :show-overflow-tooltip="true">
          <zm-table-column :label="t('monitor.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>

          <zm-table-column label="单位" align="center" prop="deptName" />
          <zm-table-column label="类型" align="center" prop="classifyName" />
          <zm-table-column label="来源" align="center" min-width="90">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.QHSE_HAZARD_SOURCE" :value="scope.row.source" />
            </template>
          </zm-table-column>

          <zm-table-column label="地点" align="center" prop="address" />

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

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

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

          <zm-table-column label="整改附件" align="center" prop="rectifyFile" min-width="90">
            <template #default="{ row }">
              <el-button
                text
                v-if="row.rectifyFile"
                :underline="false"
                type="primary"
                size="small"
                @click="viewFile(row.rectifyFile)"
                >查看</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.checkTime) }}
            </template>
          </zm-table-column>

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

          <zm-table-column label="备注" align="center" prop="remark" />

          <zm-table-column
            :label="t('devicePerson.operation')"
            align="center"
            fixed="right"
            min-width="150px"
            action>
            <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"
                v-hasPermi="['rq:iot-hazard:update']"
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                v-hasPermi="['rq:iot-hazard: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="source">
        <el-select
          v-model="formData.source"
          placeholder="请选择隐患排查来源"
          clearable
          @change="handleChange">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.QHSE_HAZARD_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属队伍" prop="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          :check-strictly="
            formData.source === 'xm' || formData.source === 'zfjf' || formData.source === 'gsjt'
          "
          node-key="id"
          filterable
          placeholder="请选择所属队伍" />
      </el-form-item>
      <el-form-item label="隐患排查类型" prop="classify">
        <el-tree-select
          style="width: 500px; overflow: auto"
          v-model="formData.classify"
          :data="deptTree"
          :props="defaultProps"
          :check-strictly="false"
          placeholder="请选择隐患排查类型"
          value-key="id" />
      </el-form-item>

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

      <el-form-item label="整改要求" prop="correctStandard">
        <el-input
          type="textarea"
          :rows="2"
          v-model="formData.correctStandard"
          placeholder="请输入整改要求" />
      </el-form-item>

      <el-form-item label="整改人" prop="correctPerson">
        <el-select
          v-model="formData.correctPerson"
          filterable
          clearable
          placeholder="请选择整改人"
          style="width: 100%">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <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', '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
    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', 'bmp']"
          :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>
  </Dialog>

  <Dialog v-model="dialogFileView" title="附件">
    <div
      v-for="(file, index) in fileList"
      :key="index"
      class="flex items-center justify-between mt-5 gap-5">
      <span class="file-name-text">{{ extractFileName(file) }}</span>
      <div class="flex gap-5 no-wrap">
        <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>

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

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { IotHiddenApi, IotHiddenTypeApi } from '@/api/pms/qhse/index'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { getUserProfile } from '@/api/system/user/profile'
import * as DeptApi from '@/api/system/dept'
import { selectedDeptsEmployee } from '@/api/system/user'
import { ElMessageBox, ElMessage } from 'element-plus'
const deptList2 = ref<Tree[]>([]) // 树形结构
import { formatDate } from '@/utils/formatTime'
import { defaultProps, handleTree } from '@/utils/tree'
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'
import FilePreviewDialog from '@/components/FilePreview/src/FilePreviewDialog.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents()

import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer])

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 deptTree = ref() // 树形结构
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: '',
  deptId: '',
  address: '',
  source: ''
})
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: '',
  classify: '',
  source: '',
  checkTime: '',
  correctStandard: '',
  correctPerson: ''
})

// 表单验证规则
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' }],
  classify: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  source: [{ required: true, message: '来源不能为空', trigger: 'blur' }],
  checkTime: [{ required: true, message: '检查时间不能为空', trigger: 'blur' }],
  correctStandard: [{ required: true, message: '整改标准不能为空', trigger: 'blur' }],
  correctPerson: [{ 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 downloadFile = (response: any) => {
  const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })

  let fileName = '排查治理记录.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 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()
  await getStatic()
}

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

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

const handleChange = (val) => {
  console.log('handleChange', val)
  if (val === 'dw') {
    formData.value.deptId = ''
  }
}
// 显示新增对话框
const handleAdd = async () => {
  isEdit.value = false
  dialogTitle.value = '新增隐患排查'
  await getTree()
  resetForm()
  formData.value.deptId = userStore.getUser.deptId
  dialogVisible.value = true
}

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

  formData.value = {
    ...row,
    classify: row.classify ? Number(row.classify) : row.classify,
    // 确保日期字段正确处理
    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 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 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
  }
}
/** 获得分类树 */
const getTree = async () => {
  deptTree.value = []
  const data = await IotHiddenTypeApi.getParentCategory()
  let dept: Tree = { id: 0, name: '顶级分类', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
  // firstLevelKeys.value = deptTree.value.map((node) => node.id)
}

let hiddenCount = ref(0)
let todo = ref(0)
let source = ref('')
const pieChartRef = ref<HTMLDivElement>()
let pieChart: echarts.ECharts | null = null
async function getStatic() {
  if (queryParams.deptId) {
    const res = await IotHiddenApi.getHiddenStatistics(queryParams.deptId)
    hiddenCount.value = res.total
    todo.value = res.todo
    source.value = res.source
  } else {
    const res = await IotHiddenApi.getHiddenStatistics(userStore.user.deptId)
    hiddenCount.value = res.total
    todo.value = res.todo
    source.value = res.source
  }

  nextTick(() => {
    initPieChart()
  })
}

const initPieChart = () => {
  if (!pieChartRef.value) return

  if (pieChart) {
    pieChart.dispose()
  }

  pieChart = echarts.init(pieChartRef.value)

  const chartData = Array.isArray(source.value)
    ? source.value.map((item: any) => ({
        name: item.classify || '未知',
        value: item.count || 0
      }))
    : []

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      textStyle: {
        fontSize: 14
      },
      itemWidth: 20,
      itemHeight: 20
    },
    series: [
      {
        name: '隐患来源',
        type: 'pie',
        radius: ['35%', '60%'],
        center: ['58%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 12,
            fontWeight: 'bold'
          }
        },
        data: chartData
      }
    ]
  }

  pieChart.setOption(option)
}

const resizePieChart = () => {
  pieChart?.resize()
}

let pieChartResizeObserver: ResizeObserver | null = null

let userList = ref([])
onMounted(async () => {
  const users = await getUserProfile()

  userList.value = await selectedDeptsEmployee({
    deptIds: users.dept.id
  })
  getList()

  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())

  try {
    getStatic()
  } catch (error) {
    console.error(error)
  }

  window.addEventListener('resize', resizePieChart)

  if (pieChartRef.value) {
    pieChartResizeObserver = new ResizeObserver(() => {
      resizePieChart()
    })
    pieChartResizeObserver.observe(pieChartRef.value)
  }
})

onUnmounted(async () => {
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
  window.removeEventListener('resize', resizePieChart)

  if (pieChartResizeObserver && pieChartRef.value) {
    pieChartResizeObserver.unobserve(pieChartRef.value)
    pieChartResizeObserver = null
  }
})

watch(
  () => source.value,
  () => {
    nextTick(() => {
      initPieChart()

      if (pieChartRef.value && !pieChartResizeObserver) {
        pieChartResizeObserver = new ResizeObserver(() => {
          resizePieChart()
        })
        pieChartResizeObserver.observe(pieChartRef.value)
      }
    })
  },
  { deep: true }
)
</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;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, minmax(180px, 1fr)) minmax(280px, 2fr);
  gap: 12px;
  margin-bottom: 16px;
}

.stats-card {
  position: relative;
  overflow: hidden;
  min-height: 100px;
  padding: 18px 18px 0px;

  border: 1px solid #e4ecf7;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgb(31 91 184 / 8%);
}

.stats-card__decor {
  position: absolute;
  border-radius: 999px;
  pointer-events: none;
  filter: blur(8px);
  opacity: 0.95;
}

.stats-card__decor--left {
  width: 72px;
  height: 72px;
  left: -10px;
  top: -8px;
}

.stats-card__decor--right {
  width: 88px;
  height: 88px;
  right: -18px;
  bottom: -24px;
}

.stats-card__header {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 14px;
}

.stats-card__icon-wrap {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 14px;
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 85%),
    0 10px 24px rgb(118 144 187 / 10%);
}

.stats-card__icon {
  font-size: 24px;
  /* line-height: 1; */
}

.stats-card__title {
  font-size: 16px;
  font-weight: 700;
  color: #324b72;
  letter-spacing: 0;
}

.stats-card__body {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: flex-end;
  gap: 8px;
  margin-top: 14px;
  padding-left: 62px;
}

.stats-card__count {
  display: block;
  font-size: 38px !important;
  font-weight: 800;
  line-height: 0.92;
  letter-spacing: 1px;
  /* font-style: italic; */
  text-shadow: 0 8px 18px rgb(68 110 183 / 10%);
}

.stats-card__note {
  padding-bottom: 4px;
  font-size: 16px;
  font-weight: 700;
  line-height: 1;
}

.pie-chart-card {
  display: flex;
  flex-direction: column;
  min-height: 180px;
}

.pie-chart-title {
  font-size: 13px;
  font-weight: 600;
  color: #324b72;
  margin-bottom: 6px;
  text-align: center;
}

.pie-chart-container {
  flex: 1;
  min-height: 50px;
  width: 100%;
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }

  .stats-card {
    min-height: 160px;
    padding: 24px 22px 22px;
    border-radius: 22px;
  }

  .stats-card__header {
    gap: 18px;
  }

  .stats-card__icon-wrap {
    width: 58px;
    height: 58px;
    border-radius: 16px;
  }

  .stats-card__icon {
    font-size: 28px;
  }

  .stats-card__title {
    font-size: 17px;
  }

  .stats-card__body {
    margin-top: 18px;
    padding-left: 76px;
    gap: 10px;
  }

  .stats-card__count {
    font-size: 46px !important;
  }

  .stats-card__note {
    font-size: 18px;
    padding-bottom: 6px;
  }

  .pie-chart-container {
    min-height: 220px;
  }
}

.file-name-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
