<template>
  <div class="app-container shop-report-page order-dashboard-page">
    <div class="report-shell">
      <section class="report-main">
        <div class="hero-panel">
          <div>
            <p class="eyebrow">Order Monitor</p>
            <h2>店铺运营报表</h2>
            <p class="hero-desc">聚合平台、渠道与店铺的销售表现，快速查看订单规模、销量与客单价。</p>
          </div>
          <div class="hero-visual">
            <span class="hero-icon el-icon-s-data" />
            <div class="hero-bars">
              <i />
              <i />
              <i />
              <i />
            </div>
          </div>
        </div>

        <OrderDateRangeFilter
          :max-date="maxDate"
          default-period="day"
          storage-key="dtm-shop-date-filter"
          popper-class="shop-report-date-popper"
          class="report-toolbar"
          @change="handleFilterChange"
        >
          <template slot="actions">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出 Excel</el-button>
          </template>
        </OrderDateRangeFilter>

        <el-alert
          class="report-alert"
          title="当前没有成本/费用数据源，毛利额和毛利率字段已预留，暂不参与计算。"
          type="warning"
          :closable="false"
          show-icon
        />

        <el-row :gutter="18" class="summary-row">
          <el-col v-for="card in summaryCards" :key="card.key" :xs="24" :sm="12" :md="6">
            <div class="summary-item" :class="card.className">
              <span class="summary-icon" :class="card.icon" />
              <span class="summary-label">{{ card.label }}</span>
              <strong>{{ card.value }}</strong>
              <small>{{ card.hint }}</small>
            </div>
          </el-col>
        </el-row>

        <section class="table-card">
          <div class="section-heading">
            <div>
              <h3>渠道明细</h3>
              <p>{{ dateRangeLabel }}</p>
            </div>
            <el-button type="primary" icon="el-icon-refresh" size="mini" plain @click="handleQuery">刷新</el-button>
          </div>

          <el-table v-loading="loading" :data="reportList" class="report-table">
            <el-table-column label="统计周期" prop="period" min-width="110" fixed="left" />
            <el-table-column label="平台" prop="platformName" min-width="140" show-overflow-tooltip />
            <el-table-column label="渠道/店铺" prop="channelName" min-width="160" show-overflow-tooltip />
            <el-table-column label="订单量" prop="orderCount" min-width="100" align="right">
              <template slot-scope="scope">{{ formatNumber(scope.row.orderCount) }}</template>
            </el-table-column>
            <el-table-column label="销量" prop="totalQuantity" min-width="100" align="right">
              <template slot-scope="scope">{{ formatNumber(scope.row.totalQuantity) }}</template>
            </el-table-column>
            <el-table-column label="销售额" prop="salesAmount" min-width="130" align="right">
              <template slot-scope="scope">¥{{ formatMoney(scope.row.salesAmount) }}</template>
            </el-table-column>
            <el-table-column label="客单价" prop="avgOrderValue" min-width="120" align="right">
              <template slot-scope="scope">¥{{ formatMoney(scope.row.avgOrderValue) }}</template>
            </el-table-column>
            <el-table-column label="毛利额" prop="grossProfit" min-width="100" align="center">
              <template slot-scope="scope">{{ scope.row.grossProfit || '--' }}</template>
            </el-table-column>
            <el-table-column label="毛利率" prop="grossMargin" min-width="100" align="center">
              <template slot-scope="scope">{{ scope.row.grossMargin || '--' }}</template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" min-width="260" show-overflow-tooltip />
          </el-table>
        </section>
      </section>

      <aside class="report-side">
        <div class="side-card performance-card">
          <div class="section-heading compact">
            <div>
              <h3>销售概览</h3>
              <p>当前筛选范围</p>
            </div>
          </div>
          <div class="gauge">
            <div class="gauge-arc" />
            <strong>{{ formatNumber(summary.orderCount) }}</strong>
            <span>总订单量</span>
          </div>
          <div class="side-metric">
            <span>平均每单件数</span>
            <strong>{{ formatNumber(avgItemsPerOrder) }}</strong>
          </div>
          <div class="side-metric">
            <span>覆盖渠道/店铺</span>
            <strong>{{ formatNumber(reportList.length) }}</strong>
          </div>
        </div>

        <div class="side-card">
          <div class="section-heading compact">
            <div>
              <h3>销售 Top 5</h3>
              <p>按销售额排序</p>
            </div>
          </div>
          <div v-if="topChannels.length" class="rank-list">
            <div v-for="(item, index) in topChannels" :key="`${item.channelName}-${index}`" class="rank-item">
              <span class="rank-index">{{ index + 1 }}</span>
              <div>
                <strong>{{ item.channelName || item.platformName || '未命名渠道' }}</strong>
                <small>{{ item.platformName || '暂无平台' }}</small>
              </div>
              <em>¥{{ formatMoney(item.salesAmount) }}</em>
            </div>
          </div>
          <el-empty v-else description="暂无数据" :image-size="72" />
        </div>
      </aside>
    </div>
  </div>
