<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import * as echarts from "echarts";
import { getProfitOverview, getProfitList, getProfitTrend, getProfitWarning } from "@/api/statistics";

defineOptions({
  name: "ProfitStatistics"
});

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: "",
  shopId: null as number | null,
  compareType: "",
  sortBy: "netProfit",
  sortOrder: "desc"
});

const overviewData = ref({
  salesAmount: 0,
  costAmount: 0,
  grossProfit: 0,
  grossProfitRate: 0
});

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

const profitChartRef = ref<HTMLElement | null>(null);
const warningChartRef = ref<HTMLElement | null>(null);
let profitChart: echarts.ECharts | null = null;
let warningChart: echarts.ECharts | null = null;

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

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

async function fetchProfitTrend() {
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    
    const { data } = await getProfitTrend(params);
    initProfitChart(data);
  } catch (error) {
    console.error("获取利润趋势失败:", error);
  }
}

async function fetchWarning() {
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1]),
      type: "low"
    };
    
    const { data } = await getProfitWarning(params);
    warningData.value = data || [];
    initWarningChart();
  } catch (error) {
    console.error("获取利润预警失败:", error);
  }
}

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

function initProfitChart(data: any) {
  if (!profitChartRef.value) return;
  
  if (profitChart) {
    profitChart.dispose();
  }
  
  profitChart = echarts.init(profitChartRef.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)" }
          ])
        }
      }
    ]
  };
  
  profitChart.setOption(option);
}

function initWarningChart() {
  if (!warningChartRef.value) return;
  
  if (warningChart) {
    warningChart.dispose();
  }
  
  warningChart = echarts.init(warningChartRef.value);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "利润预警门店",
      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: warningData.value.slice(0, 10).map((item: any) => item.shopName).reverse(),
      axisLabel: {
        width: 80,
        overflow: "truncate"
      }
    },
    series: [
      {
        name: "净利润",
        type: "bar",
        data: warningData.value.slice(0, 10).map((item: any) => item.netProfit).reverse(),
        itemStyle: {
          color: (params: any) => params.value >= 0 ? "#67c23a" : "#f56c6c"
        }
      }
    ]
  };
  
  warningChart.setOption(option);
}

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

function handleReset() {
  queryParams.keyword = "";
  queryParams.province = "";
  queryParams.city = "";
  queryParams.shopId = null;
  queryParams.compareType = "";
  queryParams.page = 1;
  fetchProfitList();
}

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

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

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

function handleDateChange() {
  fetchOverview();
  fetchProfitList();
  fetchProfitTrend();
  fetchWarning();
}

function resizeCharts() {
  profitChart?.resize();
  warningChart?.resize();
}

onMounted(() => {
  fetchOverview();
  fetchProfitList();
  fetchProfitTrend();
  fetchWarning();
  window.addEventListener("resize", resizeCharts);
});
</script>

<template>
  <div class="profit-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:money-cny-circle-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.salesAmount?.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-red">
              <i class="ri:wallet-3-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.costAmount?.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-green">
              <i class="ri:profit-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.grossProfit?.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:percent-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.grossProfitRate }}%</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="profitChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="warningChartRef" 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.compareType" placeholder="对比周期" clearable style="width: 120px">
              <el-option label="同比" value="yoy" />
              <el-option label="环比" value="mom" />
            </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="salesAmount" label="销售收入(元)" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            ¥{{ row.salesAmount?.toLocaleString() || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="costAmount" label="销售成本(元)" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.costAmount?.toLocaleString() || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="grossProfit" label="毛利润(元)" width="110" align="right" sortable="custom">
          <template #default="{ row }">
            <span :class="row.grossProfit >= 0 ? 'text-green-500' : 'text-red-500'">
              ¥{{ row.grossProfit?.toLocaleString() || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="grossProfitRate" label="毛利率" width="90" align="right">
          <template #default="{ row }">
            <span :class="row.grossProfitRate >= 0 ? 'text-green-500' : 'text-red-500'">
              {{ row.grossProfitRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="netProfit" label="净利润(元)" width="110" align="right" sortable="custom">
          <template #default="{ row }">
            <span :class="row.netProfit >= 0 ? 'text-green-500' : 'text-red-500'">
              ¥{{ row.netProfit?.toLocaleString() || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="netProfitRate" label="净利率" width="90" align="right">
          <template #default="{ row }">
            <span :class="row.netProfitRate >= 0 ? 'text-green-500' : 'text-red-500'">
              {{ row.netProfitRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="deviceCount" label="设备数" width="80" align="right" />
        <el-table-column prop="deviceProfit" label="单设备利润" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.deviceProfit || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="dailyProfit" label="日均利润" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.dailyProfit || 0 }}
          </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>
.profit-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-red { background: linear-gradient(135deg, #f56c6c, #c45656); }
    &.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>
