<template>
  <div>
    <!-- 历史文件列表 -->
    <el-card class="history-section">
      <h3>历史上传记录</h3>
      <el-table :data="fileHistory" style="width: 100%">
        <el-table-column prop="mission.name" label="分析任务" width="260" />
        <el-table-column prop="mission.id" label="任务ID" width="260" />

        <el-table-column label="" width="40">
          <template #default="scope">
            <el-button v-if="scope.row.content == 'node'" type="primary"
              style="width: 20px; height:20px; padding: 2px;">N</el-button>
            <el-button v-if="scope.row.content == 'edge'" type="warning"
              style="width: 20px; height:20px; padding: 2px;">E</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="文件名" width="280" />
        <el-table-column prop="uploadTime" label="上传时间" width="280" />
        <el-table-column prop="fileSize" label="文件大小" width="180">
        </el-table-column>

        <el-table-column label="文件信息" width="280">
          <template #default="{ row }">
            <el-dropdown>
              <span v-if="row.content === 'node'" class="analysis-records">
                {{ '节点总数：' + row.fileInfo.节点总数 }}<el-icon><arrow-down /></el-icon>
              </span>
              <span v-else class="analysis-records">
                {{ '边总数：' + row.fileInfo.边总数 }}<el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="(value, key) in row.fileInfo" :key="key">
                    {{ key }} - {{ value }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250px">
          <template #default="{ row }">
            <div style="display: flex; gap: 5px;">
              <el-button v-if="row.encrypted" type="warning" size="small" @click="handleEncryptFile(row)" plain>
                解密
              </el-button>
              <el-button v-else type="primary" size="small" @click="handleEncryptFile(row)" plain>
                加密
              </el-button>
              <el-button type="success" size="small" @click="handleDownloadFile(row)" plain>
                下载
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteFile(row)" plain>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, ArrowDown, Plus } from '@element-plus/icons-vue'
import { getData, postData, deleteData, downloadData } from '@/api/axios.js'
const fileHistory = ref([])

const handleDownloadFile = async (file) => {
  ElMessageBox.confirm(
    `下载文件 ${file.fileName} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await downloadData('/downloadfile/', { fileId: file.id })
      // 创建临时链接
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', file.fileName)
      document.body.appendChild(link)
      link.click()

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

      ElMessage.success('文件下载已开始')
    } catch (error) {
      ElMessage.error('文件下载失败,下载前请先解密文件')
      console.error('下载错误:', error)
    }
  }).catch(error => {
    console.log(error)
  })
}

const handleEncryptFile = async (file, password = "") => {
  let nextInput = false
  console.log(file)
  await ElMessageBox.confirm(
    `确定要${file.encrypted ? '解密' : '加密'}文件 ${file.fileName} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    nextInput = true
  }).catch(() => {

  })
  if (nextInput) {
    ElMessageBox.prompt(
      `请输入密码`,
      '密码验证',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputType: 'password',
        inputPattern: /^[\s\S]{6,}$/, // 至少6位
        inputErrorMessage: '密码至少需要6位字符'
      }
    ).then(async ({ value: password }) => {
      console.log(password)
      try {
        const response = await postData('/encryptfile/', { fileId: file.id, action: file.encrypted ? 'decrypt' : 'encrypt', password: password })
        // 没有报错即正常完成加解密,变更加解密状态
        file.encrypted = !file.encrypted
        ElMessage.success(`文件${file.encrypted ? '加密' : '解密'}成功！`)
      } catch (error) {
        if (file.encrypted) {
          ElMessage.error('文件解密失败')
        } else {
          ElMessage.error('文件加密失败')
        }

        console.error('加解密错误:', error)
      }
    })
  }
}

const handleDeleteFile = (file) => {
  ElMessageBox.confirm(
    `确定要删除文件 ${file.fileName} 吗？此操作不可恢复。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteData('/uploadfile/', { id: file.id }).then(response => {
      if (response.status == 'success') {
        ElMessage.success('文件已删除')
        updateUploadHistory()
      } else {
        ElMessage.error('文件删除失败' + response.message)
      }
    })
      .catch(error => {
        ElMessage.error('文件删除失败');
        console.log(error)
      })
  }).catch(() => { })
}

const updateUploadHistory = () => {
  getData('/uploadfile/')
    .then(response => {
      fileHistory.value = []
      response.data.reverse().forEach(item => {
        fileHistory.value.push({
          id: item.id,
          content: item.content,
          fileName: item.name,
          uploadTime: item.uploadTime.split('.')[0].replace('T', ' '),
          fileSize: item.size,
          encrypted: item.encrypted,
          // 按照目前逻辑，每个文件的关联mission应该只有一个
          mission: item.missions[0],
          fileInfo: item.fileInfo,
        })
      })
      // history.forEach(element => {
      //   console.log(element.uploadTime.replace('T', ' ').aplit('.')[0])
      // });
    })
    .catch(error => {
      ElMessage.error('获取上传历史失败')
      console.log(error)
    })
}
onMounted(() => {
  updateUploadHistory();
})
</script>

<style lang="scss" scoped>
.history-section {
  h3 {
    margin-bottom: 15px;
    color: var(--el-text-color-primary);
  }

  .analysis-records {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
    gap: 5px;
  }
}
</style>