<template>
  <div class="page-container order-dashboard-page">
    <header class="page-header">
      <h1 class="main-title">商品渠道透视</h1>
      <p class="subtitle">分析商品在不同销售渠道的覆盖广度</p>
    </header>

    <OrderDateRangeFilter
      :max-date="maxDate"
      default-period="day"
      storage-key="dtm-shop-date-filter"
      @change="handleFilterChange"
    />

    <div class="chart-card">
      <h3 class="chart-title">商品渠道覆盖 Top 20 趋势</h3>
      <OrderLoadingPanel
        v-if="loading"
        title="正在加载商品渠道数据"
        detail="正在读取商品在各销售渠道的覆盖情况"
      />
      <div ref="channelChartRef" style="width: 100%; height: 500px;"></div>
    </div>

    <div class="table-card">
      <OrderLoadingPanel
        v-if="loading"
        title="正在加载渠道明细"
        detail="正在生成商品覆盖平台排名"
      />
      <div class="table-header">
        <h3 class="chart-title">商品渠道覆盖明细</h3>
        <div class="search-box">
          <el-input
            v-model.trim="skuKeyword"
            clearable
            placeholder="输入 SKU 搜索"
            @keyup.enter.native="applySkuSearch"
            @clear="applySkuSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="applySkuSearch" />
          </el-input>
        </div>
      </div>
      <table class="data-table">
        <thead>
          <tr>
            <th>排名</th>
            <th>商品编码</th>
            <th>覆盖平台数</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in paginatedData" :key="item.productCode">
            <td>{{ (currentPage - 1) * itemsPerPage + index + 1 }}</td>
            <td>{{ item.productCode }}</td>
            <td>{{ item.platformCount }}</td>
          </tr>
          <tr v-if="loading">
            <td colspan="3">正在加载数据...</td>
          </tr>
          <tr v-else-if="!paginatedData.length">
            <td colspan="3">没有找到符合条件的数据</td>
          </tr>
        </tbody>
      </table>
      <div class="pagination-controls">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import OrderLoadingPanel from '../components/OrderLoadingPanel.vue'
import OrderDateRangeFilter from '../components/OrderDateRangeFilter.vue'
import { getShopCrossSellingProducts, getShopMaxDate } from '@/api/order'

export default {
  name: 'OrderChannel',
  components: {
    OrderLoadingPanel,
    OrderDateRangeFilter
  },
  data() {
    return {
      allProducts: [],
      currentPage: 1,
      itemsPerPage: 10,
      skuKeyword: '',
      maxDate: '',
      currentQuery: {},
      loading: true,
      chartInstance: null
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.itemsPerPage
      return this.allProducts.slice(start, start + this.itemsPerPage)
    },
    totalPages() {
      return Math.max(1, Math.ceil(this.allProducts.length / this.itemsPerPage))
    }
  },
  mounted() {
    this.initFilter()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.chartInstance?.dispose()
  },
  methods: {
    handleResize() {
      this.chartInstance?.resize()
    },
    applySkuSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    async initFilter() {
      try {
        this.maxDate = await getShopMaxDate()
      } catch (error) {
        const today = new Date()
        this.maxDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
      }
    },
    handleFilterChange(params) {
      this.currentQuery = params || {}
      this.currentPage = 1
      this.fetchData()
    },
    initLineChart() {
      const chartEl = this.$refs.channelChartRef
      if (!chartEl) return
      if (this.chartInstance) {
        this.chartInstance.dispose()
      }
      this.chartInstance = echarts.init(chartEl)
      const top20Data = this.allProducts.slice(0, 20)
      this.chartInstance.setOption({
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: top20Data.map(item => item.productCode),
          axisLabel: { interval: 0, rotate: 30 }
        },
        yAxis: {
          type: 'value',
          name: '覆盖平台数'
        },
        series: [{
          name: '覆盖平台数',
          type: 'line',
          smooth: true,
          data: top20Data.map(item => item.platformCount),
          itemStyle: { color: '#5470C6' },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
              { offset: 1, color: 'rgba(84, 112, 198, 0)' }
            ])
          }
        }]
      }, true)
    },
    async fetchData() {
      this.loading = true
      try {
        const response = await getShopCrossSellingProducts({
          startDate: this.currentQuery.startDate,
          endDate: this.currentQuery.endDate,
          skuKeyword: this.skuKeyword || undefined
        })
        if (response?.success) {
          this.allProducts = response.data || []
          this.initLineChart()
          return
        }
        this.allProducts = []
        this.initLineChart()
      } catch (error) {
        console.error('获取商品渠道数据失败:', error)
        this.allProducts = []
        this.initLineChart()
      } finally {
        this.loading = false
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage += 1
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage -= 1
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f0f2f5;
}

.page-header {
  margin-bottom: 10px;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.subtitle {
  font-size: 14px;
  color: #999;
}

.chart-card,
.table-card {
  position: relative;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.search-box {
  width: 280px;
}

.chart-title {
  font-size: 18px;
  color: #333;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  text-align: left;
}

.data-table th {
  background-color: #f7f7f7;
  font-weight: 600;
}

.pagination-controls {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 15px;
}

.pagination-controls button {
  padding: 8px 12px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.pagination-controls button:hover:not(:disabled) {
  border-color: #5470C6;
  color: #5470C6;
}

.pagination-controls button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
