<template>
  <div class="app-container">
    <div class="portal-header">
      <h2 class="portal-title">直管工程</h2>
      <el-button type="primary" icon="Plus" @click="handleAddProject">添加项目</el-button>
    </div>

    <el-row :gutter="16">
      <el-col v-for="item in folderListData" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb16">
        <el-card shadow="hover" class="project-card" @click="handleProjectClick(item)">
          <div class="card-body">
            <div class="card-icon">
              <svg-icon icon-class="folder" />
            </div>
            <div class="card-info">
              <div class="card-title">{{ item.name }}</div>
              <div class="card-meta">
                <span>创建时间：{{ parseTime(item.date, '{y}-{m}-{d}') }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty v-if="!loading && folderListData.length === 0" description="暂无工程数据" />

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getFolderList" />

    <el-dialog title="添加项目" v-model="addDialogVisible" width="500px" append-to-body>
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入项目名�? maxlength="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddProject">�?�?/el-button>
          <el-button @click="addDialogVisible = false">�?�?/el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="项目详情" v-model="detailVisible" width="800px" append-to-body top="5vh">
      <template v-if="currentProject">
        <div class="detail-header">
          <h3>{{ currentProject.name }}</h3>
        </div>
        <el-table v-loading="fileLoading" :data="fileList" stripe max-height="400">
          <el-table-column label="文件名称" min-width="200" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="handlePreview(scope.row)">
                {{ scope.row.name }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" width="120" prop="size" />
          <el-table-column label="上传时间" width="160" prop="date">
            <template #default="scope">
              <span>{{ parseTime(scope.row.date) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button link type="primary" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!fileLoading && fileList.length === 0" description="暂无文件" />
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zggc">
import { folderList, getFileList, mkdir, downloadFile } from "@/api/efinder/finder"
import { parseTime } from "@/utils/goldenwater"

const { proxy } = getCurrentInstance()
const router = useRouter()

const folderListData = ref([])
const total = ref(0)
const loading = ref(true)
const addDialogVisible = ref(false)
const detailVisible = ref(false)
const currentProject = ref(null)
const fileList = ref([])
const fileLoading = ref(false)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    fdCate: "zggc"
  },
  addForm: {
    name: undefined
  },
  addRules: {
    name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }]
  }
})

const { queryParams, addForm, addRules } = toRefs(data)

function getFolderList() {
  loading.value = true
  folderList(queryParams.value).then(response => {
    folderListData.value = response.data || response.rows || []
    total.value = response.total || folderListData.value.length
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleProjectClick(item) {
  currentProject.value = item
  detailVisible.value = true
  loadProjectFiles(item)
}

function loadProjectFiles(item) {
  fileLoading.value = true
  getFileList({ pid: item.id }).then(response => {
    fileList.value = response.rows || response.data || []
    fileLoading.value = false
  }).catch(() => {
    fileLoading.value = false
  })
}

function handleAddProject() {
  addForm.value = { name: undefined }
  addDialogVisible.value = true
  proxy.resetForm("addFormRef")
}

function submitAddProject() {
  proxy.$refs["addFormRef"].validate(valid => {
    if (valid) {
      mkdir({ name: addForm.value.name, pid: 0, fdCate: queryParams.value.fdCate }).then(() => {
        proxy.$modal.msgSuccess("添加成功")
        addDialogVisible.value = false
        getFolderList()
      })
    }
  })
}

function handlePreview(row) {
  const fileType = row.type ? row.type.toLowerCase() : ""
  router.push({ path: "/efinder/viewer", query: { fileId: row.id, fileType, fileName: row.name } })
}

function handleDownload(row) {
  downloadFile(row.id).then(res => {
    const blob = new Blob([res])
    const link = document.createElement("a")
    link.href = URL.createObjectURL(blob)
    link.download = row.name
    link.click()
    URL.revokeObjectURL(link.href)
    proxy.$modal.msgSuccess("下载成功")
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getFolderList()
}

onMounted(() => {
  getFolderList()
})
</script>

<style lang="scss" scoped>
.portal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.portal-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.project-card {
  cursor: pointer;
  transition: transform 0.2s;

  &:hover {
    transform: translateY(-2px);
  }
}

.card-body {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-icon {
  font-size: 32px;
  color: var(--el-color-primary);
}

.card-info {
  flex: 1;
  min-width: 0;
}

.card-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-meta {
  font-size: 12px;
  color: #999;
}

.mb16 {
  margin-bottom: 16px;
}

.detail-header h3 {
  margin: 0 0 12px;
  font-size: 18px;
}
</style>
