<template>
  <div class="prediction-view">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>按店铺预测</span>
          <el-tooltip content="使用针对特定店铺训练的模型进行销售预测">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
      </template>

      <div class="model-selection-section">
        <h4>🎯 选择预测模型</h4>
        <el-form :model="form" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="目标店铺">
                <StoreSelector 
                  v-model="form.store_id"
                  @change="handleStoreChange"
                  :show-all-option="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="算法类型">
                <el-select
                  v-model="form.model_type"
                  placeholder="选择算法"
                  @change="handleModelTypeChange"
                  style="width: 100%"
                  :disabled="!form.store_id"
                >
                  <el-option
                    v-for="item in modelTypes"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" v-if="form.model_type">
            <el-col :span="5">
              <el-form-item label="模型版本">
                <el-select
                  v-model="form.version"
                  placeholder="选择版本"
                  style="width: 100%"
                  :disabled="!availableVersions.length"
                  :loading="versionsLoading"
                >
                  <el-option
                    v-for="version in availableVersions"
                    :key="version"
                    :label="version"
                    :value="version"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="预测天数">
                <el-input-number
                  v-model="form.future_days"
                  :min="1"
                  :max="365"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="历史天数">
                <el-input-number
                  v-model="form.history_lookback_days"
                  :min="7"
                  :max="365"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="起始日期">
                <el-date-picker
                  v-model="form.start_date"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :clearable="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="预测分析">
                <el-switch
                  v-model="form.analyze_result"
                  active-text="开启"
                  inactive-text="关闭"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="prediction-actions">
        <el-button
          type="primary"
          size="large"
          @click="startPrediction"
          :loading="predicting"
          :disabled="!canPredict"
        >
          <el-icon><TrendCharts /></el-icon>
          开始预测
        </el-button>
      </div>
    </el-card>

    <el-card v-if="predictionResult" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>📈 预测结果</span>
        </div>
      </template>
      <div class="prediction-chart">
        <canvas ref="chartCanvas" width="800" height="400"></canvas>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { QuestionFilled, TrendCharts } from '@element-plus/icons-vue'
import Chart from 'chart.js/auto'
import StoreSelector from '../../components/StoreSelector.vue'

const modelTypes = ref([])
const availableVersions = ref([])
const versionsLoading = ref(false)
const predicting = ref(false)
const predictionResult = ref(null)
const chartCanvas = ref(null)
let chart = null

const form = reactive({
  training_mode: 'store',
  store_id: '',
  model_type: '',
  version: '',
  future_days: 7,
  history_lookback_days: 30,
  start_date: '',
  analyze_result: true
})

const canPredict = computed(() => {
  return form.store_id && form.model_type && form.version
})

