<template>
  <div class="dashboard-editor-container">
    <!-- 轮播图区域（保持不变） -->
    <el-row class="banner-section">
      <el-col :span="24">
        <div class="carousel-container">
          <div class="carousel-wrapper">
            <div
                class="carousel-slide"
                :style="{ transform: `translateX(-${currentIndex * 100}%)` }"
            >
              <div
                  v-for="(item, index) in bannerList"
                  :key="index"
                  class="carousel-item"
                  @click="handleBannerClick(item)"
              >
                <img
                    :src="item.imageUrl"
                    :alt="item.bannerName"
                    class="carousel-bg-img"
                />
                <div class="carousel-overlay"></div>
              </div>
            </div>

            <div class="carousel-nav">
              <el-button circle class="nav-btn prev-btn" @click="prevSlide">
                <el-icon><ArrowLeft /></el-icon>
              </el-button>
              <el-button circle class="nav-btn next-btn" @click="nextSlide">
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>

            <div class="carousel-indicators">
              <div
                  v-for="(item, index) in bannerList"
                  :key="index"
                  class="indicator-item"
                  :class="{ active: currentIndex === index }"
                  @click="goToSlide(index)"
              >
                <div class="indicator-dot"></div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 顶部卡片区域，传入真实统计数据 -->
    <panel-group
        :total-order="totalOrderStat.totalOrderCount"
        :jd-order="totalOrderStat.jdOrderCount"
        :sf-order="totalOrderStat.sfOrderCount"
        :total-amount="totalOrderStat.totalAmount"
        @handle-set-line-chart-data="handleSetLineChartData"
    />

    <el-row :gutter="32" class="chart-continer">
      <el-col :xs="24" :sm="24" :lg="8" class="chart-section">
        <div class="chart-wrapper">
          <div class="chart-title">订单渠道占比</div>
          <pie-chart-one :chart-data="pieChartData" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8" class="chart-section">
        <div class="chart-wrapper">
          <div class="chart-title">近7天订单趋势</div>
          <!-- 传入三个系列数据、X轴标签和当前可见系列 -->
          <line-chart
              :jd-data="jdCounts"
              :sf-data="sfCounts"
              :total-data="totalCounts"
              :x-axis-data="xAxisLabels"
              :visible-series="visibleSeries"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import PanelGroup from './dashboard/PanelGroup.vue'
import LineChart from './dashboard/LineChart.vue'
import PieChartOne from './dashboard/PieChart-one.vue'
import { getTotalOrderStatist, getLast7DaysOrderStatistics } from '@/api/logistics/index.js'
import { listIndexBanner } from '@/api/logistics/banner.js'

// 轮播图数据
const bannerList = ref([])
const currentIndex = ref(0)
let autoPlayTimer = null
const interval = 5000

// 统计数据
const totalOrderStat = ref({
  totalOrderCount: 0,
  jdOrderCount: 0,
  sfOrderCount: 0,
  totalAmount: 0
})
const last7DaysOrders = ref([])

