<template>
  <view class="folder-select-page">
    <!-- 顶部导航栏 -->
    <view class="header-bg" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header-content">
        <view class="back-btn" @click="handleBack">
          <text class="back-icon">‹</text>
        </view>
        <text class="header-title">选择文件夹</text>
        <view class="placeholder"></view>
      </view>
    </view>
    
    <!-- 项目信息 -->
    <view class="project-info-bar">
      <text class="project-label">当前项目：</text>
      <text class="project-name">{{ projectName }}</text>
    </view>
    
    <!-- 文件夹树状列表 -->
    <scroll-view scroll-y class="folder-list">
      <!-- 调试信息 -->
      <view class="debug-info" style="padding: 20rpx; background: #fff3cd; border-bottom: 1rpx solid #ffc107;">
        <text style="font-size: 24rpx; color: #856404; display: block;">调试信息：</text>
        <text style="font-size: 24rpx; color: #856404; display: block;">文件夹数量: {{ folderTree.length }}</text>
        <text style="font-size: 24rpx; color: #856404; display: block;">加载状态: {{ loading ? '加载中' : '已完成' }}</text>
        <text style="font-size: 24rpx; color: #856404; display: block;">folderTree 是否为数组: {{ Array.isArray(folderTree) ? '是' : '否' }}</text>
        <view v-if="folderTree.length > 0" style="margin-top: 10rpx;">
          <text style="font-size: 24rpx; color: #856404; display: block;">第一个文件夹: {{ folderTree[0].name }}</text>
          <text style="font-size: 24rpx; color: #856404; display: block;">第一个文件夹子节点数: {{ folderTree[0].children?.length || 0 }}</text>
        </view>
      </view>
      
      <!-- 使用树形组件 -->
      <tree-view
        v-if="folderTree.length > 0"
        :tree-data="folderTree"
        :permission="permission"
        @select="handleSelectFolder"
      />
      
      <view v-if="folderTree.length === 0 && !loading" class="empty-tip">
        <text class="empty-text">暂无文件夹</text>
      </view>
      
      <view v-if="loading" class="loading-tip">
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getFolderList, getFolderPermission } from '@/apis/scan'
import TreeView from '@/components/TreeView/index.vue'

