<template>
  <div class="budget-estimator">
    <el-card class="estimator-card">
      <template #header>
        <div class="card-header">
          <span><i class="el-icon-money"></i> EC2 预算估算</span>
          <div class="card-subtitle">规划您的云计算花费，避免预算超支</div>
        </div>
      </template>

      <div class="form-container">
        <el-form :model="form" label-width="120px">
          <el-row :gutter="20">
            <el-col :md="12" :sm="24">
              <el-form-item label="实例类型">
                <el-select v-model="form.instance_type" placeholder="请选择实例类型" class="full-width">
                  <el-option
                    v-for="type in instanceTypes"
                    :key="type"
                    :label="type"
                    :value="type">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :md="12" :sm="24">
              <el-form-item label="区域">
                <el-select v-model="form.region" placeholder="请选择区域" class="full-width">
                  <el-option
                    v-for="region in regions"
                    :key="region.code"
                    :label="region.name"
                    :value="region.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :md="12" :sm="24">
              <el-form-item label="操作系统">
                <el-select v-model="form.operating_system" placeholder="请选择操作系统" class="full-width">
                  <el-option label="Linux" value="Linux">
                    <div class="option-with-icon">
                      <span class="option-icon">🐧</span>
                      <span>Linux</span>
                    </div>
                  </el-option>
                  <el-option label="Windows" value="Windows">
                    <div class="option-with-icon">
                      <span class="option-icon">🪟</span>
                      <span>Windows</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :md="12" :sm="24">
              <el-form-item label="购买选项">
                <el-select v-model="form.purchase_option" placeholder="请选择购买选项" class="full-width">
                  <el-option label="按需实例" value="OnDemand">
                    <div class="option-with-icon">
                      <span class="option-icon">⏱️</span>
                      <span>按需实例</span>
                    </div>
                  </el-option>
                  <el-option label="预留实例" value="Reserved">
                    <div class="option-with-icon">
                      <span class="option-icon">📅</span>
                      <span>预留实例</span>
                    </div>
                  </el-option>
                  <el-option label="Spot实例" value="Spot">
                    <div class="option-with-icon">
                      <span class="option-icon">💸</span>
                      <span>Spot实例</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="center">
            <i class="el-icon-time"></i> 使用时长设置
          </el-divider>

          <el-form-item>
            <el-radio-group v-model="form.duration_type" class="duration-radio-group">
              <el-radio-button label="preset">
                <div class="radio-content">
                  <i class="el-icon-star-off"></i>
                  <span>预设时长</span>
                </div>
              </el-radio-button>
              <el-radio-button label="custom">
                <div class="radio-content">
                  <i class="el-icon-edit"></i>
                  <span>自定义</span>
                </div>
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <div v-if="form.duration_type === 'custom'" class="custom-duration">
            <el-form-item label="月数">
              <el-slider 
                v-model="form.duration" 
                :min="1" 
                :max="36" 
                :format-tooltip="formatDuration"
                :marks="{1: '1个月', 12: '1年', 36: '3年'}"
                class="duration-slider">
              </el-slider>
            </el-form-item>
          </div>

          <div v-else class="preset-duration">
            <el-form-item label="预设时长">
              <el-radio-group v-model="form.preset_duration" class="preset-radio-group">
                <el-radio :label="1">
                  <div class="duration-option">
                    <span class="duration-icon">1</span>
                    <span>1个月</span>
                  </div>
                </el-radio>
                <el-radio :label="3">
                  <div class="duration-option">
                    <span class="duration-icon">3</span>
                    <span>3个月</span>
                  </div>
                </el-radio>
                <el-radio :label="6">
                  <div class="duration-option">
                    <span class="duration-icon">6</span>
                    <span>6个月</span>
                  </div>
                </el-radio>
                <el-radio :label="12">
                  <div class="duration-option">
                    <span class="duration-icon">12</span>
                    <span>1年</span>
                  </div>
                </el-radio>
                <el-radio :label="36">
                  <div class="duration-option">
                    <span class="duration-icon">36</span>
                    <span>3年</span>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="form-actions">
            <el-button type="primary" @click="calculateBudget" icon="el-icon-money" class="calculate-button">计算预算</el-button>
          </div>
        </el-form>
      </div>

      <div v-if="budgetResult" class="budget-result animated fadeIn">
        <h3><i class="el-icon-wallet"></i> 预算估算结果</h3>
        
        <el-row :gutter="20">
          <el-col :md="6" :sm="12">
            <div class="budget-card hourly">
              <div class="budget-icon">⏱️</div>
              <div class="budget-title">每小时价格</div>
              <div class="budget-amount">${{ budgetResult.hourly_price.toFixed(4) }}</div>
            </div>
          </el-col>
          <el-col :md="6" :sm="12">
            <div class="budget-card monthly">
              <div class="budget-icon">📅</div>
              <div class="budget-title">每月价格</div>
              <div class="budget-amount">${{ budgetResult.monthly_price.toFixed(2) }}</div>
            </div>
          </el-col>
          <el-col :md="6" :sm="12">
            <div class="budget-card yearly">
              <div class="budget-icon">🗓️</div>
              <div class="budget-title">年度价格</div>
              <div class="budget-amount">${{ (budgetResult.monthly_price * 12).toFixed(2) }}</div>
            </div>
          </el-col>
          <el-col :md="6" :sm="12">
            <div class="budget-card total">
              <div class="budget-icon">💰</div>
              <div class="budget-title">总价格</div>
              <div class="budget-amount">${{ budgetResult.total_price.toFixed(2) }}</div>
              <div class="budget-period">{{ getDurationText() }}</div>
            </div>
          </el-col>
        </el-row>

        <div class="chart-container">
          <div ref="budgetChart" style="height: 400px;"></div>
        </div>
        
        <div class="budget-tips">
          <h4><i class="el-icon-warning-outline"></i> 预算提示</h4>
          <ul>
            <li>以上价格仅包含EC2实例费用，不包含存储、数据传输等额外费用</li>
            <li>实际账单可能因使用情况和AWS价格变动而有所不同</li>
            <li v-if="form.purchase_option === 'Reserved'">预留实例需要预付费用，但总体可节省高达72%的成本</li>
            <li v-if="form.purchase_option === 'Spot'">Spot实例价格可能随市场波动，但可节省高达90%的成本</li>
          </ul>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import apiService from '../api'