// 计算属性：X轴标签（MM-DD）
const xAxisLabels = computed(() => {
  return last7DaysOrders.value.map(item => {
    const date = new Date(item.statisticsDate)
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${month}-${day}`
  })
})

// 各系列数据
const jdCounts = computed(() => last7DaysOrders.value.map(item => item.jdOrderCount))
const sfCounts = computed(() => last7DaysOrders.value.map(item => item.sfOrderCount))
const totalCounts = computed(() => last7DaysOrders.value.map(item => item.totalOrderCount))

// 饼图数据
const pieChartData = computed(() => [
  { value: totalOrderStat.value.jdOrderCount, name: '京东订单' },
  { value: totalOrderStat.value.sfOrderCount, name: '顺丰订单' }
])

// 控制折线图显示哪些系列（默认全部显示）
const visibleSeries = ref(['jd', 'sf', 'total'])

// 卡片点击切换系列显示
const handleSetLineChartData = (type) => {
  switch (type) {
    case 'newVisitis': // 总订单数卡片 -> 只显示总订单
      visibleSeries.value = ['total']
      break
    case 'messages': // 京东订单卡片 -> 只显示京东
      visibleSeries.value = ['jd']
      break
    case 'purchases': // 顺丰订单卡片 -> 只显示顺丰
      visibleSeries.value = ['sf']
      break
    case 'shoppings': // 总费用卡片（暂无每日费用，显示总订单趋势）
      visibleSeries.value = ['total']
      break
    default:
      visibleSeries.value = ['jd', 'sf', 'total']
  }
}

// 轮播图方法
const nextSlide = () => {
  currentIndex.value = (currentIndex.value + 1) % bannerList.value.length
  resetAutoPlay()
}
const prevSlide = () => {
  currentIndex.value = (currentIndex.value - 1 + bannerList.value.length) % bannerList.value.length
  resetAutoPlay()
}
const goToSlide = (index) => {
  currentIndex.value = index
  resetAutoPlay()
}
const startAutoPlay = () => {
  stopAutoPlay()
  autoPlayTimer = setInterval(nextSlide, interval)
}
const stopAutoPlay = () => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer)
    autoPlayTimer = null
  }
}
const resetAutoPlay = () => {
  stopAutoPlay()
  startAutoPlay()
}

const handleBannerClick = (item) => {
  if (item.linkUrl && item.linkUrl.startsWith('http')) {
    window.open(item.linkUrl, '_blank')
  }
}

// API 调用
const getBannerList = () => {
  listIndexBanner().then(response => {
    bannerList.value = response.data
    startAutoPlay()
  })
}

const queryStatist = () => {
  getTotalOrderStatist().then(response => {
    totalOrderStat.value = response
  })
}

const queryLast7DayStatist = () => {
  getLast7DaysOrderStatistics().then(response => {
    last7DaysOrders.value = response
  })
}

onMounted(() => {
  getBannerList()
  queryStatist()
  queryLast7DayStatist()
})

onUnmounted(() => {
  stopAutoPlay()
})
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 16px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .banner-section {
    .carousel-container {
      position: relative;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);

      .carousel-wrapper {
        position: relative;
        overflow: hidden;
        min-height: 230px;

        .carousel-slide {
          display: flex;
          transition: transform 0.5s ease-in-out;
          height: 100%;

          .carousel-item {
            flex: 0 0 100%;
            position: relative;
            cursor: pointer;
            min-height: 230px;

            .carousel-bg-img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              position: absolute;
              top: 0;
              left: 0;
            }

            .carousel-overlay {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              background: linear-gradient(
                      135deg,
                      rgba(0, 0, 0, 0.7) 0%,
                      rgba(0, 0, 0, 0.4) 50%,
                      rgba(0, 0, 0, 0.2) 100%
              );
            }

            .carousel-content {
              position: relative;
              z-index: 2;
              padding: 20px;
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: center;
              color: white;

              .carousel-title {
                font-size: 42px;
                font-weight: 700;
                margin-bottom: 20px;
                line-height: 1.2;
                text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
                background: linear-gradient(135deg, #fff 0%, #e6f7ff 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
              }

              .carousel-desc {
                font-size: 20px;
                margin-bottom: 36px;
                line-height: 1.6;
                color: rgba(255, 255, 255, 0.95);
                max-width: 600px;
                text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
              }

              .carousel-button {
                background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
                color: white;
                border: none;
                padding: 16px 42px;
                font-size: 18px;
                transition: all 0.3s ease;
                box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
                border-radius: 10px;
                border: 2px solid rgba(255, 255, 255, 0.3);
                align-self: flex-start;

                &:hover {
                  background: linear-gradient(135deg, #66b1ff 0%, #409EFF 100%);
                  transform: translateY(-3px);
                  box-shadow: 0 10px 25px rgba(64, 158, 255, 0.5);
                }

                &:active {
                  transform: translateY(-1px);
                }
              }
            }

            &:hover {
              .carousel-bg-img {
                transform: scale(1.05);
                transition: transform 0.8s ease;
              }
            }
          }
        }

        .carousel-nav {
          position: absolute;
          top: 50%;
          left: 0;
          right: 0;
          transform: translateY(-50%);
          display: flex;
          justify-content: space-between;
          padding: 0 20px;
          z-index: 3;

          .nav-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover {
              background: rgba(255, 255, 255, 0.3);
              border-color: rgba(255, 255, 255, 0.5);
            }

            .el-icon {
              font-size: 20px;
              font-weight: bold;
            }
          }
        }

        .carousel-indicators {
          position: absolute;
          bottom: 24px;
          left: 0;
          right: 0;
          display: flex;
          justify-content: center;
          gap: 12px;
          z-index: 3;

          .indicator-item {
            cursor: pointer;
            padding: 8px;

            .indicator-dot {
              width: 12px;
              height: 12px;
              border-radius: 50%;
              background: rgba(255, 255, 255, 0.4);
              transition: all 0.3s ease;
            }

            &.active {
              .indicator-dot {
                background: white;
                width: 32px;
                border-radius: 6px;
                box-shadow: 0 0 8px rgba(64, 158, 255, 0.6);
              }
            }

            &:hover:not(.active) {
              .indicator-dot {
                background: rgba(255, 255, 255, 0.7);
                transform: scale(1.2);
              }
            }
          }
        }
      }
    }
  }

  .chart-continer{
    padding: 0px 20px 0px 0px;

    .chart-title{
      height: 26px;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      line-height: 26px;

      &::before{
        content: ''; /* 必须设置content，否则伪元素不会显示 */
        display: inline-block; /* 伪元素默认是行内，设置为块级以控制宽高 */
        width: 4px;
        height: 16px;
        line-height: 26px;
        background: #2D71FF;
        border-radius: 2px 2px 2px 2px;
        margin-right: 6px;
      }
    }

    .chart-section{
      marging:0px !important;
      padding:0px !important;
      padding-left: 20px !important;
    }

  }


  .chart-wrapper {
    background: #fff;
    padding: 16px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }
}

@media (max-width: 1200px) {
  .dashboard-editor-container {
    .banner-section {
      .carousel-container {
        .carousel-wrapper {
          min-height: 190px;

          .carousel-slide {
            .carousel-item {
              min-height: 190px;

              .carousel-content {
                padding: 10px;

                .carousel-title {
                  font-size: 36px;
                }

                .carousel-desc {
                  font-size: 18px;
                }
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 1024px) {
  .dashboard-editor-container {
    padding: 20px;

    .banner-section {
      .carousel-container {
        .carousel-wrapper {
          min-height: 240px;

          .carousel-slide {
            .carousel-item {
              min-height: 240px;

              .carousel-content {
                padding: 32px;

                .carousel-title {
                  font-size: 32px;
                }

                .carousel-desc {
                  font-size: 16px;
                  margin-bottom: 30px;
                }

                .carousel-button {
                  padding: 14px 36px;
                  font-size: 16px;
                }
              }
            }
          }

          .carousel-nav {
            .nav-btn {
              width: 40px;
              height: 40px;
            }
          }
        }
      }
    }

    .chart-wrapper {
      padding: 12px;
    }
  }
}

@media (max-width: 768px) {
  .dashboard-editor-container {
    .banner-section {
      .carousel-container {
        .carousel-wrapper {
          min-height: 200px;

          .carousel-slide {
            .carousel-item {
              min-height: 200px;

              .carousel-content {
                padding: 24px;

                .carousel-title {
                  font-size: 28px;
                  margin-bottom: 16px;
                }

                .carousel-desc {
                  font-size: 15px;
                  margin-bottom: 24px;
                }

                .carousel-button {
                  padding: 12px 32px;
                  font-size: 15px;
                }
              }
            }
          }

          .carousel-nav {
            padding: 0 12px;

            .nav-btn {
              width: 36px;
              height: 36px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .dashboard-editor-container {
    padding: 16px;

    .banner-section {
      .carousel-container {
        .carousel-wrapper {
          min-height: 180px;

          .carousel-slide {
            .carousel-item {
              min-height: 180px;

              .carousel-content {
                padding: 20px;

                .carousel-title {
                  font-size: 24px;
                }

                .carousel-desc {
                  font-size: 14px;
                }

                .carousel-button {
                  padding: 10px 28px;
                  font-size: 14px;
                }
              }
            }
          }

          .carousel-nav {
            display: none; /* 小屏幕隐藏导航箭头 */
          }

          .carousel-indicators {
            bottom: 16px;

            .indicator-item {
              .indicator-dot {
                width: 8px;
                height: 8px;
              }

              &.active {
                .indicator-dot {
                  width: 24px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>