</template>

<script>
import { getShopMaxDate, getShopOperationReport } from '@/api/order'
import OrderDateRangeFilter from '@/views/order/components/OrderDateRangeFilter'

export default {
  name: 'ShopOperationReport',
  components: {
    OrderDateRangeFilter
  },
  data() {
    return {
      loading: false,
      maxDate: '',
      currentQuery: {},
      reportList: []
    }
  },
  computed: {
    summary() {
      const total = this.reportList.reduce((result, row) => {
        result.orderCount += Number(row.orderCount || 0)
        result.totalQuantity += Number(row.totalQuantity || 0)
        result.salesAmount += Number(row.salesAmount || 0)
        return result
      }, { orderCount: 0, totalQuantity: 0, salesAmount: 0 })
      total.avgOrderValue = total.orderCount > 0 ? total.salesAmount / total.orderCount : 0
      return total
    },
    summaryCards() {
      return [
        {
          key: 'sales',
          label: '销售额',
          value: `¥${this.formatMoney(this.summary.salesAmount)}`,
          hint: '当前周期累计销售',
          icon: 'el-icon-wallet',
          className: 'is-primary'
        },
        {
          key: 'orders',
          label: '订单量',
          value: this.formatNumber(this.summary.orderCount),
          hint: '有效订单总数',
          icon: 'el-icon-s-order',
          className: 'is-blue'
        },
        {
          key: 'quantity',
          label: '销量',
          value: this.formatNumber(this.summary.totalQuantity),
          hint: '商品销售件数',
          icon: 'el-icon-shopping-bag-1',
          className: 'is-orange'
        },
        {
          key: 'avg',
          label: '平均客单价',
          value: `¥${this.formatMoney(this.summary.avgOrderValue)}`,
          hint: '销售额 / 订单量',
          icon: 'el-icon-s-marketing',
          className: 'is-green'
        }
      ]
    },
    topChannels() {
      return [...this.reportList]
        .sort((a, b) => Number(b.salesAmount || 0) - Number(a.salesAmount || 0))
        .slice(0, 5)
    },
    avgItemsPerOrder() {
      return this.summary.orderCount > 0 ? this.summary.totalQuantity / this.summary.orderCount : 0
    },
    dateRangeLabel() {
      if (this.currentQuery.startDate && this.currentQuery.endDate) {
        return `${this.currentQuery.startDate} 至 ${this.currentQuery.endDate}`
      }
      return '等待筛选条件'
    }
  },
  created() {
    this.initFilter()
  },
  methods: {
    async initFilter() {
      try {
        const maxDate = await getShopMaxDate()
        this.maxDate = maxDate || ''
      } catch (error) {
        this.maxDate = ''
      }
    },
    buildParams() {
      return {
        periodType: this.currentQuery.periodType || 'day',
        startDate: this.currentQuery.startDate,
        endDate: this.currentQuery.endDate
      }
    },
    handleFilterChange(params) {
      this.currentQuery = params || {}
      this.handleQuery()
    },
    async handleQuery() {
      this.loading = true
      try {
        const res = await getShopOperationReport(this.buildParams())
        this.reportList = Array.isArray(res.data) ? res.data : []
      } finally {
        this.loading = false
      }
    },
    handleExport() {
      this.download('/api/shop/report/export', this.buildParams(), `店铺运营报表_${new Date().getTime()}.xlsx`)
    },
    formatNumber(value) {
      const number = Number(value || 0)
      return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(number)
    },
    formatMoney(value) {
      const number = Number(value || 0)
      return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(number)
    }
  }
}
</script>

