<template>
  <div class="home card">
    <!-- 搜索表单 -->
    <el-form :model="searchParams" :inline="true" class="search-form">
      <el-form-item label="日期范围">
        <el-select
          v-model="searchParams.dateRange"
          placeholder="请选择日期范围"
          style="width: 150px"
          clearable
          @change="handleDateRangeChange"
        >
          <el-option label="昨日" value="YESTERDAY" />
          <el-option label="最近7天" value="LAST7DAYS" />
          <el-option label="本周" value="THIS_WEEK" />
          <el-option label="本月" value="THIS_MONTH" />
          <el-option label="本季度" value="THIS_QUARTER" />
          <el-option label="自定义" value="CUSTOM" />
        </el-select>
      </el-form-item>
      <el-form-item label="获取时间" v-if="searchParams.dateRange === 'CUSTOM'">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 240px"
          @change="handleCustomDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="label" label="统计项" width="200" align="left" />
      <el-table-column prop="current" label="本期" align="right">
        <template #default="scope">
          <span>{{ formatNumber(scope.row.current) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="last" label="上期" align="right">
        <template #default="scope">
          <span>{{ formatNumber(scope.row.last) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="change" label="变化" align="right">
        <template #default="scope">
          <span :class="getChangeClass(scope.row.change)">
            {{ formatChange(scope.row.change) }}
          </span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts" name="home">
import { ref, reactive, onMounted } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { getHomeStaticsAll, type ResHomeStatics, type ReqHomeStaticsParams } from "@/api/modules/home";

// 日期范围枚举
enum DateRangeEnum {
  YESTERDAY = "YESTERDAY", // 昨日
  LAST7DAYS = "LAST7DAYS", // 最近7天
  THIS_WEEK = "THIS_WEEK", // 本周
  THIS_MONTH = "THIS_MONTH", // 本月
  THIS_QUARTER = "THIS_QUARTER", // 本季度
  CUSTOM = "CUSTOM" // 自定义
}

// 搜索参数
const searchParams = reactive<ReqHomeStaticsParams & { dateRange?: string }>({
  currentStart: "",
  currentEnd: "",
  dateRange: "LAST7DAYS" // 默认选择最近7天
});

// 日期范围选择器（仅用于自定义）
const dateRange = ref<string[]>([]);

// 表格数据
const tableData = ref<any[]>([]);

// 统计项标签映射
const labelMap: Record<string, string> = {
  advertiserAccountCount: "广告账户数量",
  cost: "总消耗",
  noGrantCost: "非赠款消耗",
  materialCost: "素材总消耗",
  firstPublishMaterialCost: "首发素材消耗",
  highQualityMaterialCost: "优质素材消耗",
  poorQualityMaterialCost: "低质素材消耗",
  lowEfficiencyMaterialCost: "低效素材消耗",
  improvableMaterialCost: "可提升素材消耗"
};

// 格式化数字
const formatNumber = (num: number): string => {
  if (num === 0) return "0";
  if (num >= 10000) {
    return (num / 10000).toFixed(2) + "万";
  }
  return num.toLocaleString("zh-CN", { maximumFractionDigits: 2 });
};

// 格式化变化值
const formatChange = (change: number): string => {
  if (change === 0) return "0";
  const absChange = Math.abs(change);
  const sign = change > 0 ? "+" : "-";
  return `${sign}${formatNumber(absChange)}`;
};

// 获取变化样式类
const getChangeClass = (change: number): string => {
  if (change > 0) return "change-positive";
  if (change < 0) return "change-negative";
  return "";
};

// 计算日期范围
const calculateDateRange = (dateRange: string): string[] | null => {
  if (!dateRange || dateRange === DateRangeEnum.CUSTOM) {
    return null; // 自定义时返回 null，使用手动选择的日期
  }

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  let startDate: Date;
  let endDate: Date = new Date(today);
  endDate.setHours(23, 59, 59, 999);

  switch (dateRange) {
    case DateRangeEnum.YESTERDAY: {
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 1);
      endDate = new Date(startDate);
      endDate.setHours(23, 59, 59, 999);
      break;
    }
    case DateRangeEnum.LAST7DAYS: {
      startDate = new Date(today);
      startDate.setDate(today.getDate() - 6); // 包含今天，所以是6天前
      break;
    }
    case DateRangeEnum.THIS_WEEK: {
      const dayOfWeek = today.getDay();
      const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek; // 周一
      startDate = new Date(today);
      startDate.setDate(today.getDate() + diff);
      break;
    }
    case DateRangeEnum.THIS_MONTH: {
      startDate = new Date(today.getFullYear(), today.getMonth(), 1);
      break;
    }
    case DateRangeEnum.THIS_QUARTER: {
      const month = today.getMonth();
      const quarterStartMonth = Math.floor(month / 3) * 3;
      startDate = new Date(today.getFullYear(), quarterStartMonth, 1);
      break;
    }
    default:
      return null;
  }

  const formatDate = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  };

  return [formatDate(startDate), formatDate(endDate)];
};

// 处理日期范围变化
const handleDateRangeChange = (value: string) => {
  if (value && value !== DateRangeEnum.CUSTOM) {
    const dateRangeResult = calculateDateRange(value);
    if (dateRangeResult) {
      searchParams.currentStart = dateRangeResult[0];
      searchParams.currentEnd = dateRangeResult[1];
      // 自动触发查询
      handleSearch();
    }
  } else if (value === DateRangeEnum.CUSTOM) {
    // 自定义时清空日期，让用户手动选择
    dateRange.value = [];
  } else if (!value) {
    // 清空时也清空日期
    dateRange.value = [];
  }
};

// 处理自定义日期范围变化
const handleCustomDateRangeChange = (dates: string[] | null) => {
  if (dates && dates.length === 2) {
    searchParams.currentStart = dates[0];
    searchParams.currentEnd = dates[1];
  }
};

// 查询
const handleSearch = () => {
  loadData();
};

// 重置
const handleReset = () => {
  searchParams.dateRange = "LAST7DAYS";
  const dateRangeResult = calculateDateRange("LAST7DAYS");
  if (dateRangeResult) {
    searchParams.currentStart = dateRangeResult[0];
    searchParams.currentEnd = dateRangeResult[1];
  }
  dateRange.value = [];
  loadData();
};

// 加载数据
const loadData = async () => {
  try {
    const { data } = await getHomeStaticsAll(searchParams);

    // 转换为表格数据格式
    tableData.value = Object.keys(labelMap).map(key => {
      const current = data.current[key as keyof typeof data.current] || 0;
      const last = data.last[key as keyof typeof data.last] || 0;
      const change = current - last;

      return {
        label: labelMap[key],
        current,
        last,
        change
      };
    });
  } catch (error) {
    console.error("加载统计数据失败:", error);
  }
};

onMounted(() => {
  // 初始化默认日期范围
  if (searchParams.dateRange && searchParams.dateRange !== DateRangeEnum.CUSTOM) {
    const dateRangeResult = calculateDateRange(searchParams.dateRange);
    if (dateRangeResult) {
      searchParams.currentStart = dateRangeResult[0];
      searchParams.currentEnd = dateRangeResult[1];
    }
  }
  loadData();
});
</script>

<style scoped lang="scss">
@import "./index.scss";

.home {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .change-positive {
    color: #f56c6c;
  }

  .change-negative {
    color: #67c23a;
  }
}
</style>
