<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2><i class="el-icon-data-analysis"></i> 特征重要性分析</h2>
      <p class="page-desc">展示销售预测模型中各个特征的重要性，帮助理解模型决策过程</p>
    </div>

    <div class="upload-toolbar">
      <div class="toolbar-left">
        <el-upload
          ref="toolbarUpload"
          class="toolbar-upload"
          :limit="1"
          accept=".xlsx,.xls,.csv"
          :http-request="customUpload"
          :disabled="upload.isUploading"
          :on-change="handleFileChange"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :auto-upload="false"
          :show-file-list="false"
        >
          <el-button plain>上传文件</el-button>
        </el-upload>
        <el-button :loading="upload.isUploading" type="primary" @click="submitUpload">分析特征</el-button>
        <el-button type="success" :disabled="!hasResults" @click="exportResults">导出结果</el-button>
      </div>
      <div class="toolbar-status" v-if="upload.fileName">已上传：{{ upload.fileName }}</div>
      <div class="toolbar-status" v-else-if="upload.pendingFileName">已选择：{{ upload.pendingFileName }}</div>
      <div class="toolbar-status muted" v-else>未上传</div>
    </div>

    <!-- 特征重要性雷达图 -->
    <div class="bg-white rounded-xl p-6 mb-20 shadow-sm">
      <div class="flex justify-between items-center mb-6">
        <h3 class="text-lg font-semibold text-gray-800">特征重要性雷达图</h3>
        <div class="text-sm" v-if="hasResults">
          <span class="text-green-700 font-medium">
            <i class="fa fa-check-circle mr-1"></i>
            特征重要性分析完成
          </span>
        </div>
      </div>
      <div class="h-96">
        <canvas ref="featureRadarRef"></canvas>
      </div>
    </div>

    <!-- 特征重要性详情 -->
    <div class="bg-white rounded-xl p-6 mb-20 shadow-sm">
      <h3 class="text-lg font-semibold text-gray-800 mb-6">特征重要性详情</h3>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead>
          <tr>
            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">特征名称</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">重要性</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">重要性等级</th>
            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">说明</th>
          </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(feature, index) in featureDetails" :key="index">
            <td class="px-4 py-3 text-sm font-medium text-gray-800">{{ feature.name }}</td>
            <td class="px-4 py-3 text-sm">
              <div class="flex items-center">
                <span class="text-sm font-medium">{{ feature.importance }}%</span>
                <div class="ml-2 flex-1">
                  <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-blue-500 h-2 rounded-full" :style="{ width: feature.importance + '%' }"></div>
                  </div>
                </div>
              </div>
            </td>
            <td class="px-4 py-3 text-sm">
              <span :class="feature.importanceClass">{{ feature.importanceLevel }}</span>
            </td>
            <td class="px-4 py-3 text-sm text-gray-600">{{ feature.description }}</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 特征相关性分析 -->
    <div class="bg-white rounded-xl p-6 mb-20 shadow-sm">
      <h3 class="text-lg font-semibold text-gray-800 mb-6">特征相关性分析</h3>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div v-for="(correlation, index) in featureCorrelations" :key="index" class="p-4 border border-gray-200 rounded-lg">
          <h4 class="text-md font-medium text-gray-700 mb-3">{{ correlation.title }}</h4>
          <div class="flex items-center">
            <span class="text-sm font-medium">{{ correlation.value }}%</span>
            <div class="ml-2 flex-1">
              <div class="w-full bg-gray-200 rounded-full h-2">
                <div class="bg-green-500 h-2 rounded-full" :style="{ width: Math.abs(correlation.value) + '%' }"></div>
              </div>
            </div>
          </div>
          <p class="text-xs text-gray-500 mt-2">{{ correlation.description }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, beforeUnmount } from 'vue'
import { analyzeSaleTrendWithFile, getSaleTrendResults, predictSalesTrend } from '@/api/client'
import { Chart } from 'chart.js'

