<template>
  <div class="attachment-management">
    <a-space direction="vertical" :size="16" fill>
      <a-row class="search-form">
        <a-col :flex="1">
          <a-form :model="filterForm" layout="inline">
            <a-form-item field="businessType" label="业务类型">
              <a-select
                v-model="filterForm.businessType"
                placeholder="请选择业务类型"
                allow-clear
                style="width: 200px"
              >
                <a-option v-for="type in businessTypes" :key="type.code" :value="type.code">{{ type.name }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="keyword" label="关键词">
              <a-input
                v-model="filterForm.keyword"
                placeholder="请输入文件名或描述关键词"
                allow-clear
              />
            </a-form-item>
            <a-form-item field="fileType" label="文件类型">
              <a-select
                v-model="filterForm.fileType"
                placeholder="请选择文件类型"
                allow-clear
                style="width: 150px"
              >
                <a-option value="image">图片</a-option>
                <a-option value="document">文档</a-option>
                <a-option value="video">视频</a-option>
                <a-option value="other">其他</a-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleSearch">
                  <template #icon><icon-search /></template>
                  搜索
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon><icon-refresh /></template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-card :bordered="false">
        <template #title>附件列表</template>
        <template #extra>
          <a-space>
            <a-button type="primary" size="small" :disabled="selectedRowKeys.length === 0">
              <template #icon><icon-download /></template>
              批量下载
            </a-button>
            <a-button 
              type="primary" 
              status="danger" 
              size="small" 
              :disabled="selectedRowKeys.length === 0"
              @click="handleBatchDelete"
            >
              <template #icon><icon-delete /></template>
              批量删除
            </a-button>
          </a-space>
        </template>

        <a-table
          :loading="loading"
          :data="tableData"
          :pagination="pagination"
          @page-change="onPageChange"
          row-key="id"
          :row-selection="{
            type: 'checkbox',
            showCheckedAll: true,
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectionChange
          }"
        >
          <template #columns>
            <a-table-column title="文件名" data-index="fileName">
              <template #cell="{ record }">
                <a-space>
                  <component :is="getFileIcon(record.fileType)" />
                  <a href="javascript:;" @click="previewFile(record)">
                    {{ record.fileName }}
                  </a>
                </a-space>
              </template>
            </a-table-column>
            <a-table-column title="文件类型" data-index="fileType">
              <template #cell="{ record }">
                <a-tag>{{ getFileTypeText(record.fileType) }}</a-tag>
              </template>
            </a-table-column>
            <a-table-column title="业务类型" data-index="businessType">
              <template #cell="{ record }">
                <a-tag>{{ getBusinessTypeName(record.businessType) }}</a-tag>
              </template>
            </a-table-column>
            <a-table-column title="文件大小" data-index="fileSize">
              <template #cell="{ record }">
                {{ formatFileSize(record.fileSize) }}
              </template>
            </a-table-column>
            <a-table-column title="上传时间" data-index="createTime" />
            <a-table-column title="描述" data-index="remark" />
            <a-table-column title="操作" width="180">
              <template #cell="{ record }">
                <a-space>
                  <a-button size="small" @click="previewFile(record)">
                    <template #icon><icon-eye /></template>
                    预览
                  </a-button>
                  <a-button size="small" @click="downloadFile(record)">
                    <template #icon><icon-download /></template>
                    下载
                  </a-button>
                  <a-popconfirm
                    content="确定要删除该文件吗？"
                    @ok="deleteFile(record)"
                  >
                    <a-button size="small" status="danger">
                      <template #icon><icon-delete /></template>
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table-column>
          </template>
          <template #empty>
            <a-empty description="暂无数据" />
          </template>
        </a-table>
      </a-card>

      <a-modal
        v-model:visible="previewVisible"
        :title="currentPreviewFile?.fileName"
        :footer="false"
        style="width: 70%"
        unmount-on-close
      >
        <FilePreview
          v-if="previewVisible"
          :file="currentPreviewFile"
          style="width: 100%; height: 500px"
        />
      </a-modal>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import FilePreview from '@/components/FilePreview/index.vue'
import { 
  IconSearch, 
  IconRefresh,
  IconDownload,
  IconDelete,
  IconEye,
  IconFile
} from '@arco-design/web-vue/es/icon'
import { getAttachBusinessTypes, getAttachmentList, deleteAttachment } from '@/apis/attach-info'
import type { AttachInfoData, BusinessType } from '@/apis/attach-info/type'