<style scoped>
.shop-report-page {
  min-height: calc(100vh - 84px);
  padding: 24px;
  background: #eef3fb;
  color: #17243b;
}

.report-shell {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 300px;
  gap: 22px;
  max-width: 1680px;
  margin: 0 auto;
}

.report-main,
.report-side {
  min-width: 0;
}

.hero-panel {
  min-height: 150px;
  padding: 26px 30px;
  margin-bottom: 18px;
  border-radius: 22px;
  background: linear-gradient(110deg, #ffffff 0%, #f7f9ff 52%, #eaf0ff 100%);
  box-shadow: 0 20px 45px rgba(42, 61, 115, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
}

.eyebrow {
  margin: 0 0 8px;
  color: #6b6ff5;
  font-size: 12px;
  font-weight: 700;
  text-transform: uppercase;
}

.hero-panel h2 {
  margin: 0;
  font-size: 28px;
  line-height: 1.2;
  color: #101b33;
}

.hero-desc {
  max-width: 520px;
  margin: 12px 0 0;
  color: #7b8498;
  line-height: 1.7;
}

.hero-visual {
  position: relative;
  width: 168px;
  height: 110px;
  border-radius: 24px;
  background: #ffffff;
  box-shadow: 0 18px 40px rgba(91, 105, 247, 0.18);
}

.hero-icon {
  position: absolute;
  top: 20px;
  left: 22px;
  width: 48px;
  height: 48px;
  border-radius: 16px;
  background: #6c3df4;
  color: #fff;
  font-size: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hero-bars {
  position: absolute;
  right: 24px;
  bottom: 22px;
  display: flex;
  align-items: flex-end;
  gap: 9px;
}

.hero-bars i {
  width: 10px;
  border-radius: 999px;
  background: #ffb24d;
}

.hero-bars i:nth-child(1) { height: 32px; }
.hero-bars i:nth-child(2) { height: 52px; background: #5e6cf7; }
.hero-bars i:nth-child(3) { height: 42px; }
.hero-bars i:nth-child(4) { height: 64px; background: #ef4c43; }

.report-toolbar {
  margin-bottom: 16px;
  border-radius: 22px;
  box-shadow: 0 16px 36px rgba(38, 51, 96, 0.06);
  overflow: hidden;
}

.report-toolbar ::v-deep .order-date-filter {
  padding: 16px 18px;
  border: 0;
  border-radius: 22px;
  background: #fff;
  display: grid;
  grid-template-columns: auto 1fr;
  align-items: center;
  gap: 12px;
}

.report-toolbar ::v-deep .el-form-item {
  height: 38px;
  margin: 0;
  padding: 3px;
  border-radius: 15px;
  background: #f6f8ff;
  display: flex;
  align-items: center;
}

.report-toolbar ::v-deep .el-form-item:nth-child(1) {
  grid-column: 1 / -1;
  justify-self: start;
}

.report-toolbar ::v-deep .el-form-item:nth-child(2) {
  justify-self: start;
}

.report-toolbar ::v-deep .el-form-item__label {
  height: 32px;
  padding: 0 10px 0 8px;
  color: #5d667a;
  font-size: 13px;
  font-weight: 700;
  line-height: 32px;
}

.report-toolbar ::v-deep .el-form-item__content {
  line-height: 32px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.report-toolbar ::v-deep .date-action-row,
.report-toolbar ::v-deep .filter-actions {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.report-toolbar ::v-deep .el-radio-group {
  display: inline-flex;
  gap: 4px;
  padding: 0;
  vertical-align: top;
}

.report-toolbar ::v-deep .el-radio-button__inner {
  min-width: 56px;
  height: 32px;
  padding: 0 14px;
  border: 0;
  border-radius: 11px;
  background: transparent;
  color: #667086;
  line-height: 32px;
  box-shadow: none;
  transition: all 0.18s ease;
}

.report-toolbar ::v-deep .el-radio-button:first-child .el-radio-button__inner,
.report-toolbar ::v-deep .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 11px;
}

.report-toolbar ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background: #6267f2;
  color: #fff;
  box-shadow: 0 8px 18px rgba(98, 103, 242, 0.22);
}

.report-toolbar ::v-deep .el-date-editor.el-input__inner {
  width: 350px;
  height: 32px;
  padding: 0 12px;
  border: 0;
  border-radius: 12px;
  background: #fff;
  color: #29364f;
  box-shadow: inset 0 0 0 1px rgba(98, 103, 242, 0.12);
}

.report-toolbar ::v-deep .el-date-editor .el-range-input {
  width: 128px;
  color: #29364f;
  font-weight: 600;
  background: transparent;
}

.report-toolbar ::v-deep .el-date-editor .el-range-separator {
  width: 32px;
  color: #8c94a8;
  line-height: 30px;
}

.report-toolbar ::v-deep .el-date-editor .el-range__icon,
.report-toolbar ::v-deep .el-date-editor .el-range__close-icon {
  color: #9aa4bc;
  line-height: 30px;
}

.report-toolbar ::v-deep .el-button {
  height: 32px;
  padding: 0 16px;
  border-radius: 12px;
  font-weight: 700;
}

.report-toolbar ::v-deep .el-button--primary {
  background: #6267f2;
  border-color: #6267f2;
  box-shadow: 0 8px 18px rgba(98, 103, 242, 0.22);
}

.report-toolbar ::v-deep .el-button--default {
  border-color: transparent;
  background: #fff;
  color: #6e778b;
}

.report-toolbar ::v-deep .el-button--warning.is-plain {
  border-color: transparent;
  background: #fff6e8;
  color: #f39a20;
}

.report-toolbar ::v-deep .el-button + .el-button {
  margin-left: 0;
}

.report-alert {
  margin-bottom: 16px;
  border: 0;
  border-radius: 14px;
}

.summary-row {
  margin-bottom: 18px;
}

.summary-row .el-col {
  margin-bottom: 18px;
}

.summary-item {
  position: relative;
  min-height: 142px;
  padding: 20px;
  border: 0;
  border-radius: 20px;
  background: #fff;
  box-shadow: 0 16px 34px rgba(37, 50, 88, 0.08);
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  overflow: hidden;
}

.summary-item::after {
  content: "";
  position: absolute;
  top: -38px;
  right: -34px;
  width: 112px;
  height: 112px;
  border-radius: 50%;
  background: rgba(98, 103, 242, 0.1);
}

.summary-icon {
  position: absolute;
  top: 18px;
  left: 20px;
  width: 44px;
  height: 44px;
  border-radius: 15px;
  background: #f1efff;
  color: #6c3df4;
  font-size: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.summary-label {
  margin-bottom: 8px;
  color: #7b8498;
  font-size: 13px;
}

.summary-item strong {
  color: #121d35;
  font-size: 25px;
  line-height: 1.2;
}

.summary-item small {
  margin-top: 10px;
  color: #a0a8b8;
}

.summary-item.is-primary {
  color: #fff;
  background: linear-gradient(145deg, #7935f5 0%, #6028ee 100%);
  box-shadow: 0 20px 36px rgba(99, 50, 236, 0.24);
}

.summary-item.is-primary .summary-label,
.summary-item.is-primary small,
.summary-item.is-primary strong {
  color: #fff;
}

.summary-item.is-primary .summary-icon {
  background: #fff;
  color: #6c3df4;
}

.summary-item.is-blue .summary-icon {
  background: #edf1ff;
  color: #5e6cf7;
}

.summary-item.is-orange .summary-icon {
  background: #fff2dd;
  color: #f5a338;
}

.summary-item.is-green .summary-icon {
  background: #eaf8f4;
  color: #29b98f;
}

.table-card,
.side-card {
  border-radius: 22px;
  background: #fff;
  box-shadow: 0 18px 42px rgba(42, 61, 115, 0.08);
}

.table-card {
  padding: 20px;
}

.section-heading {
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.section-heading h3 {
  margin: 0;
  color: #101b33;
  font-size: 18px;
}

.section-heading p {
  margin: 6px 0 0;
  color: #8a93a6;
  font-size: 12px;
}

.section-heading.compact {
  margin-bottom: 14px;
}

.report-table {
  width: 100%;
  border-radius: 14px;
  overflow: hidden;
}

.report-table ::v-deep th.el-table__cell {
  background: #f8f9fd;
  color: #697287;
  font-weight: 700;
}

.report-table ::v-deep .el-table__cell {
  border-bottom-color: #eef1f7;
}

.report-table ::v-deep::before {
  display: none;
}

.report-side {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.side-card {
  padding: 20px;
}

.performance-card {
  overflow: hidden;
}

.gauge {
  position: relative;
  height: 142px;
  margin: 4px 0 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
}

.gauge-arc {
  position: absolute;
  top: 12px;
  width: 156px;
  height: 78px;
  border: 24px solid #edf0f7;
  border-bottom: 0;
  border-radius: 156px 156px 0 0;
}

.gauge-arc::after {
  content: "";
  position: absolute;
  inset: -24px -24px 0 -24px;
  border: 24px solid #ffad55;
  border-right-color: transparent;
  border-bottom: 0;
  border-radius: 156px 156px 0 0;
  transform: rotate(10deg);
  transform-origin: center bottom;
}

.gauge strong {
  position: relative;
  z-index: 1;
  color: #101b33;
  font-size: 28px;
}

.gauge span {
  position: relative;
  z-index: 1;
  margin-top: 4px;
  color: #8a93a6;
  font-size: 12px;
}

.side-metric {
  padding: 14px 0;
  border-top: 1px solid #eef1f7;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.side-metric span {
  color: #80899b;
}

.side-metric strong {
  color: #101b33;
  font-size: 18px;
}

.rank-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rank-item {
  min-height: 58px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f2f7;
  display: grid;
  grid-template-columns: 34px minmax(0, 1fr) auto;
  gap: 10px;
  align-items: center;
}

.rank-item:last-child {
  border-bottom: 0;
}

.rank-index {
  width: 28px;
  height: 28px;
  border-radius: 10px;
  background: #f1efff;
  color: #6c3df4;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rank-item strong,
.rank-item small {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rank-item strong {
  color: #1b2740;
}

.rank-item small {
  margin-top: 4px;
  color: #9aa3b4;
}

.rank-item em {
  color: #1b2740;
  font-style: normal;
  font-weight: 700;
}

@media (max-width: 1280px) {
  .report-shell {
    grid-template-columns: 1fr;
  }

  .report-side {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .shop-report-page {
    padding: 14px;
  }

  .hero-panel {
    padding: 22px;
  }

  .hero-visual {
    display: none;
  }

  .report-side {
    grid-template-columns: 1fr;
  }

  .report-toolbar ::v-deep .el-form-item {
    width: 100%;
    height: auto;
    align-items: flex-start;
    flex-direction: column;
  }

  .report-toolbar ::v-deep .el-form-item:nth-child(1),
  .report-toolbar ::v-deep .el-form-item:nth-child(2) {
    grid-column: 1;
  }

  .report-toolbar ::v-deep .date-action-row {
    width: 100%;
    flex-wrap: wrap;
  }

  .report-toolbar ::v-deep .el-date-editor.el-input__inner {
    width: 100%;
  }
}
</style>

<style>
.shop-report-date-popper {
  width: 646px;
  border: 0 !important;
  border-radius: 18px !important;
  background: #fff;
  box-shadow: 0 24px 60px rgba(32, 45, 82, 0.16) !important;
  overflow: hidden !important;
}

.shop-report-date-popper .popper__arrow {
  display: none;
}

.shop-report-date-popper.el-picker-panel {
  color: #24314a;
}

.shop-report-date-popper .el-picker-panel__body-wrapper {
  border-radius: 18px !important;
  overflow: hidden;
}

.shop-report-date-popper .el-picker-panel__body {
  min-width: 646px;
}

.shop-report-date-popper .el-date-range-picker__content {
  width: 50%;
  padding: 20px 22px 18px;
}

.shop-report-date-popper .el-date-range-picker__content.is-left {
  border-right-color: #eef1f7;
}

.shop-report-date-popper .el-date-range-picker__header {
  height: 32px;
  margin-bottom: 12px;
  line-height: 32px;
}

.shop-report-date-popper .el-date-range-picker__header div {
  color: #24314a;
  font-size: 16px;
  font-weight: 700;
}

.shop-report-date-popper .el-picker-panel__icon-btn {
  color: #8c94a8;
  font-size: 13px;
  line-height: 32px;
}

.shop-report-date-popper .el-date-table {
  table-layout: fixed;
}

.shop-report-date-popper .el-date-table th {
  padding: 6px 0 10px;
  color: #7d879b;
  font-weight: 700;
  border-bottom: 0;
}

.shop-report-date-popper .el-date-table td {
  height: 36px;
  padding: 2px 0;
  color: #26364f;
}

.shop-report-date-popper .el-date-table td div {
  height: 32px;
  padding: 2px 0;
  border-radius: 10px;
  box-sizing: border-box;
}

.shop-report-date-popper .el-date-table td span {
  width: 28px;
  height: 28px;
  border-radius: 9px;
  line-height: 28px;
}

.shop-report-date-popper .el-date-table td.available:hover span {
  background: #f0f2ff;
  color: #6267f2;
}

.shop-report-date-popper .el-date-table td.in-range div,
.shop-report-date-popper .el-date-table td.in-range div:hover {
  background: #f4f6ff;
}

.shop-report-date-popper .el-date-table td.disabled div {
  background: transparent;
}

.shop-report-date-popper .el-date-table td.disabled span {
  color: #b7bfce;
}

.shop-report-date-popper .el-date-table td.prev-month span,
.shop-report-date-popper .el-date-table td.next-month span {
  color: #b7bfce;
}

.shop-report-date-popper .el-date-table td.start-date span,
.shop-report-date-popper .el-date-table td.end-date span,
.shop-report-date-popper .el-date-table td.current:not(.disabled) span {
  background: #6267f2;
  color: #fff;
  box-shadow: 0 8px 16px rgba(98, 103, 242, 0.24);
}

.shop-report-date-popper .el-date-table td.start-date div,
.shop-report-date-popper .el-date-table td.end-date div {
  border-radius: 10px;
}

.shop-report-date-popper .el-date-table td.today span {
  color: #6267f2;
  font-weight: 700;
}

.shop-report-date-popper .el-date-table td.start-date.today span,
.shop-report-date-popper .el-date-table td.end-date.today span,
.shop-report-date-popper .el-date-table td.current.today span {
  color: #fff;
}
</style>
