<script setup>
import {ref, onMounted} from 'vue'
import Swiper from '@/components/Swiper/index.vue'
import {downloadFile, downloadList} from '@/api'
import Banner from '@/components/Banner/index.vue'
import DownloadImg from '@/components/downloadImg/index.vue'
import {ElMessage} from 'element-plus'

const currentPage = ref(1)
const currentFilePage = ref(1)

onMounted(() => {
  getList()
})

const list = ref(null)

/**
 * 将带有 Key（路径）的扁平列表转换为树形结构
 * @param {Array} items - 原始数据，每个元素包含 Key, ETag, Size, LastModifiedDateTime 等
 * @returns {Array} 树形数组，每个元素为文件或文件夹节点
 */
const transform = (items) => {
  const root = {children: []}
  const getOrCreateFolder = (parent, name, fullPath) => {
    let folder = parent.children.find((child) => child.name === name && child.type === 'folder')
    if (!folder) {
      folder = {name, type: 'folder', children: [], fullPath}
      parent.children.push(folder)
    }
    return folder
  }

  items.forEach((item) => {
    const parts = item.Key.split('/')
    if (parts.length === 1) {
      root.children.push({
        name: parts[0],
        type: 'file',
        etag: item.ETag,
        size: item.Size,
        lastModified: item.LastModifiedDateTime,
        fullPath: item.Key,
      })
    } else {
      let currentParent = root
      let currentPath = ''
      for (let i = 0; i < parts.length - 1; i++) {
        const folderName = parts[i]
        currentPath += (currentPath ? '/' : '') + folderName
        currentParent = getOrCreateFolder(currentParent, folderName, currentPath + '/')
      }
      const fileName = parts[parts.length - 1]
      currentParent.children.push({
        name: fileName,
        type: 'file',
        etag: item.ETag,
        size: item.Size,
        lastModified: item.LastModifiedDateTime,
        fullPath: item.Key,
      })
    }
  })
  return root.children
}

// el-tree 的 props 配置
const treeProps = {
  children: 'children',
  label: 'name',
}

/**
 * 格式化文件大小
 */
const formatSize = (bytes) => {
  if (!bytes) return ''
  const units = ['B', 'KB', 'MB', 'GB']
  let i = 0
  let size = bytes
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024
    i++
  }
  return size.toFixed(2) + ' ' + units[i]
}

/**
 * 获取下载的文件列表
 */
const getList = () => {
  let params = {
    recursive: true,
    version: true,
    prefix: '',
    bucket: '',
  }
  downloadList(params)
    .then((res) => {
      console.log(res)
      if (res.code == 0 && res?.data?.length > 0) {
        list.value = transform(res.data)
        console.log('list.value===>', list.value)
      }
    })
    .catch((error) => {
      console.log('error', error)
    })
}

/**
 * 下载文件
 */
const downloadFileFN = (data) => {
  console.log('data===>', data)
  let query = {
    bucket: '',
    objname: data.fullPath,
    expiresMinutes: 60,
    isDownload: true,
  }
  downloadFile(query)
    .then((res) => {
      console.log('res===>', res)
      if (res.code === 0 && res.data) {
        window.open(res.data)
      }
    })
    .catch((err) => {
      console.log('err===>', err)
    })
}

// 提示用户敬请期待
const showMsg = () => {
  ElMessage.warning('敬请期待！')
}

const imgType = ref('ios')
const showImgType = ref(false)

const openImg = (type) => {
  imgType.value = type
  showImgType.value = true
}
</script>