import * as echarts from 'echarts'

export default {
  name: 'BudgetEstimator',
  data() {
    return {
      form: {
        instance_type: '',
        region: '',
        operating_system: 'Linux',
        purchase_option: 'OnDemand',
        duration_type: 'preset',
        duration: 1,
        preset_duration: 1
      },
      instanceTypes: [],
      regions: [],
      budgetResult: null
    }
  },
  async created() {
    try {
      // 使用API服务获取实例类型和区域列表
      const [instanceTypes, regions] = await Promise.all([
        apiService.getInstanceTypes(),
        apiService.getRegions()
      ])
      
      this.instanceTypes = instanceTypes
      this.regions = regions
      
      // 如果数据加载成功，默认选择第一个实例类型和区域
      if (this.instanceTypes && this.instanceTypes.length > 0) {
        this.form.instance_type = this.instanceTypes[0]
      }
      
      if (this.regions && this.regions.length > 0) {
        this.form.region = this.regions[0].code
      }
    } catch (error) {
      console.error('Error fetching data:', error)
      this.$message.error('获取数据失败')
    }
  },
  methods: {
    async calculateBudget() {
      try {
        const duration = this.form.duration_type === 'custom' ? this.form.duration : this.form.preset_duration
        // 使用API服务计算预算
        this.budgetResult = await apiService.calculatePrice({
          ...this.form,
          duration
        })
        
        this.$nextTick(() => {
          this.updateChart()
        })
      } catch (error) {
        console.error('Error calculating budget:', error)
        this.$message.error('计算预算失败')
      }
    },
    updateChart() {
      const chartDom = this.$refs.budgetChart
      const myChart = echarts.init(chartDom)
      
      const duration = this.form.duration_type === 'custom' ? this.form.duration : this.form.preset_duration
      const monthlyData = Array.from({ length: duration }, (_, i) => ({
        month: `第${i + 1}个月`,
        cost: this.budgetResult.monthly_price
      }))
      
      const option = {
        title: {
          text: '月度成本趋势',
          left: 'center',
          textStyle: {
            color: '#2c3e50'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: ${c}'
        },
        xAxis: {
          type: 'category',
          data: monthlyData.map(item => item.month),
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '成本 ($)',
          nameTextStyle: {
            color: '#7f8c8d'
          },
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [
          {
            name: '月度成本',
            type: 'bar',
            data: monthlyData.map(item => item.cost),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#f39c12' },
                { offset: 1, color: '#e67e22' }
              ])
            },
            markLine: {
              data: [
                {
                  type: 'average',
                  name: '平均值',
                  lineStyle: {
                    color: '#e74c3c'
                  },
                  label: {
                    formatter: '平均月度成本: ${avg}',
                    color: '#e74c3c'
                  }
                }
              ]
            }
          },
          {
            name: '累计成本',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            data: monthlyData.map((_, index) => 
              this.budgetResult.monthly_price * (index + 1)
            ),
            itemStyle: {
              color: '#3498db'
            },
            lineStyle: {
              width: 3,
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#3498db' },
                { offset: 1, color: '#2980b9' }
              ])
            }
          }
        ]
      }
      
      myChart.setOption(option)
      
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    },
    formatDuration(val) {
      if (val === 1) return '1个月'
      if (val === 12) return '1年'
      if (val === 36) return '3年'
      return `${val}个月`
    },
    getDurationText() {
      const duration = this.form.duration_type === 'custom' ? this.form.duration : this.form.preset_duration
      if (duration === 1) return '1个月'
      if (duration === 12) return '1年'
      if (duration === 36) return '3年'
      return `${duration}个月`
    },
    // 获取区域的中文名称
    getRegionName(regionCode) {
      const region = this.regions.find(r => r.code === regionCode)
      return region ? region.name : regionCode
    }
  }
}
</script>

