<template>
  <el-row :gutter="20">
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :span="isLeftContentCollapsed ? 24 : 20" :xs="24">
      <ContentWrap style="border: 0">
        <!-- 搜索工作栏 -->
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="月报标题" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入月报标题" />
          </el-form-item>

          <el-form-item label="创建日期" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-200px" />
          </el-form-item>

          <el-form-item>
            <el-button @click="handleQuery" v-hasPermi="['rq:qhse-month-report:query']"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <!-- <el-button type="primary" @click="add" color="#626aef">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button> -->
            <el-button type="success" plain @click="handleExport" :loading="exportLoading">
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <ContentWrap style="border: 0">
        <zm-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#333' }"
          :cell-style="{ padding: '12px 8px' }"
          height="70.8vh">
          <zm-table-column
            prop="title"
            label="月报标题"
            align="center"
            fixed="left"
            show-overflow-tooltip />
          <zm-table-column prop="personName" label="工单填报人" align="center" />
          <zm-table-column label="创建日期" prop="createTime" align="center">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </zm-table-column>

          <zm-table-column label="操作" width="150" align="center" fixed="right" action>
            <template #default="{ row }">
              <div class="flex gap-1 justify-center">
                <el-button text type="primary" @click="add(row)"> 填报 </el-button>
                <el-button text size="small" type="success" @click="detail(row)"> 查看 </el-button>
              </div>
            </template>
          </zm-table-column>
        </zm-table>

        <!-- 分页 -->
        <div class="mt-2 flex justify-right">
          <el-pagination
            v-model:current-page="pagination.pageNo"
            v-model:page-size="pagination.pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background />
        </div>
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { QhseMonthReportApi } from '@/api/pms/qhse'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { useUserStore } from '@/store/modules/user'
import { getUserProfile } from '@/api/system/user/profile'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'QhseMonthlyReport' })

const userStore = useUserStore()
const router = useRouter()
// 查询参数
const queryParams = reactive({
  createTime: null,
  title: '',
  deptId: ''
})

let queryFormRef = ref(null)

// 表格数据
const tableData = ref([])
const isLeftContentCollapsed = ref(false)

const dialogTitle = ref('新增')

// 搜索
const handleQuery = () => {
  pagination.pageNo = 1 // 搜索后回到第一页
  loadTableData()
}

const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  pagination.pageNo = 1
  loadTableData()
}

const downloadFile = (response) => {
  // 创建 blob 对象
  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 QhseMonthReportApi.exportQhseMonthReport(queryParams)

    // 下载文件
    downloadFile(response)
    exportLoading.value = false
  } catch (error) {
    ElMessage.error('导出失败，请重试')
    console.error('导出错误:', error)
  } finally {
  }
}

// 重置查询
const resetQuery = () => {
  pagination.pageNo = 1 // 重置为第一页
  queryFormRef.value.resetFields()
  loadTableData()
}

// 删除确认
const deleteRow = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除 ${row.elementDescription} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await QhseMonthReportApi.deleteQhseMonthReport(row.id)
    ElMessage.success('删除成功')
    loadTableData() // 重新加载数据
  } catch (error) {
    // 用户取消或删除失败
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 每页数量变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNo = 1 // 重置为第一页
  loadTableData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.pageNo = val
  loadTableData()
}

const add = (row) => {
  // console.log(userInfo.value)
  // if (row.dutyPerson !== userInfo.value.id && userInfo.value.username !== 'admin') {
  //   ElMessage.error('您没有权限进行此操作')
  //   return
  // }
  router.push({
    name: 'MonthlyReportAdd',
    params: {
      id: row.id
    }
  })
}

const detail = (row) => {
  // if (row.dutyPerson !== userInfo.value.id && userInfo.value.username !== 'admin') {
  //   ElMessage.error('您没有权限进行此操作')
  //   return
  // }
  router.push({
    name: 'MonthlyReportInfo',
    params: {
      id: row.id
    }
  })
}

// 提交表单
const formRef = ref(null)

// 加载数据
const exportLoading = ref(false)
let total = ref(0)
const pagination = reactive({
  pageNo: 1,
  pageSize: 10
})
const loadTableData = async () => {
  try {
    const params = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      createTime: queryParams.createTime,
      title: queryParams.title,
      deptId: queryParams.deptId
    }
    const res = await QhseMonthReportApi.getQhseMonthReportPage(params)
    tableData.value = res.list || []
    total.value = res.total || 0
  } catch (error) {
    console.error('加载失败:', error)
  }
}

let userInfo = ref({})

// 页面挂载后加载数据
onMounted(async () => {
  loadTableData()

  const users = await getUserProfile()
  userInfo.value = users

  console.log('xxxxxxxxxxxxxxxxxx', userInfo.value)
})
</script>

<style scoped lang="scss">
::v-deep .el-button {
  border-radius: 0;
}

::v-deep .el-select__wrapper {
  border-radius: 0 !important;
  height: 26px;
}
.hazard-table-container {
  margin: 20px;
  margin-top: 10px;
}

.area-header {
  font-weight: bold;
  text-align: center;
  padding: 12px 0;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ddd;
}
</style>
