<template>
  <div class="price-comparison">
    <el-card class="comparison-card">
      <template #header>
        <div class="card-header">
          <span><i class="el-icon-data-analysis"></i> EC2 价格对比</span>
          <div class="card-subtitle">比较不同配置的价格，做出最佳选择</div>
        </div>
      </template>

      <div class="form-container">
        <div class="configurations-container">
          <div v-for="(config, index) in configurations" :key="index" class="configuration-item animated fadeIn">
            <el-card class="config-card">
              <template #header>
                <div class="config-header">
                  <span><i class="el-icon-s-platform"></i> 配置 #{{ index + 1 }}</span>
                  <el-button type="danger" size="small" icon="el-icon-delete" circle @click="removeConfiguration(index)"></el-button>
                </div>
              </template>

              <el-form :model="config" label-width="120px">
                <el-row :gutter="20">
                  <el-col :md="12" :sm="24">
                    <el-form-item label="实例类型">
                      <el-select v-model="config.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="config.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="config.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="config.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-form-item label="使用时长(月)">
                  <el-slider 
                    v-model="config.duration" 
                    :min="1" 
                    :max="36" 
                    :format-tooltip="formatDuration"
                    :marks="{1: '1个月', 12: '1年', 36: '3年'}"
                    class="duration-slider">
                  </el-slider>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </div>

        <div class="comparison-actions">
          <el-button type="primary" icon="el-icon-plus" @click="addConfiguration" class="action-button">添加配置</el-button>
          <el-button type="success" icon="el-icon-refresh" @click="comparePrices" class="action-button">比较价格</el-button>
          <el-button icon="el-icon-download" @click="exportResults" class="action-button" :disabled="!comparisonResults.length">导出结果</el-button>
        </div>

        <div v-if="comparisonResults.length" class="comparison-results animated fadeIn">
          <h3><i class="el-icon-s-data"></i> 对比结果</h3>
          
          <div class="chart-container">
            <div ref="priceChart" style="height: 400px;"></div>
          </div>
          
          <el-table :data="comparisonResults" border style="width: 100%; margin-top: 20px;" :stripe="true" class="result-table">
            <el-table-column label="配置" width="50">
              <template #default="scope">
                <div class="config-number">{{ scope.$index + 1 }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="configuration.instance_type" label="实例类型"></el-table-column>
            <el-table-column prop="configuration.region" label="区域">
              <template #default="scope">
                {{ getRegionName(scope.row.configuration.region) }}
              </template>
            </el-table-column>
            <el-table-column prop="configuration.operating_system" label="操作系统">
              <template #default="scope">
                <div class="option-with-icon">
                  <span class="option-icon">{{ scope.row.configuration.operating_system === 'Linux' ? '🐧' : '🪟' }}</span>
                  <span>{{ scope.row.configuration.operating_system }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="configuration.purchase_option" label="购买选项">
              <template #default="scope">
                <div class="option-with-icon">
                  <span class="option-icon">
                    {{ scope.row.configuration.purchase_option === 'OnDemand' ? '⏱️' : 
                       scope.row.configuration.purchase_option === 'Reserved' ? '📅' : '💸' }}
                  </span>
                  <span>{{ getPurchaseOptionLabel(scope.row.configuration.purchase_option) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price.hourly_price" label="每小时价格">
              <template #default="scope">
                <div class="price-value">
                  ${{ scope.row.price.hourly_price.toFixed(4) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price.monthly_price" label="每月价格">
              <template #default="scope">
                <div class="price-value">
                  ${{ scope.row.price.monthly_price.toFixed(2) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price.total_price" label="总价格">
              <template #default="scope">
                <div class="price-value highlight">
                  ${{ scope.row.price.total_price.toFixed(2) }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

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

export default {
  name: 'PriceComparison',
  data() {
    return {
      configurations: [],
      instanceTypes: [],
      regions: [],
      comparisonResults: []
    }
  },
  async created() {
    try {
      const [instanceTypes, regions] = await Promise.all([
        apiService.getInstanceTypes(),
        apiService.getRegions()
      ])
      
      this.instanceTypes = instanceTypes
      this.regions = regions
      this.addConfiguration()
    } catch (error) {
      console.error('Error fetching data:', error)
      this.$message.error('获取数据失败')
    }
  },
  methods: {
    addConfiguration() {
      this.configurations.push({
        instance_type: '',
        region: '',
        operating_system: 'Linux',
        purchase_option: 'OnDemand',
        duration: 1
      })
    },
    removeConfiguration(index) {
      this.configurations.splice(index, 1)
      if (this.configurations.length === 0) {
        this.addConfiguration()
      }
    },
    async comparePrices() {
      try {
        this.comparisonResults = await apiService.comparePrices({
          configurations: this.configurations
        })
        
        this.$nextTick(() => {
          this.updateChart()
        })
      } catch (error) {
        console.error('Error comparing prices:', error)
        this.$message.error('比较价格失败')
      }
    },
    updateChart() {
      const chartDom = this.$refs.priceChart
      const myChart = echarts.init(chartDom)
      
      const option = {
        title: {
          text: '价格对比图表',
          left: 'center',
          textStyle: {
            color: '#2c3e50'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['每小时价格', '每月价格', '总价格'],
          bottom: 10
        },
        xAxis: {
          type: 'category',
          data: this.comparisonResults.map((_, index) => `配置 ${index + 1}`),
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '价格 ($)',
          nameTextStyle: {
            color: '#7f8c8d'
          },
          axisLine: {
            lineStyle: {
              color: '#7f8c8d'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [
          {
            name: '每小时价格',
            type: 'bar',
            data: this.comparisonResults.map(result => result.price.hourly_price),
            itemStyle: {
              color: '#3498db'
            }
          },
          {
            name: '每月价格',
            type: 'bar',
            data: this.comparisonResults.map(result => result.price.monthly_price),
            itemStyle: {
              color: '#f39c12'
            }
          },
          {
            name: '总价格',
            type: 'bar',
            data: this.comparisonResults.map(result => result.price.total_price),
            itemStyle: {
              color: '#2ecc71'
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}$',
              fontSize: 12
            }
          }
        ]
      }
      
      myChart.setOption(option)
      
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    },
    exportResults() {
      if (!this.comparisonResults.length) {
        this.$message.warning('没有可导出的结果')
        return
      }
      
      const csv = this.generateCSV()
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = 'price-comparison.csv'
      link.click()
      
      this.$message.success('导出成功')
    },
    generateCSV() {
      const headers = ['实例类型', '区域', '操作系统', '购买选项', '每小时价格', '每月价格', '总价格']
      const rows = this.comparisonResults.map(result => [
        result.configuration.instance_type,
        result.configuration.region,
        result.configuration.operating_system,
        this.getPurchaseOptionLabel(result.configuration.purchase_option),
        result.price.hourly_price.toFixed(4),
        result.price.monthly_price.toFixed(2),
        result.price.total_price.toFixed(2)
      ])
      
      return [
        headers.join(','),
        ...rows.map(row => row.join(','))
      ].join('\n')
    },
    formatDuration(val) {
      if (val === 1) return '1个月'
      if (val === 12) return '1年'
      if (val === 36) return '3年'
      return `${val}个月`
    },
    getPurchaseOptionLabel(option) {
      switch(option) {
        case 'OnDemand': return '按需实例'
        case 'Reserved': return '预留实例'
        case 'Spot': return 'Spot实例'
        default: return option
      }
    },
    getRegionName(regionCode) {
      const region = this.regions.find(r => r.code === regionCode)
      return region ? region.name : regionCode
    }
  }
}
</script>

<style scoped>
/* Add your styles here */
</style>