<template>
  <view class="stock-home-container">
    <!-- 顶部用户信息栏 -->
    <view class="user-header">
      <view class="user-info">
        <image class="avatar" src="/static/images/avatar.png" mode="aspectFill"></image>
        <view class="user-details">
          <text class="username">{{$t('home.welcome')}}</text>
          <text class="username">{{userName}}</text>
        </view>
      </view>
      <view class="account-summary">
        <text class="label">{{$t('home.totalAssets')}}</text>
        <text class="total-assets">${{formatNumber(totalAssets)}}</text>
        <text class="asset-change" :class="{'positive': dailyChange >= 0, 'negative': dailyChange < 0}">
          {{dailyChange >= 0 ? '+' : ''}}{{formatNumber(dailyChange)}} ({{dailyChangePercent >= 0 ? '+' : ''}}{{dailyChangePercent}}%)
        </text>
      </view>
    </view>

    <!-- 主要功能入口 -->
    <view class="quick-actions">
      <view class="action-item" @click="navigateTo('trade')">
        <image src="/static/icons/trade.png" mode="widthFix"></image>
        <text>Trade</text>
      </view>
      <view class="action-item" @click="navigateTo('deposit')">
        <image src="/static/icons/deposit.png" mode="widthFix"></image>
        <text>Deposit</text>
      </view>
      <view class="action-item" @click="navigateTo('withdraw')">
        <image src="/static/icons/withdraw.png" mode="widthFix"></image>
        <text>Withdraw</text>
      </view>
      <view class="action-item" @click="navigateTo('transfer')">
        <image src="/static/icons/transfer.png" mode="widthFix"></image>
        <text>Transfer</text>
      </view>
    </view>

    <!-- 自选股票列表 -->
    <view class="watchlist-section">
      <view class="section-header">
        <text class="section-title">Watchlist</text>
        <text class="section-more" @click="navigateTo('watchlist')">More ></text>
      </view>
      <scroll-view scroll-x class="stock-scroll" :scroll-with-animation="true">
        <view class="stock-card" v-for="(stock, index) in watchlist" :key="index" @click="viewStockDetail(stock)">
          <text class="stock-symbol">{{stock.symbol}}</text>
          <text class="stock-name">{{stock.name}}</text>
          <text class="stock-price">${{stock.price}}</text>
          <text class="stock-change" :class="{'positive': stock.change >= 0, 'negative': stock.change < 0}">
            {{stock.change >= 0 ? '+' : ''}}{{stock.change}}%
          </text>
        </view>
      </scroll-view>
    </view>

    <!-- 市场指数 -->
    <view class="market-indices">
      <view class="section-header">
        <text class="section-title">Market Indices</text>
        <text class="section-more" @click="navigateTo('markets')">More ></text>
      </view>
      <swiper class="indices-swiper" 
              :indicator-dots="true" 
              :autoplay="true" 
              :interval="5000" 
              :duration="1000" 
              @change="handleSwiperChange"
              :circular="true">
        <swiper-item v-for="(index, i) in marketIndices" :key="i">
          <view class="index-item">
            <view class="index-data-top">
              <text class="index-name">{{index.name}}</text>
              <text class="index-value">{{index.value}}</text>
              <text class="index-change" :class="{'positive': index.change >= 0, 'negative': index.change < 0}">
                {{index.change >= 0 ? '+' : ''}}{{index.change}}%
              </text>
            </view>
            
            <view class="chart-container">
              <qiun-data-charts 
                v-if="chartReady && list[i] && list[i].newKline"
                type="line" 
                :opts="opts" 
                :chartData="list[i].newKline" 
                :tooltipFormat="tooltipDemo1" 
                canvas2d
                width="100%"
                height="100%"
              />
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 新闻资讯 -->
    <view class="news-section">
      <view class="section-header">
        <text class="section-title">Market News</text>
        <text class="section-more" @click="navigateTo('news')">More ></text>
      </view>
      <view class="news-list">
        <view class="news-item" v-for="(news, idx) in marketNews" :key="idx" @click="viewNewsDetail(news)">
          <image class="news-image" :src="news.imageUrl" mode="aspectFill"></image>
          <view class="news-content">
            <text class="news-title">{{news.title}}</text>
            <text class="news-time">{{formatTime(news.time)}}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import NoContent from '../components/no-content.vue'

