<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import * as echarts from "echarts";
import { getShopOverview, getShopList, getShopRanking, getShopTrend } from "@/api/statistics";

defineOptions({
  name: "ShopStatistics"
});

const loading = ref(false);
const dateRange = ref<[Date, Date]>([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  new Date()
]);

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
  province: "",
  city: "",
  district: "",
  status: null as number | null,
  sortBy: "salesAmount",
  sortOrder: "desc"
});

const overviewData = ref({
  totalShops: 0,
  activeShops: 0,
  totalSales: 0,
  totalOrders: 0
});

const tableData = ref([]);
const total = ref(0);
const rankingData = ref([]);

const salesChartRef = ref<HTMLElement | null>(null);
const rankingChartRef = ref<HTMLElement | null>(null);
let salesChart: echarts.ECharts | null = null;
let rankingChart: echarts.ECharts | null = null;

async function fetchOverview() {
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    
    const { data } = await getShopOverview(params);
    overviewData.value = data;
  } catch (error) {
    console.error("获取门店概览失败:", error);
  }
}

async function fetchShopList() {
  loading.value = true;
  try {
    const params = {
      ...queryParams,
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    
    const { data } = await getShopList(params);
    tableData.value = data.list || [];
    total.value = Number(data.total) || 0;
  } catch (error) {
    console.error("获取门店统计数据失败:", error);
  } finally {
    loading.value = false;
  }
}

async function fetchRanking() {
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1]),
      type: "sales",
      limit: 10
    };
    
    const { data } = await getShopRanking(params);
    rankingData.value = data || [];
    initRankingChart();
  } catch (error) {
    console.error("获取门店排行失败:", error);
  }
}

function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}

function initRankingChart() {
  if (!rankingChartRef.value) return;
  
  if (rankingChart) {
    rankingChart.dispose();
  }
  
  rankingChart = echarts.init(rankingChartRef.value);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "门店销售排行 TOP10",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      name: "销售额(元)"
    },
    yAxis: {
      type: "category",
      data: rankingData.value.map((item: any) => item.shopName).reverse(),
      axisLabel: {
        width: 80,
        overflow: "truncate"
      }
    },
    series: [
      {
        name: "销售额",
        type: "bar",
        data: rankingData.value.map((item: any) => item.salesAmount).reverse(),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: "#83bff6" },
            { offset: 1, color: "#188df0" }
          ])
        }
      }
    ]
  };
  
  rankingChart.setOption(option);
}

async function showShopTrend(shopId: number) {
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    
    const { data } = await getShopTrend(shopId, params);
    initSalesChart(data);
  } catch (error) {
    console.error("获取门店趋势失败:", error);
  }
}

function initSalesChart(data: any) {
  if (!salesChartRef.value) return;
  
  if (salesChart) {
    salesChart.dispose();
  }
  
  salesChart = echarts.init(salesChartRef.value);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "门店销售趋势",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#e5e7eb",
      borderWidth: 1
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: data.dates || [],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: "value",
      name: "销售额(元)"
    },
    series: [
      {
        name: "销售额",
        type: "line",
        smooth: true,
        data: data.series?.[0]?.data || [],
        itemStyle: { color: "#67c23a" },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
            { offset: 1, color: "rgba(103, 194, 58, 0.05)" }
          ])
        }
      }
    ]
  };
  
  salesChart.setOption(option);
}

function handleSearch() {
  queryParams.page = 1;
  fetchShopList();
}

function handleReset() {
  queryParams.keyword = "";
  queryParams.province = "";
  queryParams.city = "";
  queryParams.district = "";
  queryParams.status = null;
  queryParams.page = 1;
  fetchShopList();
}

function handleSortChange({ prop, order }: any) {
  queryParams.sortBy = prop || "salesAmount";
  queryParams.sortOrder = order === "ascending" ? "asc" : "desc";
  fetchShopList();
}

function handlePageChange(page: number) {
  queryParams.page = page;
  fetchShopList();
}

function handleSizeChange(size: number) {
  queryParams.pageSize = size;
  queryParams.page = 1;
  fetchShopList();
}

function handleDateChange() {
  fetchOverview();
  fetchShopList();
  fetchRanking();
}

function handleViewTrend(row: any) {
  showShopTrend(row.shopId);
}

function resizeCharts() {
  salesChart?.resize();
  rankingChart?.resize();
}

onMounted(() => {
  fetchOverview();
  fetchShopList();
  fetchRanking();
  window.addEventListener("resize", resizeCharts);
});
</script>

<template>
  <div class="shop-statistics">
    <el-card shadow="never" class="mb-4">
      <div class="flex items-center justify-between">
        <span class="text-lg font-medium">门店销售统计</span>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
      </div>
    </el-card>

    <el-row :gutter="20" class="mb-6">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-blue">
              <i class="ri:store-2-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalShops }}</div>
              <div class="stat-label">门店总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-green">
              <i class="ri:store-3-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.activeShops }}</div>
              <div class="stat-label">营业门店</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-purple">
              <i class="ri:money-cny-circle-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.totalSales?.toLocaleString() || 0 }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-orange">
              <i class="ri:shopping-cart-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalOrders?.toLocaleString() || 0 }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-6">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="rankingChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="salesChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="font-medium">门店销售明细</span>
          <div class="flex items-center gap-2">
            <el-input
              v-model="queryParams.keyword"
              placeholder="门店名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
            <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 120px">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="tableData" stripe v-loading="loading" @sort-change="handleSortChange">
        <el-table-column prop="shopName" label="门店名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="province" label="省份" width="80" />
        <el-table-column prop="city" label="城市" width="80" />
        <el-table-column prop="deviceCount" label="设备数" width="80" align="right" />
        <el-table-column prop="orderCount" label="订单数" width="80" align="right" sortable="custom" />
        <el-table-column prop="userCount" label="购买用户数" width="100" align="right" />
        <el-table-column prop="salesAmount" label="销售额(元)" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            ¥{{ row.salesAmount?.toLocaleString() || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="avgOrderAmount" label="平均客单价" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.avgOrderAmount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="dailySalesAmount" label="日均销售" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.dailySalesAmount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceOutput" label="单设备产出" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.deviceOutput || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleViewTrend(row)">趋势</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.shop-statistics {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 120px);
}

.stat-card {
  display: flex;
  align-items: center;
  
  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 24px;
      color: white;
    }
    
    &.bg-blue { background: linear-gradient(135deg, #409eff, #337ecc); }
    &.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
    &.bg-purple { background: linear-gradient(135deg, #722ed1, #531dab); }
    &.bg-orange { background: linear-gradient(135deg, #fa8c16, #d46b08); }
  }
  
  .stat-info {
    flex: 1;
    
    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.chart-card {
  height: 350px;
  
  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
  }
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 280px;
  }
}
</style>
