<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>
    
    <!-- 选择表单 -->
    <view class="form-container">
      <view v-if="loading" class="loading-tip">
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else class="form-content">
        <!-- 国家-中心联动选择 -->
        <view class="form-item">
          <view class="form-label">国家 - 中心：</view>
          <picker 
            mode="multiSelector" 
            :range="pickerRange"
            :value="[selectedCountryIndex, selectedCenterIndex]"
            @change="handleMultiPickerChange"
            @columnchange="handleColumnChange"
          >
            <view class="picker-display">
              <text class="picker-text" :class="{ placeholder: selectedCountryIndex === -1 || selectedCenterIndex === -1 }">
                {{ getDisplayText() }}
              </text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>
        
        <!-- 名称输入 -->
        <view class="form-item highlight-item">
          <view class="form-label required">名称：</view>
          <view class="input-wrapper highlight">
            <input
              v-model="fileName"
              type="text"
              placeholder="请输入名称"
              class="input-field"
            />
          </view>
        </view>
        
        <!-- 生效日期选择 -->
        <view class="form-item">
          <view class="form-label">生效日期：</view>
          <picker 
            mode="date" 
            :value="effectiveDate"
            @change="handleDateChange"
          >
            <view class="picker-display">
              <text class="picker-text" :class="{ placeholder: !effectiveDate }">
                {{ effectiveDate || '请选择生效日期' }}
              </text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>
        
        <!-- 提交按钮 -->
        <button 
          class="confirm-btn" 
          :disabled="selectedCountryIndex < 0 || selectedCenterIndex < 0 || !fileName.trim()"
          @click="handleSubmit"
        >
          提交
        </button>
        
        <!-- 调试信息 -->
        <view class="debug-section">
          <view class="debug-title">调试信息：</view>
          <view class="debug-item">国家数量: {{ countryList.length }}</view>
          <view class="debug-item">中心数量: {{ centerList.length }}</view>
          <view class="debug-item">选中国家: {{ selectedCountryIndex === -1 ? '未选择' : countryList[selectedCountryIndex]?.name }}</view>
          <view class="debug-item">选中中心: {{ selectedCenterIndex === -1 ? '未选择' : centerList[selectedCenterIndex]?.name }}</view>
        </view>
        
        <!-- 原始数据展示 -->
        <view class="raw-data-section">
          <view class="raw-data-title" @click="showRawData = !showRawData">
            原始数据 {{ showRawData ? '▼' : '▶' }}
          </view>
          <view v-if="showRawData" class="json-display">{{ JSON.stringify(rawData, null, 2) }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getFolderList } from '@/apis/scan'