export default {
  components: {
    NoContent
  },
  data() {
    return {
      userName: "John Doe",
      accountId: "EU20230001",
      totalAssets: 125430.56,
      dailyChange: 1254.32,
      dailyChangePercent: 1.01,
      titleIndex: 0,
      chartReady: false,
      watchlist: [
        { symbol: "AAPL", name: "Apple Inc.", price: 175.34, change: 1.23 },
        { symbol: "MSFT", name: "Microsoft", price: 328.39, change: 0.56 },
        { symbol: "TSLA", name: "Tesla", price: 260.54, change: -2.34 },
        { symbol: "AMZN", name: "Amazon", price: 134.56, change: 0.89 },
        { symbol: "GOOGL", name: "Alphabet", price: 125.67, change: -0.45 }
      ],
      marketIndices: [
        { name: "S&P 500", value: 4524.09, change: 0.42 },
        { name: "NASDAQ", value: 14019.31, change: 0.85 },
        { name: "Dow 30", value: 34721.12, change: -0.12 },
        { name: "FTSE 100", value: 7527.53, change: 0.23 }
      ],
        opts: {
        dataPointShape: false,
        title: {
          color: '#fff'
        },
        dataLabel: false,
        color: ['#4CAF50'],
        padding: [0, 0, 0, 0],
        enableScroll: false,
        legend: {},
        xAxis: {
          itemCount: 4,
          disableGrid: true,
          disabled: true,
          axisLine: false
        },
        yAxis: {
          gridType: 'dash',
          disableGrid: true,
          dashLength: 1,
          disabled: true
        },
        extra: {
          line: {
            type: 'straight',
            width: 1,
            activeType: 'hollow'
          },
          tooltip: {
            legendShow: true
          }
        }
      },
      list: [
        {
          newKline: {
            categories: ['09:30', '10:00', '10:30', '11:00', '11:30', '13:30', '14:00', '14:30', '15:00'],
            series: [{ name: 'S&P 500', data: [4480, 4495, 4510, 4490, 4505, 4520, 4518, 4522, 4524.09] }]
          }
        },
        {
          newKline: {
            categories: ['09:30', '10:00', '10:30', '11:00', '11:30', '13:30', '14:00', '14:30', '15:00'],
            series: [{ name: 'NASDAQ', data: [13850, 13890, 13920, 13970, 13990, 14005, 14010, 14015, 14019.31] }]
          }
        },
        {
          newKline: {
            categories: ['09:30', '10:00', '10:30', '11:00', '11:30', '13:30', '14:00', '14:30', '15:00'],
            series: [{ name: 'Dow 30', data: [34750, 34780, 34800, 34760, 34740, 34730, 34725, 34723, 34721.12] }]
          }
        },
        {
          newKline: {
            categories: ['09:30', '10:00', '10:30', '11:00', '11:30', '13:30', '14:00', '14:30', '15:00'],
            series: [{ name: 'FTSE 100', data: [7490, 7505, 7510, 7500, 7515, 7520, 7523, 7525, 7527.53] }]
          }
        }
      ],
      marketNews: [
        {
          title: "Fed signals more rate hikes to combat inflation",
          imageUrl: "/static/images/news1.jpg",
          time: "2023-06-15T09:30:00Z"
        },
        {
          title: "Tech stocks rally as AI boom continues",
          imageUrl: "/static/images/news2.jpg",
          time: "2023-06-15T08:45:00Z"
        },
        {
          title: "European markets open higher amid positive earnings",
          imageUrl: "/static/images/news3.jpg",
          time: "2023-06-15T07:15:00Z"
        }
      ]
    }
  },
  mounted() {
    this.deviceInfo = uni.getSystemInfoSync();
    // 设置延迟确保DOM渲染完成
    setTimeout(() => {
      this.chartReady = true;
    }, 100);
  },
  methods: {
    formatNumber(num) {
      return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    },
    formatTime(timeString) {
      const date = new Date(timeString);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    navigateTo(page) {
      const animationType = this.deviceInfo.platform === 'android' ? 'slide-in-right' : 'pop-in';
      const isTabBarPage = ['trade', 'deposit', 'withdraw', 'transfer', 'watchlist', 'markets', 'news'].includes(page);
      
      if (isTabBarPage) {
        uni.switchTab({ 
          url: `/pages/${page}/${page}`,
          animationType
        });
      } else {
        uni.navigateTo({ 
          url: `/pages/${page}/${page}`,
          animationType
        });
      }
    },
    viewStockDetail(stock) {
      uni.navigateTo({ 
        url: `/pages/stock/detail?symbol=${stock.symbol}`,
        animationType: 'slide-in-right'
      });
    },
    viewNewsDetail(news) {
      uni.navigateTo({ 
        url: `/pages/news/detail?title=${encodeURIComponent(news.title)}`,
        animationType: 'slide-in-right'
      });
    },
    handleSwiperChange(e) {
      this.titleIndex = e.detail.current;
    },
    tooltipDemo1(params) {
      const { name, value, index } = params;
      const category = this.list[this.titleIndex].newKline.categories[index];
      const change = this.calculateChange(index);
      
      return `
        <div style="text-align: center; font-weight: bold; font-size: 12px;">${category}</div>
        <div style="font-size: 12px;">${name}: $${parseFloat(value).toFixed(2)}</div>
        <div style="color: ${change >= 0 ? '#4CAF50' : '#F44336'}; font-size: 12px;">
          ${change >= 0 ? '+' : ''}${change.toFixed(2)}%
        </div>
      `;
    },
    calculateChange(index) {
      const data = this.list[this.titleIndex].newKline.series[0].data;
      const firstValue = data[0];
      const currentValue = data[index];
      return ((currentValue - firstValue) / firstValue) * 100;
    },
  }
}
</script>

<style lang="scss">
$base-padding: 20rpx;
$card-radius: 16rpx;
$small-radius: 12rpx;
$border-width: 1rpx;

.stock-home-container {
  padding: $base-padding;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.user-header {
  background: linear-gradient(135deg, #1976D2, #2196F3);
  border-radius: $card-radius;
  padding: $base-padding;
  color: white;
  margin-bottom: $base-padding;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: $base-padding;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: $base-padding;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
}

.account-summary {
  display: flex;
  flex-direction: column;
}

.label {
  margin-top: 20rpx;
  font-size: 26rpx;
  opacity: 0.9;
}

.total-assets {
  font-size: 48rpx;
  font-weight: bold;
}

.asset-change {
  font-size: 28rpx;
  margin-top: 8rpx;
}

.positive {
  color: #4CAF50;
}

.negative {
  color: #F44336;
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  background-color: white;
  border-radius: $card-radius;
  padding: $base-padding;
  margin-bottom: $base-padding;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  padding: 10rpx 0;
  text-align: center;
}

.action-item image {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.action-item text {
  font-size: 24rpx;
  color: #333;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 30rpx 0 20rpx;
  padding: 0 5rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-more {
  font-size: 26rpx;
  color: #1976D2;
}

.watchlist-section {
  margin-bottom: $base-padding;
}

.stock-scroll {
  white-space: nowrap;
  width: 100%;
  padding-bottom: 10rpx;
}

.stock-card {
  display: inline-block;
  background-color: white;
  border-radius: $small-radius;
  padding: 20rpx;
  margin-right: 15rpx;
  width: 200rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  vertical-align: top;
  transition: transform 0.2s ease;
  
  &:last-child {
    margin-right: 0;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.stock-symbol {
  font-size: 28rpx;
  font-weight: bold;
  display: block;
  color: #333;
}

.stock-name {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin: 10rpx 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stock-price {
  font-size: 28rpx;
  font-weight: bold;
  display: block;
  color: #333;
}

.stock-change {
  font-size: 24rpx;
  display: block;
  margin-top: 8rpx;
}

.market-indices {
  margin-bottom: $base-padding;
}

.indices-swiper {
  width: 100%;
  height: 350rpx;
  margin-bottom: $base-padding;
}

.index-item {
  background-color: white;
  border-radius: $small-radius;
  padding: 20rpx;
  box-sizing: border-box;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.index-data-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10rpx 15rpx;
  border-bottom: $border-width solid #f0f0f0;
  margin-bottom: 15rpx;
}

.index-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.index-value {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.index-change {
  font-size: 28rpx;
  padding: 5rpx 10rpx;
  border-radius: 4rpx;
  background-color: rgba(76, 175, 80, 0.1);
  
  &.negative {
    background-color: rgba(244, 67, 54, 0.1);
  }
}

.chart-container {
  flex: 1;
  position: relative;
  width: 100%;
  height: 200rpx;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.news-section {
  margin-bottom: $base-padding;
}

.news-list {
  background-color: white;
  border-radius: $card-radius;
  overflow: hidden;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.news-item {
  display: flex;
  padding: 20rpx;
  border-bottom: $border-width solid #eee;
  align-items: center;
  transition: background-color 0.2s ease;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: #f9f9f9;
  }
}

.news-image {
  width: 140rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.news-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 100rpx;
}

.news-title {
  font-size: 28rpx;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.news-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

@media screen and (max-width: 320px) {
  .indices-swiper {
    height: 320rpx;
  }
  
  .index-name {
    font-size: 26rpx;
  }
  
  .index-value {
    font-size: 30rpx;
  }
  
  .index-change {
    font-size: 26rpx;
  }
  
  .stock-card {
    width: 170rpx;
    padding: 15rpx;
  }
  
  .action-item image {
    width: 50rpx;
    height: 50rpx;
  }
  
  .news-image {
    width: 120rpx;
    height: 90rpx;
  }
  
  .news-title {
    font-size: 26rpx;
  }
}

@media screen and (min-width: 414px) {
  .indices-swiper {
    height: 400rpx;
  }
  
  .stock-card {
    width: 220rpx;
  }
}
</style>