<template>
  <el-container class="data-report-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple
          :searchFields="searchFields"
          :defaultValues="defaultSearchValues"
          @search="(val) => getData(1, val)"
          @reset="getData(1)"
        >
        </sa-search-simple>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">数据报表</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button icon="Download" type="primary" @click="exportData">导出</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-value">{{ statsData.totalSales || 0 }}</div>
                <div class="stats-label">总销售额（৳）</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-value">{{ statsData.totalOrders || 0 }}</div>
                <div class="stats-label">总订单数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-value">{{ statsData.totalUsers || 0 }}</div>
                <div class="stats-label">总用户数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-value">{{ statsData.totalGoods || 0 }}</div>
                <div class="stats-label">总商品数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <div class="sa-table-wrap panel-block panel-block--bottom" v-loading="loading">
        <el-table
          height="100%"
          class="sa-table"
          :data="table.data"
          @selection-change="changeSelection"
          @sort-change="fieldFilter"
          row-key="id"
          stripe
        >
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column type="selection" width="48" align="center"></el-table-column>
          <el-table-column prop="date" label="日期" min-width="120" sortable="custom">
          </el-table-column>
          <el-table-column label="销售额" min-width="120">
            <template #default="scope"> ৳{{ scope.row.sales_amount || 0 }} </template>
          </el-table-column>
          <el-table-column label="订单数" min-width="100">
            <template #default="scope">
              {{ scope.row.order_count || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="新增用户" min-width="100">
            <template #default="scope">
              {{ scope.row.new_users || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="访问量" min-width="100">
            <template #default="scope">
              {{ scope.row.page_views || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="转化率" min-width="100">
            <template #default="scope"> {{ scope.row.conversion_rate || 0 }}% </template>
          </el-table-column>
          <el-table-column label="客单价" min-width="120">
            <template #default="scope"> ৳{{ scope.row.avg_order_value || 0 }} </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #left>
        <sa-batch-handle
          :batchHandleTools="batchHandleTools"
          :selectedLeng="table.selected.length"
          @batchHandle="batchHandle"
        ></sa-batch-handle>
      </template>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { api } from '../data.service';
  import { ElMessage } from 'element-plus';
  import { usePagination } from '@/sheep/hooks';
  const { pageData } = usePagination();

  // 搜索字段配置
  const searchFields = reactive({
    date_range: {
      type: 'daterange',
      label: '日期范围',
      placeholder: '请选择日期范围',
      width: 300,
    },
  });
  // 默认搜索值
  const defaultSearchValues = reactive({
    date_range: [],
  });

  // 统计数据
  const statsData = reactive({
    totalSales: 0,
    totalOrders: 0,
    totalUsers: 0,
    totalGoods: 0,
  });

  // 列表
  const table = reactive({
    data: [],
    order: '',
    sort: '',
    selected: [],
  });
  const loading = ref(true);

  // 获取统计数据
  async function getStatsData() {
    const { error, data } = await api.report.getStats();
    if (error === 0) {
      Object.assign(statsData, data);
    }
  }

  // 获取
  async function getData(page, searchParams = {}) {
    if (page) pageData.page = page;
    loading.value = true;
    const { error, data } = await api.report.list({
      page: pageData.page,
      list_rows: pageData.list_rows,
      order: table.order,
      ...searchParams,
      sort: table.sort,
    });
    console.log('API 响应:', error, data);
    if (error === 0) {
      table.data = data.data;
      pageData.page = data.current_page;
      pageData.list_rows = data.per_page;
      pageData.total = data.total;
    }
    loading.value = false;
  }

  // table 字段排序
  function fieldFilter({ prop, order }) {
    table.order = order == 'ascending' ? 'asc' : 'desc';
    table.sort = prop;
    getData();
  }

  //table批量选择
  function changeSelection(row) {
    table.selected = row;
  }

  // 导出数据
  async function exportData() {
    ElMessage.success('导出功能开发中...');
  }

  // 分页/批量操作
  const batchHandleTools = [
    {
      type: 'export',
      label: '导出选中',
      auth: 'shop.admin.data.report.export',
      class: 'primary',
    },
  ];

  async function batchHandle(type) {
    let ids = [];
    table.selected.forEach((row) => {
      ids.push(row.id);
    });
    switch (type) {
      case 'export':
        ElMessage.success('批量导出功能开发中...');
        break;
    }
  }

  onMounted(() => {
    getStatsData();
    getData();
  });
</script>
<style lang="scss" scoped>
  .data-report-view {
    .el-header {
      height: auto;
    }
    .el-main {
      .stats-cards {
        margin-bottom: 20px;
        .stats-card {
          .stats-content {
            text-align: center;
            .stats-value {
              font-size: 24px;
              font-weight: bold;
              color: #409eff;
              margin-bottom: 8px;
            }
            .stats-label {
              font-size: 14px;
              color: #666;
            }
          }
        }
      }
      .sa-table-wrap {
        height: calc(100% - 140px);
      }
    }
  }
</style>