const fetchModelTypes = async () => {
  try {
    const response = await axios.get('/api/model_types')
    if (response.data.status === 'success') {
      modelTypes.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取模型类型失败')
  }
}

const fetchAvailableVersions = async () => {
  if (!form.store_id || !form.model_type) {
    availableVersions.value = []
    return
  }
  try {
    versionsLoading.value = true
    const url = `/api/models/store/${form.store_id}/${form.model_type}/versions`
    const response = await axios.get(url)
    if (response.data.status === 'success') {
      availableVersions.value = response.data.data.versions || []
      if (response.data.data.latest_version) {
        form.version = response.data.data.latest_version
      }
    }
  } catch (error) {
    availableVersions.value = []
  } finally {
    versionsLoading.value = false
  }
}

const handleStoreChange = () => {
  form.model_type = ''
  form.version = ''
  availableVersions.value = []
}

const handleModelTypeChange = () => {
  form.version = ''
  fetchAvailableVersions()
}

const startPrediction = async () => {
  try {
    predicting.value = true
    const payload = {
      training_mode: form.training_mode,
      store_id: form.store_id,
      model_type: form.model_type,
      version: form.version,
      future_days: form.future_days,
      history_lookback_days: form.history_lookback_days,
      start_date: form.start_date,
      analyze_result: form.analyze_result,
    }
    const response = await axios.post('/api/prediction', payload)
    if (response.data.status === 'success') {
      predictionResult.value = response.data.data
      ElMessage.success('预测完成！')
      await nextTick()
      renderChart()
    } else {
      ElMessage.error(response.data.message || '预测失败')
    }
  } catch (error) {
    ElMessage.error('预测请求失败')
  } finally {
    predicting.value = false
  }
}

const renderChart = () => {
  if (!chartCanvas.value || !predictionResult.value) return
  if (chart) {
    chart.destroy()
  }

  const formatDate = (date) => new Date(date).toISOString().split('T')[0];

  const historyData = (predictionResult.value.history_data || []).map(p => ({ ...p, date: formatDate(p.date) }));
  const predictionData = (predictionResult.value.prediction_data || []).map(p => ({ ...p, date: formatDate(p.date) }));

  if (historyData.length === 0 && predictionData.length === 0) {
    ElMessage.warning('没有可用于图表的数据。')
    return
  }

  const allLabels = [...new Set([...historyData.map(p => p.date), ...predictionData.map(p => p.date)])].sort()
  const simplifiedLabels = allLabels.map(date => date.split('-')[2]);

  const historyMap = new Map(historyData.map(p => [p.date, p.sales]))
  const predictionMap = new Map(predictionData.map(p => [p.date, p.predicted_sales]))

  const alignedHistorySales = allLabels.map(label => historyMap.get(label) ?? null)
  const alignedPredictionSales = allLabels.map(label => predictionMap.get(label) ?? null)

  if (historyData.length > 0 && predictionData.length > 0) {
    const lastHistoryDate = historyData[historyData.length - 1].date
    const lastHistoryValue = historyData[historyData.length - 1].sales
    if (!predictionMap.has(lastHistoryDate)) {
       alignedPredictionSales[allLabels.indexOf(lastHistoryDate)] = lastHistoryValue
    }
  }

  let subtitleText = '';
  if (historyData.length > 0) {
      subtitleText += `历史数据: ${historyData[0].date} ~ ${historyData[historyData.length - 1].date}`;
  }
  if (predictionData.length > 0) {
      if (subtitleText) subtitleText += '  |  ';
      subtitleText += `预测数据: ${predictionData[0].date} ~ ${predictionData[predictionData.length - 1].date}`;
  }

  chart = new Chart(chartCanvas.value, {
    type: 'line',
    data: {
      labels: simplifiedLabels,
      datasets: [
        {
          label: '历史销量',
          data: alignedHistorySales,
          borderColor: '#67C23A',
          backgroundColor: 'rgba(103, 194, 58, 0.2)',
          tension: 0.4,
          fill: true,
          spanGaps: false,
        },
        {
          label: '预测销量',
          data: alignedPredictionSales,
          borderColor: '#409EFF',
          backgroundColor: 'rgba(64, 158, 255, 0.2)',
          tension: 0.4,
          fill: true,
          borderDash: [5, 5],
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: `“店铺${form.store_id}” - 销量预测趋势图`,
          font: { size: 18 }
        },
        subtitle: {
            display: true,
            text: subtitleText,
            padding: {
                bottom: 20
            },
            font: { size: 14 }
        }
      },
      scales: {
        x: {
          title: {
            display: true,
            text: '日期 (日)'
          },
          grid: {
            display: false
          }
        },
        y: {
          title: {
            display: true,
            text: '销量'
          },
          grid: {
            color: '#e9e9e9',
            drawBorder: false,
          },
          beginAtZero: true
        }
      }
    }
  })
}

onMounted(() => {
  fetchModelTypes()
  const today = new Date()
  form.start_date = today.toISOString().split('T')[0]
})

watch([() => form.store_id, () => form.model_type], () => {
  fetchAvailableVersions()
})
</script>

<style scoped>
.prediction-view {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.model-selection-section h4 {
  margin-bottom: 16px;
}
.prediction-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
.prediction-chart {
  margin-top: 20px;
}
</style>