export default {
  components: {
    TreeView
  },
  data() {
    return {
      statusBarHeight: 0,
      projectId: 0,
      projectName: '',
      folderTree: [],
      loading: false,
      permission: '*' // 权限配置
    }
  },
  onLoad(options) {
    console.log('页面参数:', options)
    
    this.projectId = parseInt(options.projectId) || 0
    this.projectName = decodeURIComponent(options.projectName || '')
    
    console.log('解析后的projectId:', this.projectId)
    console.log('解析后的projectName:', this.projectName)
  },
  onReady() {
    // 获取系统信息
    const windowInfo = uni.getWindowInfo()
    this.statusBarHeight = windowInfo.statusBarHeight || 0
    
    // 加载数据
    if (this.projectId) {
      this.loadPermission()
      this.loadFolderList()
    } else {
      console.error('projectId 为空，无法加载文件夹列表')
    }
  },
  methods: {
    // 返回上一页
    handleBack() {
      uni.navigateBack()
    },
    
    // 加载权限
    async loadPermission() {
      try {
        console.log('========== 开始加载权限 ==========')
        console.log('projectId:', this.projectId)
        
        const response = await getFolderPermission({
          projectId: this.projectId
        })
        
        console.log('权限响应:', response)
        
        if (response.code === 200 && response.data) {
          this.permission = response.data.content || '*'
          console.log('权限配置:', this.permission)
        } else {
          console.error('权限响应异常:', response)
          this.permission = '*'
        }
      } catch (error) {
        console.error('加载权限失败:', error)
        this.permission = '*'
      }
    },
    
    // 加载文件夹列表
    async loadFolderList() {
      if (this.loading) return
      
      try {
        this.loading = true
        
        console.log('========== 开始加载文件夹列表 ==========')
        console.log('projectId:', this.projectId)
        
        const response = await getFolderList({
          projectId: this.projectId
        })
        
        console.log('========== 后端返回的原始数据 ==========')
        console.log('response:', response)
        console.log('response.code:', response.code)
        console.log('response.msg:', response.msg)
        console.log('response.data:', response.data)
        console.log('response.data 类型:', typeof response.data)
        console.log('response.data 是否为数组:', Array.isArray(response.data))
        
        if (response.code === 200 && response.data) {
          this.folderTree = response.data
          
          console.log('========== 赋值后的 folderTree ==========')
          console.log('folderTree:', this.folderTree)
          console.log('folderTree 长度:', this.folderTree.length)
          console.log('folderTree 是否为数组:', Array.isArray(this.folderTree))
          
          // 打印第一层数据的详细信息
          this.folderTree.forEach((folder, index) => {
            console.log(`========== 第 ${index} 个文件夹 ==========`)
            console.log('完整对象:', folder)
            console.log('id:', folder.id)
            console.log('name:', folder.name)
            console.log('type:', folder.type)
            console.log('children:', folder.children)
            console.log('children 类型:', typeof folder.children)
            console.log('children 是否为数组:', Array.isArray(folder.children))
            console.log('children 长度:', folder.children?.length || 0)
            
            // 如果有子节点，打印第一个子节点
            if (folder.children && folder.children.length > 0) {
              console.log('第一个子节点:', folder.children[0])
            }
          })
        } else {
          console.error('========== 响应异常 ==========')
          console.error('响应码不是200或没有data')
          console.error('完整响应:', response)
        }
      } catch (error) {
        console.error('========== 加载失败 ==========')
        console.error('错误信息:', error)
        console.error('错误堆栈:', error.stack)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        console.log('========== 加载完成 ==========')
      }
    },
    
    // 选择文件夹
    handleSelectFolder(folder) {
      console.log('========== 选择文件夹 ==========')
      console.log('文件夹:', folder.name)
      console.log('文件夹ID:', folder.id)
      console.log('完整路径:', folder.fullPath)
      
      // 从全局数据中获取扫描的fileBase64List
      const fileBase64List = getApp().globalData.scannedFileBase64List
      
      if (!fileBase64List || fileBase64List.length === 0) {
        uni.showToast({
          title: '未找到扫描文件',
          icon: 'none'
        })
        return
      }
      
      // 将文件夹信息存储到全局数据
      getApp().globalData.selectedFolder = {
        folderId: folder.id,
        folderPath: folder.fullPath
      }
      
      // 跳转到编辑上传文件页面
      uni.navigateTo({
        url: `/pages/scan/uploadEdit/index?folderId=${folder.id}&folderPath=${encodeURIComponent(folder.fullPath)}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.folder-select-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  
  // 顶部导航栏
  .header-bg {
    background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
    position: relative;
    z-index: 100;
    
    .header-content {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      
      .back-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        
        .back-icon {
          font-size: 56rpx;
          color: #ffffff;
          font-weight: 300;
        }
      }
      
      .header-title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
      }
      
      .placeholder {
        width: 60rpx;
      }
    }
  }
  
  // 项目信息栏
  .project-info-bar {
    padding: 24rpx;
    background: #ffffff;
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #f5f5f5;
    
    .project-label {
      font-size: 28rpx;
      color: #666666;
      margin-right: 8rpx;
    }
    
    .project-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #1ec9c9;
    }
  }
  
  // 文件夹列表
  .folder-list {
    flex: 1;
    background: #ffffff;
  }
  
  .empty-tip {
    padding: 200rpx 0;
    text-align: center;
    
    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
  
  .loading-tip {
    padding: 32rpx 0;
    text-align: center;
    
    .loading-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
}
</style>