import request from '@/utils/request.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      projectId: 0,
      projectName: '',
      rawData: null,
      loading: false,
      showRawData: false,
      
      // 原始数据列表（用于查找独立的中心）
      allFolders: [],
      
      // 国家列表
      countryList: [],
      selectedCountryIndex: 0, // 默认选中第一个（NA）
      
      // 中心列表
      centerList: [],
      selectedCenterIndex: 0, // 默认选中第一个（NA）
      
      // 名称输入
      fileName: '',
      
      // 生效日期
      effectiveDate: ''
    }
  },
  computed: {
    // 构建选择器的 range 数据
    pickerRange() {
      // 第一列：国家名称数组
      const countryNames = this.countryList.map(item => item.name)
      // 第二列：中心显示名称数组
      const centerNames = this.centerList.map(item => item.displayName || item.name)
      
      return [countryNames, centerNames]
    }
  },
  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.loadFolderList()
    } else {
      console.error('projectId 为空，无法加载文件夹列表')
    }
  },
  methods: {
    // 返回上一页
    handleBack() {
      uni.navigateBack()
    },
    
    // 加载文件夹列表
    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)
        
        // 保存原始数据
        this.rawData = response
        
        // 解析数据
        if (response.code === 200 && response.data && Array.isArray(response.data)) {
          this.allFolders = response.data
          this.parseCountryList(response.data)
        }
        
      } catch (error) {
        console.error('========== 加载失败 ==========')
        console.error('错误信息:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        console.log('========== 加载完成 ==========')
      }
    },
    
    // 解析国家列表（type === 1 为国家）
    parseCountryList(data) {
      const countries = data.filter(item => {
        return item.type === 1 // 国家类型
      })
      
      // 在列表开头添加 NA 选项
      this.countryList = [
        { id: 'NA', name: 'NA', type: 1, children: [], displayName: 'NA' },
        ...countries
      ]
      
      console.log('解析后的国家列表:', this.countryList)
      
      // 初始化时加载第一个国家（NA）的中心列表
      if (this.countryList.length > 0) {
        this.loadCenterList(0)
      }
    },
    
    // 加载中心列表
    loadCenterList(countryIndex) {
      if (countryIndex >= 0 && this.countryList[countryIndex]) {
        const country = this.countryList[countryIndex]
        
        // 如果选择的是 NA（第一个选项）
        if (country.id === 'NA') {
          // 获取所有不属于任何国家的中心
          this.centerList = this.getIndependentCenters()
        } else {
          // 选择了具体国家，显示该国家下的所有中心（包括子中心）
          const allCenters = this.getAllCentersRecursive(country.children || [])
          
          // 在列表开头添加 NA 选项
          this.centerList = [
            { id: 'NA', name: 'NA', type: 2, displayName: 'NA' },
            ...allCenters
          ]
        }
        
        console.log('国家:', country.name, '中心列表:', this.centerList)
      } else {
        this.centerList = [{ id: 'NA', name: 'NA', type: 2, displayName: 'NA' }]
      }
    },
    
    // 递归获取所有中心（包括子中心）
    getAllCentersRecursive(nodes, prefix = '') {
      let centers = []
      
      nodes.forEach(node => {
        // 如果是中心类型（type === 2）
        if (node.type === 2) {
          // 添加当前中心，名称带层级前缀
          const displayName = prefix ? `${prefix} > ${node.name}` : node.name
          centers.push({
            ...node,
            displayName: displayName, // 用于显示的名称
            originalName: node.name   // 保留原始名称
          })
          
          // 如果有子节点，递归获取
          if (node.children && node.children.length > 0) {
            const subCenters = this.getAllCentersRecursive(node.children, displayName)
            centers = centers.concat(subCenters)
          }
        } else if (node.children && node.children.length > 0) {
          // 如果不是中心但有子节点，继续递归
          const subCenters = this.getAllCentersRecursive(node.children, prefix)
          centers = centers.concat(subCenters)
        }
      })
      
      return centers
    },
    
    // 多列选择器列变化
    handleColumnChange(e) {
      const column = e.detail.column // 哪一列变化了
      const value = e.detail.value   // 变化后的值
      
      console.log('列变化:', column, '值:', value)
      
      // 如果是第一列（国家）变化
      if (column === 0) {
        this.selectedCountryIndex = value
        // 重新加载中心列表
        this.loadCenterList(value)
        // 重置中心选择为第一个
        this.selectedCenterIndex = 0
      }
    },
    
    // 多列选择器确认
    handleMultiPickerChange(e) {
      const values = e.detail.value
      this.selectedCountryIndex = values[0]
      this.selectedCenterIndex = values[1]
      
      console.log('选择完成 - 国家索引:', this.selectedCountryIndex, '中心索引:', this.selectedCenterIndex)
      
      if (this.countryList[this.selectedCountryIndex]) {
        console.log('选中国家:', this.countryList[this.selectedCountryIndex].name)
      }
      if (this.centerList[this.selectedCenterIndex]) {
        console.log('选中中心:', this.centerList[this.selectedCenterIndex].name)
      }
    },
    
    // 获取显示文本
    getDisplayText() {
      if (this.selectedCountryIndex >= 0 && this.selectedCenterIndex >= 0) {
        const country = this.countryList[this.selectedCountryIndex]
        const center = this.centerList[this.selectedCenterIndex]
        
        if (country && center) {
          const centerName = center.displayName || center.name
          return `${country.name} - ${centerName}`
        }
      }
      return '请选择国家和中心'
    },
    
    // 日期选择变化
    handleDateChange(e) {
      this.effectiveDate = e.detail.value
      console.log('选择的生效日期:', this.effectiveDate)
    },
    
    // 获取所有不属于任何国家的中心
    getIndependentCenters() {
      // 收集所有国家下的中心ID
      const centerIdsInCountries = new Set()
      
      this.allFolders.forEach(folder => {
        if (folder.type === 1 && folder.children) { // 国家类型
          this.collectAllCenterIds(folder.children, centerIdsInCountries)
        }
      })
      
      // 找出所有不在国家下的中心（直接在根目录下的中心）
      const independentCenters = this.allFolders.filter(folder => {
        return folder.type === 2 && !centerIdsInCountries.has(folder.id)
      })
      
      // 递归获取这些独立中心及其子中心
      const allIndependentCenters = this.getAllCentersRecursive(independentCenters)
      
      // 在列表开头添加 NA 选项
      return [
        { id: 'NA', name: 'NA', type: 2, displayName: 'NA' },
        ...allIndependentCenters
      ]
    },
    
    // 收集所有中心ID（递归）
    collectAllCenterIds(nodes, centerIds) {
      nodes.forEach(node => {
        if (node.type === 2) {
          centerIds.add(node.id)
        }
        if (node.children && node.children.length > 0) {
          this.collectAllCenterIds(node.children, centerIds)
        }
      })
    },
    
    // 中心选择变化（保留以防需要）
    handleCenterChange(e) {
      const index = parseInt(e.detail.value)
      this.selectedCenterIndex = index
      
      if (index >= 0 && this.centerList[index]) {
        console.log('选中中心:', this.centerList[index].name)
      }
    },
    
    // 提交
    async handleSubmit() {
      if (this.selectedCountryIndex < 0) {
        uni.showToast({
          title: '请选择国家',
          icon: 'none'
        })
        return
      }
      
      if (this.selectedCenterIndex < 0) {
        uni.showToast({
          title: '请选择中心',
          icon: 'none'
        })
        return
      }
      
      if (!this.fileName.trim()) {
        uni.showToast({
          title: '请输入名称',
          icon: 'none'
        })
        return
      }
      
      const selectedCountry = this.countryList[this.selectedCountryIndex]
      const selectedCenter = this.centerList[this.selectedCenterIndex]
      
      // 从全局数据中获取扫描的fileBase64List
      const fileBase64List = getApp().globalData.scannedFileBase64List
      
      if (!fileBase64List || fileBase64List.length === 0) {
        uni.showToast({
          title: '未找到扫描文件',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '提交中...',
          mask: true
        })
        
        // 构建请求参数
        const params = {
          projectId: this.projectId,
          country: selectedCountry.id === 'NA' ? 0 : selectedCountry.id,
          center: selectedCenter.id === 'NA' ? 0 : selectedCenter.id,
          name: this.fileName.trim(),
          effectiveDate: this.effectiveDate || '',
          files: fileBase64List
        }
        
        console.log('========== 提交参数 ==========')
        console.log('params:', params)
        
        // 调用上传接口
        const response = await request({
          url: '/applet/scan/upload',
          method: 'POST',
          data: params
        })
        
        console.log('========== 上传响应 ==========')
        console.log('response:', response)
        
        uni.hideLoading()
        
        if (response.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
          })
          
          // 清空全局数据
          getApp().globalData.scannedFileBase64List = []
          
          // 延迟返回首页
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }, 2000)
        } else {
          throw new Error(response.msg || '提交失败')
        }
        
      } catch (error) {
        uni.hideLoading()
        console.error('========== 提交失败 ==========')
        console.error('错误信息:', error)
        uni.showToast({
          title: error.message || '提交失败',
          icon: 'none'
        })
      }
    },
    
    // 确认选择（保留旧方法以防其他地方调用）
    handleConfirm() {
      this.handleSubmit()
    }
  }
}
</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;
    }
  }
  
  // 表单容器
  .form-container {
    flex: 1;
    overflow-y: auto;
  }
  
  .form-content {
    padding: 32rpx;
  }
  
  .form-item {
    margin-bottom: 32rpx;
    
    &.highlight-item {
      .form-label {
        font-size: 32rpx;
        color: #1ec9c9;
        
        &.required::after {
          content: ' *';
          color: #ff4444;
        }
      }
    }
    
    .form-label {
      font-size: 28rpx;
      color: #333333;
      font-weight: 600;
      margin-bottom: 16rpx;
    }
    
    .input-wrapper {
      background: #ffffff;
      border: 2rpx solid #e0e0e0;
      border-radius: 12rpx;
      padding: 24rpx;
      transition: all 0.3s;
      
      &.highlight {
        border: 3rpx solid #1ec9c9;
        background: linear-gradient(135deg, #f0fffe 0%, #ffffff 100%);
        box-shadow: 0 4rpx 12rpx rgba(30, 201, 201, 0.15);
        padding: 28rpx;
      }
      
      &:focus-within {
        border-color: #1ec9c9;
        box-shadow: 0 0 0 4rpx rgba(30, 201, 201, 0.1);
      }
      
      .input-field {
        width: 100%;
        font-size: 28rpx;
        color: #333333;
        
        &::placeholder {
          color: #999999;
        }
      }
    }
    
    .picker-display {
      background: #ffffff;
      border: 2rpx solid #e0e0e0;
      border-radius: 12rpx;
      padding: 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all 0.3s;
      
      &.disabled {
        background: #f5f5f5;
        opacity: 0.6;
      }
      
      .picker-text {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
        
        &.placeholder {
          color: #999999;
        }
      }
      
      .picker-arrow {
        font-size: 40rpx;
        color: #999999;
        font-weight: 300;
        margin-left: 16rpx;
      }
    }
  }
  
  .confirm-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #1ec9c9 0%, #1eb8b8 100%);
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 600;
    border-radius: 16rpx;
    border: none;
    margin-top: 32rpx;
    transition: all 0.3s;
    box-shadow: 0 6rpx 20rpx rgba(30, 201, 201, 0.3);
    
    &:disabled {
      background: #cccccc;
      box-shadow: none;
      opacity: 0.6;
    }
    
    &:active:not(:disabled) {
      opacity: 0.9;
      transform: scale(0.98);
    }
    
    &::after {
      border: none;
    }
  }
  
  // 调试信息
  .debug-section {
    margin-top: 48rpx;
    padding: 24rpx;
    background: #fff3cd;
    border-radius: 12rpx;
    border: 1rpx solid #ffc107;
    
    .debug-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #856404;
      margin-bottom: 12rpx;
    }
    
    .debug-item {
      font-size: 24rpx;
      color: #856404;
      line-height: 1.8;
    }
  }
  
  // 原始数据
  .raw-data-section {
    margin-top: 32rpx;
    
    .raw-data-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #666666;
      padding: 16rpx;
      background: #f5f5f5;
      border-radius: 8rpx;
      cursor: pointer;
      
      &:active {
        background: #e0e0e0;
      }
    }
    
    .json-display {
      margin-top: 16rpx;
      background: #f5f5f5;
      padding: 24rpx;
      border-radius: 8rpx;
      font-size: 22rpx;
      color: #333333;
      font-family: 'Courier New', monospace;
      line-height: 1.6;
      word-break: break-all;
      white-space: pre-wrap;
    }
  }
  
  .loading-tip {
    padding: 200rpx 0;
    text-align: center;
    
    .loading-text {
      font-size: 28rpx;
      color: #999999;
    }
  }
}
</style>