<template>
  <div class="page">
    <Banner class="banner" img="banner/download.png" />
    <Swiper
      id="one"
      title="资源下载"
      v-model="currentPage"
      :sourceWidth="1200"
      :sourceHeight="400"
      :show-pagination="false"
      :auto-play="false"
      :showHover="false"
    >
      <template #default>
        <div class="my-card flex j-s">
          <div class="img" @click="openImg('ios')">
            <img src="/static/images/download/ios.png" alt="" />
          </div>
          <div class="img" @click="openImg('android')">
            <img src="/static/images/download/android.png" alt="" />
          </div>
          <div class="img" @click="showMsg">
            <img src="/static/images/download/windows.png" alt="" />
          </div>
        </div>
      </template>
    </Swiper>

    <Swiper
      id="file"
      title="文件下载"
      v-model="currentFilePage"
      :sourceWidth="1200"
      :sourceHeight="400"
      :show-pagination="false"
      :auto-play="false"
      :showHover="false"
    >
      <div class="file-list">
        <el-tree v-if="list && list.length" :data="list" :props="treeProps" accordion node-key="name">
          <template #default="{data}">
            <div class="tree-node">
              <!-- 文件夹图标 -->
              <svg
                v-if="data.type === 'folder'"
                class="node-icon folder-icon"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M2 6C2 4.89543 2.89543 4 4 4H9.17157C9.70199 4 10.2107 4.21071 10.5858 4.58579L12 6H20C21.1046 6 22 6.89543 22 8V18C22 19.1046 21.1046 20 20 20H4C2.89543 20 2 19.1046 2 18V6Z"
                  fill="#F7C948"
                  stroke="#E5A800"
                  stroke-width="1.2"
                />
              </svg>
              <!-- 文件图标 -->
              <svg
                v-else
                class="node-icon file-icon"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M6 2H14.1716C14.702 2 15.2107 2.21071 15.5858 2.58579L19.4142 6.41421C19.7893 6.78929 20 7.29799 20 7.82843V20C20 21.1046 19.1046 22 18 22H6C4.89543 22 4 21.1046 4 20V4C4 2.89543 4.89543 2 6 2Z"
                  fill="#A8C5E0"
                  stroke="#7DA8CC"
                  stroke-width="1.2"
                />
                <path d="M14 2V6C14 7.10457 14.8954 8 16 8H20" stroke="#7DA8CC" stroke-width="1.2" fill="none" />
              </svg>

              <span class="node-label">{{ data.name }}</span>

              <!-- 文件信息（仅文件类型显示） -->
              <template v-if="data.type === 'file'">
                <span class="file-size">{{ formatSize(data.size) }}</span>
                <span class="file-date">{{ data.lastModified }}</span>
                <!-- 下载图标 -->
                <svg
                  class="download-icon"
                  @click.stop="downloadFileFN(data)"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M12 3V15M12 15L8 11M12 15L16 11"
                    stroke="#4A90D9"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M4 17V19C4 20.1046 4.89543 21 6 21H18C19.1046 21 20 20.1046 20 19V17"
                    stroke="#4A90D9"
                    stroke-width="2"
                    stroke-linecap="round"
                  />
                </svg>
              </template>
            </div>
          </template>
        </el-tree>
        <div v-else class="empty-tip">暂无下载资源</div>
      </div>
    </Swiper>

    <DownloadImg :type="imgType" v-model="showImgType" />
  </div>
</template>

<style lang="scss" scoped>
.my-card {
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  .img {
    width: 300px;
    height: 360px;
    padding: 20px;
    box-sizing: border-box;

    img {
      padding: 20px;
      width: 100%;
      height: 100%;

      &:hover {
        cursor: pointer;
        transition: all 0.3s ease;
        transform: translateY(-10px);
      }
    }
  }
}

.file-title {
  text-align: center;
  font-family: 'PingFang SC';
  font-weight: 600;
  font-size: 1.5rem;
  color: #333333;

  &::after {
    content: '';
    display: block;
    width: 120px;
    height: 6px;
    background-color: #0389ff;
    position: relative;
    left: 50%;
    top: 20px;
    translate: -50%;
  }
}

.file-list {
  width: 1200px;
  max-height: 500px;
  border: 1px solid #e5e5e5;
  margin: 0px auto;
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto;
  text-align: left;

  .empty-tip {
    text-align: center;
    color: #999;
    font-size: 14px;
    padding: 40px 0;
  }
}

/* el-tree 节点自定义样式 */
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 4px 0;
  gap: 8px;

  .node-icon {
    width: 20px;
    height: 20px;
    flex-shrink: 0;
  }

  .node-label {
    flex: 1;
    font-size: 14px;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .file-size {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
    min-width: 80px;
    text-align: right;
  }

  .file-date {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
    min-width: 140px;
    text-align: right;
  }

  .download-icon {
    width: 20px;
    height: 20px;
    flex-shrink: 0;
    cursor: pointer;
    transition: opacity 0.2s;

    &:hover {
      opacity: 0.7;
    }
  }
}

/* 覆盖 el-tree 默认样式 */
::v-deep(.el-tree) {
  background: transparent;

  .el-tree-node__content {
    height: auto;
    padding: 6px 0;

    &:hover {
      background-color: #f5f7fa;
    }
  }

  .el-tree-node__expand-icon {
    color: #666;
  }
}
</style>