<style scoped>
.budget-estimator {
  max-width: 1000px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.estimator-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.estimator-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.card-header span {
  font-size: 20px;
  font-weight: 600;
}

.card-header i {
  margin-right: 8px;
}

.card-subtitle {
  margin-top: 5px;
  font-size: 14px;
  opacity: 0.8;
}

.form-container {
  padding: 20px 10px;
}

.full-width {
  width: 100%;
}

.option-with-icon {
  display: flex;
  align-items: center;
}

.option-icon {
  margin-right: 8px;
  font-size: 16px;
}

.duration-radio-group {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.radio-content {
  display: flex;
  align-items: center;
  padding: 0 8px;
}

.radio-content i {
  margin-right: 5px;
}

.preset-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.duration-option {
  display: flex;
  align-items: center;
}

.duration-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 28px;
  height: 28px;
  background-color: #f39c12;
  color: white;
  border-radius: 50%;
  margin-right: 8px;
  font-weight: bold;
}

.el-divider {
  margin: 30px 0;
}

.el-divider__text {
  background-color: #f8f9fa;
  color: #7f8c8d;
}

.duration-slider {
  margin: 15px 0;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.calculate-button {
  min-width: 160px;
  height: 44px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.calculate-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.budget-result {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px dashed #e0e0e0;
}

.budget-result h3 {
  margin-bottom: 20px;
  color: #2c3e50;
  font-size: 18px;
  text-align: center;
}

.budget-result h3 i {
  margin-right: 8px;
  color: var(--secondary-color);
}

.budget-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  text-align: center;
  transition: all 0.3s ease;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.05);
  height: 100%;
  min-height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.budget-card:hover {
  transform: translateY(-5px);
}

.budget-card.hourly {
  border-top: 5px solid #3498db;
}

.budget-card.monthly {
  border-top: 5px solid #f39c12;
}

.budget-card.yearly {
  border-top: 5px solid #9b59b6;
}

.budget-card.total {
  border-top: 5px solid #2ecc71;
}

.budget-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.budget-title {
  color: #7f8c8d;
  font-size: 16px;
  margin-bottom: 10px;
}

.budget-amount {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.budget-period {
  font-size: 14px;
  color: #95a5a6;
}

.chart-container {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.05);
  margin: 30px 0;
}

.budget-tips {
  background-color: #fef9e6;
  border-radius: 8px;
  padding: 15px 20px;
  margin-top: 20px;
}

.budget-tips h4 {
  color: #f39c12;
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.budget-tips h4 i {
  margin-right: 8px;
}

.budget-tips ul {
  margin: 0;
  padding-left: 20px;
}

.budget-tips li {
  margin-bottom: 8px;
  color: #7f8c8d;
}

.animated {
  animation-duration: 0.5s;
  animation-fill-mode: both;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fadeIn {
  animation-name: fadeIn;
}

@media (max-width: 768px) {
  .preset-radio-group {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 