defineOptions({ name: 'AttachmentManagement' })

const loading = ref(false)
const previewVisible = ref(false)
const currentPreviewFile = ref<any>(null)
const businessTypes = ref<BusinessType[]>([])
const selectedRowKeys = ref<(string | number)[]>([])

const filterForm = reactive({
  businessType: '',
  keyword: '',
  fileType: '',
})

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
})

const tableData = ref<AttachInfoData[]>([])

// 获取业务类型列表
const fetchBusinessTypes = async () => {
  try {
    const res = await getAttachBusinessTypes()
    if (res.data) {
      businessTypes.value = res.data
      // 默认选择第一个业务类型
      if (businessTypes.value.length > 0) {
        filterForm.businessType = businessTypes.value[0].code
        fetchAttachmentList()
      }
    }
  } catch (error) {
    console.error('获取业务类型失败:', error)
    Message.error('获取业务类型失败')
  }
}

// 获取附件列表
const fetchAttachmentList = async () => {
  if (!filterForm.businessType) {
    Message.warning('请先选择业务类型')
    return
  }
  
  loading.value = true
  try {
    const res = await getAttachmentList(filterForm.businessType)
    if (res.data) {
      tableData.value = res.data
      pagination.total = res.data.length
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取附件列表失败:', error)
    Message.error('获取附件列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchBusinessTypes()
})

const handleSearch = () => {
  fetchAttachmentList()
}

const resetSearch = () => {
  // 仅重置关键词和文件类型，保留业务类型
  filterForm.keyword = ''
  filterForm.fileType = ''
  fetchAttachmentList()
}

const onPageChange = (page: number) => {
  pagination.current = page
  fetchAttachmentList()
}

const onSelectionChange = (rowKeys: (string | number)[]) => {
  selectedRowKeys.value = rowKeys
}

const previewFile = (file: AttachInfoData) => {
  currentPreviewFile.value = {
    ...file,
    fileFormat: getFileFormat(file.fileName),
  }
  previewVisible.value = true
}

const downloadFile = (file: AttachInfoData) => {
  if (file.fileUrl) {
    const a = document.createElement('a')
    a.href = file.fileUrl
    a.download = file.fileName
    a.click()
    Message.success(`开始下载: ${file.fileName}`)
  } else {
    Message.error('文件链接不存在')
  }
}

const deleteFile = async (file: AttachInfoData) => {
  try {
    const res = await deleteAttachment(file.id)
    if (res) {
      Message.success(`已删除: ${file.fileName}`)
      // 从列表中移除
      tableData.value = tableData.value.filter(item => item.id !== file.id)
      pagination.total = tableData.value.length
    } else {
      Message.error('删除文件失败')
    }
  } catch (error) {
    console.error('删除文件失败:', error)
    Message.error('删除文件失败')
  }
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    return
  }
  
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个文件吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const promises = selectedRowKeys.value.map(id => deleteAttachment(id))
        await Promise.all(promises)
        Message.success('批量删除成功')
        fetchAttachmentList()
        selectedRowKeys.value = []
      } catch (error) {
        console.error('批量删除失败:', error)
        Message.error('批量删除失败')
      }
    }
  })
}

const getFileTypeText = (type: string) => {
  const typeMap = {
    image: '图片',
    document: '文档',
    video: '视频',
    other: '其他'
  }
  return typeMap[type] || '未知'
}

const getBusinessTypeName = (code: string) => {
  const businessType = businessTypes.value.find(item => item.code === code)
  return businessType ? businessType.name : code
}

const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  let tempSize = size
  
  while (tempSize >= 1024 && index < units.length - 1) {
    tempSize /= 1024
    index++
  }
  
  return `${tempSize.toFixed(2)} ${units[index]}`
}

const getFileFormat = (fileName: string) => {
  const ext = fileName.split('.').pop()?.toLowerCase() || ''
  return ext
}

const getFileIcon = (fileType: string) => {
  // 简化为仅使用通用文件图标
  return IconFile
}
</script>

<style scoped lang="scss">
.attachment-management {
  width: 100%;

  .search-form {
    margin-bottom: 16px;
  }
}
</style> 