export default {
  name: 'FeatureImportanceAnalysis',
  data() {
    return {
      featureRadarChart: null,
      upload: {
        isUploading: false,
        fileName: '',
        pendingFileName: '',
        ignoreFileChange: false
      },
      results: {}
    }
  },
  computed: {
    hasResults() {
      return Object.keys(this.results || {}).length > 0
    },
    featureImportance() {
      return this.results.feature_importance || {
        features: [
          '价格',
          '促销力度',
          '退款率',
          '季节性',
          '时间趋势',
          '品类影响',
          'SKU影响'
        ],
        importance: [15, 15, 10, 15, 20, 10, 15]
      }
    },
    featureDetails() {
      const features = this.featureImportance.features
      const importance = this.featureImportance.importance
      
      const descriptions = {
        '价格': '产品价格对销量的影响程度',
        '促销力度': '促销活动对销量的促进作用',
        '退款率': '退款率对销售表现的负面影响',
        '季节性': '季节因素对销量的影响',
        '时间趋势': '时间推移对销量的整体影响',
        '品类影响': '不同品类对销量的影响差异',
        'SKU影响': '不同SKU对销量的影响差异'
      }
      
      return features.map((feature, index) => {
        const importanceValue = importance[index] || 0
        let importanceLevel = '低'
        let importanceClass = 'text-red-600'
        
        if (importanceValue >= 20) {
          importanceLevel = '高'
          importanceClass = 'text-green-600'
        } else if (importanceValue >= 10) {
          importanceLevel = '中'
          importanceClass = 'text-yellow-600'
        }
        
        return {
          name: feature,
          importance: importanceValue,
          importanceLevel: importanceLevel,
          importanceClass: importanceClass,
          description: descriptions[feature] || ''
        }
      })
    },
    featureCorrelations() {
      return [
        {
          title: '价格与销量相关性',
          value: -35,
          description: '价格上涨通常会导致销量下降'
        },
        {
          title: '促销力度与销量相关性',
          value: 65,
          description: '促销力度越大，销量通常越高'
        },
        {
          title: '退款率与销量相关性',
          value: -40,
          description: '退款率高会影响产品口碑，导致销量下降'
        },
        {
          title: '季节性与销量相关性',
          value: 50,
          description: '季节性因素对销量有显著影响'
        }
      ]
    }
  },
  mounted() {
    console.log('Component mounted, calling getList()...')
    this.getList()
  },
  beforeUnmount() {
    if (this.featureRadarChart) this.featureRadarChart.destroy()
  },
  methods: {
    /** 获取销售分析结果 */
    getList() {
      console.log('Getting sales trend results...')
      getSaleTrendResults().then(response => {
        console.log('Get results response:', response)
        if (response && response.success && response.data) {
          const results = response.data || {}
          console.log('Sales trend results:', results)
          this.results = results
          this.$nextTick(() => {
            console.log('Rendering feature radar chart...')
            this.renderFeatureRadarChart()
          })
        }
      }).catch(error => {
        console.error('Error getting sales trend results:', error)
        // 即使出错，也使用默认数据显示雷达图
        this.results = {
          feature_importance: {
            features: [
              '价格',
              '促销力度',
              '退款率',
              '季节性',
              '时间趋势',
              '品类影响',
              'SKU影响'
            ],
            importance: [15, 15, 10, 15, 20, 10, 15]
          }
        }
        this.$nextTick(() => {
          console.log('Rendering feature radar chart with default data...')
          this.renderFeatureRadarChart()
        })
      })
    },
    /** 文件选择改变处理 */
    handleFileChange(file, fileList) {
      if (this.upload.ignoreFileChange) return
      console.log('handleFileChange called')
      console.log('file:', file)
      console.log('fileList:', fileList)
      if (!fileList || fileList.length === 0) return
      if (!file || !file.raw) return

      this.upload.pendingFileName = file.name
      this.upload.fileName = ''
      console.log('pendingFileName set to:', this.upload.pendingFileName)
    },
    handleUploadSuccess(response, file, fileList) {
      console.log('handleUploadSuccess called')
      console.log('response:', response)
      console.log('file:', file)
    },
    handleUploadError(error, file, fileList) {
      console.error('handleUploadError called')
      console.error('error:', error)
      console.error('file:', file)
    },
    /** 文件上传前的校验 */
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel' ||
        file.type === 'text/csv' ||
        file.name.endsWith('.xlsx') ||
        file.name.endsWith('.xls') ||
        file.name.endsWith('.csv')
      const isLt500M = file.size / 1024 / 1024 < 500

      if (!isExcel) {
        this.$modal.msgError('上传文件只能是 xlsx/xls/csv 格式!')
        return false
      }
      if (!isLt500M) {
        this.$modal.msgError('上传文件大小不能超过 500MB!')
        return false
      }
      return true
    },
    customUpload(options) {
      console.log('customUpload called')
      console.log('options:', options)
      console.log('options.file:', options.file)
      if (!options.file) {
        console.error('No file in options')
        this.$modal.msgError('请选择要上传的文件')
        options.onError(new Error('No file to upload'))
        return
      }
      console.log('options.file.raw:', options.file.raw)
      const file = options.file.raw || options.file
      console.log('file to upload:', file)
      if (!file) {
        console.error('No file to upload')
        this.$modal.msgError('请选择要上传的文件')
        options.onError(new Error('No file to upload'))
        return
      }
      console.log('Starting file upload and analysis...')
      this.upload.isUploading = true
      analyzeSaleTrendWithFile(file).then(response => {
        console.log('analyzeSaleTrendWithFile response:', response)
        this.upload.isUploading = false
        if (response && response.success) {
          const results = response.data || {}
          console.log('Upload analysis results:', results)
          this.results = results
          this.$modal.msgSuccess('文件上传并分析成功')
          this.upload.fileName = this.upload.pendingFileName || file.name
          this.upload.pendingFileName = ''
          this.$nextTick(() => {
            console.log('Rendering feature radar chart...')
            this.renderFeatureRadarChart()
          })
          options.onSuccess(response)
        } else {
          console.error('Upload failed with response:', response)
          this.$modal.msgError(response.message || '分析失败')
          options.onError(new Error(response.message || '分析失败'))
        }
      }).catch(error => {
        console.error('analyzeSaleTrendWithFile error:', error)
        this.upload.isUploading = false
        const msg = (error && error.message) || '文件上传失败，请重试'
        this.$modal.msgError(msg)
        options.onError(error)
        // 即使上传失败，也使用默认数据显示雷达图
        this.results = {
          feature_importance: {
            features: [
              '价格',
              '促销力度',
              '退款率',
              '季节性',
              '时间趋势',
              '品类影响',
              'SKU影响'
            ],
            importance: [15, 15, 10, 15, 20, 10, 15]
          }
        }
        this.$nextTick(() => {
          console.log('Rendering feature radar chart with default data...')
          this.renderFeatureRadarChart()
        })
      }).finally(() => {
        if (this.$refs.toolbarUpload) {
          this.upload.ignoreFileChange = true
          this.$refs.toolbarUpload.clearFiles()
          this.$nextTick(() => {
            this.upload.ignoreFileChange = false
          })
        }
      })
    },
    submitUpload() {
      console.log('submitUpload called')
      const target = this.$refs.toolbarUpload
      console.log('target:', target)
      if (!target) {
        console.error('No upload component reference')
        this.$modal.msgError('上传组件未初始化')
        return
      }
      const fileList = target.uploadFiles || []
      console.log('fileList:', fileList)
      if (!fileList || fileList.length === 0) {
        console.error('No files selected')
        this.$modal.msgError('请选择要上传的文件')
        return
      }
      console.log('Calling target.submit()')
      target.submit()
    },
    /** 渲染特征重要性雷达图 */
    renderFeatureRadarChart() {
      console.log('Rendering feature radar chart...')
      const canvas = this.$refs.featureRadarRef
      if (!canvas) {
        console.error('No canvas reference found')
        return
      }
      
      console.log('Feature importance data:', this.featureImportance)
      const features = this.featureImportance.features
      const importance = this.featureImportance.importance
      
      console.log('Features:', features)
      console.log('Importance:', importance)
      
      // 确保 features 和 importance 是数组且长度相同
      if (!Array.isArray(features) || !Array.isArray(importance) || features.length !== importance.length) {
        console.error('Invalid feature importance data:', { features, importance })
        // 使用默认数据
        const defaultFeatures = [
          '价格',
          '促销力度',
          '退款率',
          '季节性',
          '时间趋势',
          '品类影响',
          'SKU影响'
        ]
        const defaultImportance = [15, 15, 10, 15, 20, 10, 15]
        this.renderChart(canvas, defaultFeatures, defaultImportance)
        return
      }
      
      this.renderChart(canvas, features, importance)
    },
    /** 渲染雷达图 */
    renderChart(canvas, features, importance) {
      if (this.featureRadarChart) this.featureRadarChart.destroy()
      
      try {
        // 使用 Chart.js v2 语法
        this.featureRadarChart = new Chart(canvas, {
          type: 'radar',
          data: {
            labels: features,
            datasets: [{
              label: '特征重要性',
              data: importance,
              backgroundColor: 'rgba(59, 130, 246, 0.2)',
              borderColor: 'rgba(59, 130, 246, 1)',
              pointBackgroundColor: 'rgba(59, 130, 246, 1)',
              pointBorderColor: '#fff',
              pointHoverBackgroundColor: '#fff',
              pointHoverBorderColor: 'rgba(59, 130, 246, 1)'
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scale: {
              ticks: {
                beginAtZero: true,
                max: 100
              }
            },
            legend: {
              position: 'top'
            },
            tooltips: {
              callbacks: {
                label: function(tooltipItem, data) {
                  return data.labels[tooltipItem.index] + ': ' + data.datasets[0].data[tooltipItem.index] + '%'
                }
              }
            }
          }
        })
        console.log('Chart rendered successfully')
      } catch (error) {
        console.error('Error rendering chart:', error)
      }
    },
    /** 导出结果 */
    exportResults() {
      if (!this.hasResults) {
        this.$modal.msgError('暂无可导出的结果')
        return
      }
      
      const payload = JSON.stringify(this.results || {}, null, 2)
      const blob = new Blob([payload], { type: 'application/json;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `feature_importance_${this.formatUploadDate(new Date())}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },
    /** 格式化上传日期 */
    formatUploadDate(date) {
      const d = date instanceof Date ? date : new Date(date)
      if (Number.isNaN(d.getTime())) return ''
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;

  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;

    i {
      margin-right: 8px;
      color: #409EFF;
    }
  }

  .page-desc {
    color: #909399;
    font-size: 14px;
    margin: 0;
  }
}

.mb-20 { margin-bottom: 20px; }

.upload-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border: 1px solid #e6eaf2;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-upload ::v-deep .el-upload {
  display: inline-flex;
}

.toolbar-status {
  font-size: 13px;
  color: #16a34a;
  background: #f0fdf4;
  border: 1px solid #dcfce7;
  border-radius: 6px;
  padding: 6px 10px;
}

.toolbar-status.muted {
  color: #6b7280;
  background: #f8fafc;
  border-color: #e2e8f0;
}

.p-6 { padding: 24px; }
.p-4 { padding: 16px; }
.px-4 { padding-left: 16px; padding-right: 16px; }
.py-3 { padding-top: 12px; padding-bottom: 12px; }
.mb-6 { margin-bottom: 24px; }
.mt-2 { margin-top: 8px; }
.mt-3 { margin-top: 12px; }

.flex { display: flex; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.gap-2 { gap: 8px; }
.gap-6 { gap: 24px; }

.grid { display: grid; }
.grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); }
.overflow-x-auto { overflow-x: auto; }
.min-w-full { min-width: 100%; }

.text-3xl { font-size: 22px; line-height: 1.3; }
.text-base { font-size: 16px; line-height: 1.5; }
.text-lg { font-size: 18px; line-height: 1.5; }
.text-md { font-size: 16px; line-height: 1.5; }
.text-sm { font-size: 14px; line-height: 1.5; }
.text-xs { font-size: 12px; line-height: 1.4; }
.font-bold { font-weight: 700; }
.font-semibold { font-weight: 600; }
.font-medium { font-weight: 500; }
.text-left { text-align: left; }
.uppercase { text-transform: uppercase; }
.tracking-wider { letter-spacing: 0.06em; }

.text-gray-900 { color: #111827; }
.text-gray-800 { color: #303133; }
.text-gray-700 { color: #606266; }
.text-gray-600 { color: #909399; }
.text-gray-500 { color: #909399; }
.text-blue-600 { color: #2563eb; }
.text-green-700 { color: #15803d; }
.text-green-600 { color: #16a34a; }
.text-red-600 { color: #dc2626; }
.text-yellow-600 { color: #ca8a04; }

.bg-white { background-color: #ffffff; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-green-500 { background-color: #10b981; }

.border { border: 1px solid #e5e7eb; }
.border-gray-200 { border-color: #e5e7eb; }
.rounded-xl { border-radius: 0.75rem; }
.rounded-lg { border-radius: 0.5rem; }
.rounded-full { border-radius: 9999px; }

.shadow-sm { box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); }

.h-96 { height: 24rem; }

.flex-1 { flex: 1; }
.ml-2 { margin-left: 8px; }

@media (min-width: 768px) {
  .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
</style>