<template>
  <div class="">
    <!-- 视图切换按钮和搜索表单 -->
    <div class="header-section">
      <div class="view-switch">
        <el-radio-group v-model="viewType" @change="handleViewChange">
          <el-radio-button label="table">表格</el-radio-button>
          <el-radio-button label="chart">柱状图</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 共享搜索表单 -->
      <el-form :model="initParam" :inline="true" class="shared-search-form">
        <el-form-item label="日期范围">
          <el-select
            v-model="initParam.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="initParam.dateRange === 'CUSTOM'">
          <el-date-picker
            v-model="initParam.dt"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="广告主ID">
          <el-input
            v-model="initParam.advertiserId"
            placeholder="请输入广告主ID"
            style="width: 200px"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="广告主公司ID">
          <el-input
            v-model="initParam.advCompanyId"
            placeholder="请输入广告主公司ID"
            style="width: 200px"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="广告主公司名称">
          <el-input
            v-model="initParam.advCompanyName"
            placeholder="请输入广告主公司名称"
            style="width: 200px"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 总计数据展示（仅表格视图显示） -->
    <div v-if="viewType === 'table'" class="total-data-section">
      <el-descriptions title="总计数据" :column="3" border>
        <el-descriptions-item label="总消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.cost.current }} / {{ totalDiffData.cost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.cost.color }">
              {{ totalDiffData.cost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="非赠款消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.noGrantCost.current }} / {{ totalDiffData.noGrantCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.noGrantCost.color }">
              {{ totalDiffData.noGrantCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="素材总消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.materialCost.current }} / {{ totalDiffData.materialCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.materialCost.color }">
              {{ totalDiffData.materialCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="首发素材消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.firstPublishMaterialCost.current }} / {{ totalDiffData.firstPublishMaterialCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.firstPublishMaterialCost.color }">
              {{ totalDiffData.firstPublishMaterialCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="优质素材消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.highQualityMaterialCost.current }} / {{ totalDiffData.highQualityMaterialCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.highQualityMaterialCost.color }">
              {{ totalDiffData.highQualityMaterialCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="低质素材消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.poorQualityMaterialCost.current }} / {{ totalDiffData.poorQualityMaterialCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.poorQualityMaterialCost.color }">
              {{ totalDiffData.poorQualityMaterialCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="低效素材消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.lowEfficiencyMaterialCost.current }} / {{ totalDiffData.lowEfficiencyMaterialCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.lowEfficiencyMaterialCost.color }">
              {{ totalDiffData.lowEfficiencyMaterialCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="可提升素材消耗（当前/上期）">
          <div class="total-diff-content">
            <div>{{ totalDiffData.improvableMaterialCost.current }} / {{ totalDiffData.improvableMaterialCost.last }}</div>
            <div class="total-diff" :style="{ color: totalDiffData.improvableMaterialCost.color }">
              {{ totalDiffData.improvableMaterialCost.diff }}
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 表格视图 -->
    <ProTable
      v-if="viewType === 'table'"
      ref="proTable"
      :columns="tableColumns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :tool-button="['refresh', 'setting']"
      row-key="advertiserId"
      height="1800"
    >
      <!-- 表格 header 按钮 -->
      <!-- <template #tableHeader="scope"> -->
      <!-- <el-button type="primary" plain @click="batchDelete(scope.selectedList)"> 批量同步广告主消耗数据 </el-button> -->
      <!-- </template> -->
    </ProTable>

    <!-- 柱状图视图 -->
    <div v-if="viewType === 'chart'" class="chart-container">
      <div class="chart-header">
        <el-radio-group v-model="chartPeriod" size="small">
          <el-radio-button label="current">当前期</el-radio-button>
          <el-radio-button label="last">上期</el-radio-button>
        </el-radio-group>
      </div>
      <ECharts :option="chartOption" :height="500" />
    </div>

    <SynchronizationAdvertiserAccountCostDt ref="synchronizationAdvertiserAccountCostDt" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { advertiserStatus } from "@/utils/dict";
import ECharts from "@/components/ECharts/index.vue";
import { ECOption } from "@/components/ECharts/config";

import { 
  getAdvertiserAccountCostDtList,
  getAdvertiserAccountCostDtRangeStaticsPage,
  getAdvertiserAccountCostDtRangeStaticsTotal
} from "@/api/modules/dataManage";
import SynchronizationAdvertiserAccountCostDt from "./components/SynchronizationAdvertiserAccountCostDt.vue";
const synchronizationAdvertiserAccountCostDt = ref<any>();

// 视图类型：table 表格，chart 柱状图
const viewType = ref<"table" | "chart">("table");
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<any>({
  dateRange: "LAST7DAYS" // 默认选择最近7天
});
const advertiserId = ref<string[]>([]);

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

// 计算日期范围
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 dateRange = calculateDateRange(value);
    if (dateRange) {
      initParam.dt = dateRange;
      // 自动触发查询
      handleSearch();
    }
  } else if (value === DateRangeEnum.CUSTOM) {
    // 自定义时清空日期，让用户手动选择
    initParam.dt = undefined;
  } else if (!value) {
    // 清空时也清空日期
    initParam.dt = undefined;
  }
};

// 初始化时设置默认日期范围
onMounted(() => {
  if (initParam.dateRange && initParam.dateRange !== DateRangeEnum.CUSTOM) {
    const dateRange = calculateDateRange(initParam.dateRange);
    if (dateRange) {
      initParam.dt = dateRange;
    }
  }
});

// dataCallback 是对于返回的表格数据做处理
// 接口返回数据结构：
// {
//   "content": [
//     {
//       "advertiserInfo": { "advertiserId": 0, "advertiserName": "string" },
//       "current": { "cost": 0, "noGrantCost": 0, "materialCost": 0, ... },
//       "last": { "cost": 0, "noGrantCost": 0, "materialCost": 0, ... }
//     }
//   ],
//   "total": 0
// }
const dataCallback = (data: any) => {
  // 处理返回的数据结构，将 advertiserInfo、current、last 扁平化以便表格显示
  const content = (data?.content || []).map((item: any) => {
    // 确保数据结构匹配：item.advertiserInfo, item.current, item.last
    const advertiserInfo = item.advertiserInfo || {};
    const current = item.current || {};
    const last = item.last || {};
    
    return {
      // 广告主信息
      advertiserId: advertiserInfo.advertiserId,
      advertiserName: advertiserInfo.advertiserName,
      // 当前期数据（完整字段）
      cost: current.cost || 0,
      noGrantCost: current.noGrantCost || 0,
      materialCost: current.materialCost || 0,
      firstPublishMaterialCost: current.firstPublishMaterialCost || 0,
      highQualityMaterialCost: current.highQualityMaterialCost || 0,
      poorQualityMaterialCost: current.poorQualityMaterialCost || 0,
      lowEfficiencyMaterialCost: current.lowEfficiencyMaterialCost || 0,
      improvableMaterialCost: current.improvableMaterialCost || 0,
      // 上期数据（完整字段，用于对比）
      lastCost: last.cost || 0,
      lastNoGrantCost: last.noGrantCost || 0,
      lastMaterialCost: last.materialCost || 0,
      lastFirstPublishMaterialCost: last.firstPublishMaterialCost || 0,
      lastHighQualityMaterialCost: last.highQualityMaterialCost || 0,
      lastPoorQualityMaterialCost: last.poorQualityMaterialCost || 0,
      lastLowEfficiencyMaterialCost: last.lowEfficiencyMaterialCost || 0,
      lastImprovableMaterialCost: last.improvableMaterialCost || 0,
      // 保留原始数据以便后续使用
      _raw: item
    };
  });
  return {
    content: content,
    total: Number(data?.total) || content.length
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  // delete newParams.createTime;
  // 处理获取时间日期范围
  newParams.dt && (newParams.currentStart = newParams.dt[0]);
  newParams.dt && (newParams.currentEnd = newParams.dt[1]);
  delete newParams.dt;
  // 使用新的分页接口
  return getAdvertiserAccountCostDtRangeStaticsPage(newParams);
};

// 柱状图数据
const chartData = ref<any>(null);

// 总计数据（用于表格视图显示）
const totalData = ref<{
  current?: any;
  last?: any;
}>({
  current: {},
  last: {}
});

// 精确除法函数，避免浮点数精度问题
const mathDiv = (a: number, b: number): number => {
  if (b === 0) return 0;
  const factor = Math.pow(10, Math.max(getDecimalPlaces(a), getDecimalPlaces(b)));
  return (Math.round(a * factor) / Math.round(b * factor));
};

// 获取小数位数
const getDecimalPlaces = (num: number): number => {
  const str = num.toString();
  if (str.indexOf('.') === -1) return 0;
  return str.split('.')[1].length;
};

// 获取柱状图数据
const getChartData = async () => {
  try {
    // 使用表格的查询参数（优先从 ProTable 实例获取，如果不存在则使用 initParam）
    const tableSearchParam = proTable.value?.searchParam || {};
    const tableInitParam = proTable.value?.searchInitParam || {};
    const pageable = proTable.value?.pageable || { page: 1, size: 10 };
    // 合并表格的查询参数，使用表格的分页参数
    const params: any = {
      ...initParam,
      ...tableInitParam,
      ...tableSearchParam,
      page: pageable.page,
      size: pageable.size
    };
    
    // 请求分页数据（百分比计算基于当前页数据的总和，不再需要总计数据）
    const pageRes = await getTableList(params);
    
    // 处理返回的数据结构
    const pageData = pageRes?.data || pageRes;
    chartData.value = pageData;
  } catch (error) {
    console.error("获取柱状图数据失败:", error);
    ElMessage.error("获取柱状图数据失败");
    // 确保即使出错也设置默认值，避免图表不显示
    chartData.value = { content: [] };
  }
};

// 获取总计数据
const getTotalData = async (params: any) => {
  try {
    // 使用和表格相同的参数处理逻辑
    let totalParams = JSON.parse(JSON.stringify(params));
    totalParams.createTime && (totalParams.startTime = totalParams.createTime[0]);
    totalParams.createTime && (totalParams.endTime = totalParams.createTime[1]);
    // 处理获取时间日期范围
    totalParams.dt && (totalParams.currentStart = totalParams.dt[0]);
    totalParams.dt && (totalParams.currentEnd = totalParams.dt[1]);
    delete totalParams.dt;
    // 移除分页参数
    delete totalParams.page;
    delete totalParams.size;
    
    const res: any = await getAdvertiserAccountCostDtRangeStaticsTotal(totalParams);
    // 提取总计数据（根据当前期或上期）
    // 接口返回结构可能是 { data: { current: {...}, last: {...} } } 或直接 { current: {...}, last: {...} }
    const data = res?.data || res;
    const periodData = chartPeriod.value === "current" 
      ? (data?.current || {}) 
      : (data?.last || {});
    console.log("总计数据获取:", { res, data, periodData, chartPeriod: chartPeriod.value });
    return periodData;
  } catch (error) {
    console.error("获取总计数据失败:", error);
    return {};
  }
};

// 加载总计数据（用于表格视图）
const loadTotalData = async () => {
  try {
    // 使用表格的查询参数
    const tableSearchParam = proTable.value?.searchParam || {};
    const tableInitParam = proTable.value?.searchInitParam || {};
    // 合并表格的查询参数
    const params: any = {
      ...initParam,
      ...tableInitParam,
      ...tableSearchParam
    };
    
    // 使用和表格相同的参数处理逻辑
    let totalParams = JSON.parse(JSON.stringify(params));
    totalParams.createTime && (totalParams.startTime = totalParams.createTime[0]);
    totalParams.createTime && (totalParams.endTime = totalParams.createTime[1]);
    // 处理获取时间日期范围
    totalParams.dt && (totalParams.currentStart = totalParams.dt[0]);
    totalParams.dt && (totalParams.currentEnd = totalParams.dt[1]);
    delete totalParams.dt;
    // 移除分页参数
    delete totalParams.page;
    delete totalParams.size;
    
    const res: any = await getAdvertiserAccountCostDtRangeStaticsTotal(totalParams);
    // 接口返回结构可能是 { data: { current: {...}, last: {...} } } 或直接 { current: {...}, last: {...} }
    const data = res?.data || res;
    totalData.value = {
      current: data?.current || {},
      last: data?.last || {}
    };
  } catch (error) {
    console.error("获取总计数据失败:", error);
    ElMessage.error("获取总计数据失败");
    totalData.value = {
      current: {},
      last: {}
    };
  }
};

// 柱状图数据期数选择：current 当前期，last 上期
const chartPeriod = ref<"current" | "last">("current");

// 注意：百分比计算已改为基于当前页数据的总和，不再需要总计数据

// 柱状图配置
const chartOption = computed<ECOption>(() => {
  if (!chartData.value || (Array.isArray(chartData.value) && chartData.value.length === 0)) {
    return {
      title: {
        text: "广告主消耗统计",
        left: "center"
      },
      tooltip: {
        trigger: "axis"
      },
      xAxis: [
        {
          type: "category",
          data: []
        }
      ],
      yAxis: [
        {
          type: "value"
        }
      ],
      series: []
    } as ECOption;
  }

  // 接口返回数据结构：
  // {
  //   "content": [
  //     {
  //       "advertiserInfo": { "advertiserId": 0, "advertiserName": "string" },
  //       "current": { "cost": 0, "noGrantCost": 0, "materialCost": 0, ... },
  //       "last": { "cost": 0, "noGrantCost": 0, "materialCost": 0, ... }
  //     }
  //   ]
  // }
  // 处理不同的数据结构
  let content: any[] = [];
  if (chartData.value) {
    if (Array.isArray(chartData.value)) {
      content = chartData.value;
    } else if (chartData.value.content) {
      content = chartData.value.content;
    } else if (chartData.value.data) {
      content = Array.isArray(chartData.value.data) ? chartData.value.data : (chartData.value.data.content || []);
    }
  }
  
  // 提取广告主名称和所有消耗数据
  const advertiserNames: string[] = [];
  const costData: number[] = [];
  const noGrantCostData: number[] = [];
  const materialCostData: number[] = [];
  const firstPublishMaterialCostData: number[] = [];
  const highQualityMaterialCostData: number[] = [];
  const poorQualityMaterialCostData: number[] = [];
  const lowEfficiencyMaterialCostData: number[] = [];
  const improvableMaterialCostData: number[] = [];

  // 计算当前页数据的总和
  let pageTotal = {
    cost: 0,
    noGrantCost: 0,
    materialCost: 0,
    firstPublishMaterialCost: 0,
    highQualityMaterialCost: 0,
    poorQualityMaterialCost: 0,
    lowEfficiencyMaterialCost: 0,
    improvableMaterialCost: 0
  };

  if (Array.isArray(content)) {
    content.forEach((item: any) => {
      // 确保数据结构匹配：item.advertiserInfo, item.current, item.last
      const advertiserInfo = item.advertiserInfo || {};
      const periodData = chartPeriod.value === "current" ? (item.current || {}) : (item.last || {});
      
      // 使用 advertiserInfo 里的 advertiserName 作为 X 轴
      const name = advertiserInfo.advertiserName || "--";
      advertiserNames.push(name);
      
      // 提取所有消耗数据（8个字段）
      const cost = periodData.cost || 0;
      const noGrantCost = periodData.noGrantCost || 0;
      const materialCost = periodData.materialCost || 0;
      const firstPublishMaterialCost = periodData.firstPublishMaterialCost || 0;
      const highQualityMaterialCost = periodData.highQualityMaterialCost || 0;
      const poorQualityMaterialCost = periodData.poorQualityMaterialCost || 0;
      const lowEfficiencyMaterialCost = periodData.lowEfficiencyMaterialCost || 0;
      const improvableMaterialCost = periodData.improvableMaterialCost || 0;
      
      costData.push(cost);
      noGrantCostData.push(noGrantCost);
      materialCostData.push(materialCost);
      firstPublishMaterialCostData.push(firstPublishMaterialCost);
      highQualityMaterialCostData.push(highQualityMaterialCost);
      poorQualityMaterialCostData.push(poorQualityMaterialCost);
      lowEfficiencyMaterialCostData.push(lowEfficiencyMaterialCost);
      improvableMaterialCostData.push(improvableMaterialCost);
      
      // 累加总和
      pageTotal.cost += cost;
      pageTotal.noGrantCost += noGrantCost;
      pageTotal.materialCost += materialCost;
      pageTotal.firstPublishMaterialCost += firstPublishMaterialCost;
      pageTotal.highQualityMaterialCost += highQualityMaterialCost;
      pageTotal.poorQualityMaterialCost += poorQualityMaterialCost;
      pageTotal.lowEfficiencyMaterialCost += lowEfficiencyMaterialCost;
      pageTotal.improvableMaterialCost += improvableMaterialCost;
    });
  }

  const periodLabel = chartPeriod.value === "current" ? "当前期" : "上期";

  // 系列名称到总计字段的映射
  const seriesTotalMap: Record<string, string> = {
    "总消耗": "cost",
    "非赠款消耗": "noGrantCost",
    "素材总消耗": "materialCost",
    "首发素材消耗": "firstPublishMaterialCost",
    "优质素材消耗": "highQualityMaterialCost",
    "低质素材消耗": "poorQualityMaterialCost",
    "低效素材消耗": "lowEfficiencyMaterialCost",
    "可提升素材消耗": "improvableMaterialCost"
  };

  return {
    title: {
      text: `广告主消耗统计（${periodLabel}）`,
      left: "center"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      },
      formatter: function (params: any) {
        let result = params[0].name + "<br/>";
        params.forEach(function (item: any) {
          const seriesName = item.seriesName;
          const totalField = seriesTotalMap[seriesName];
          if (totalField && pageTotal[totalField as keyof typeof pageTotal] !== undefined) {
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            // 处理 item.value 可能是字符串的情况
            let value = item.value;
            if (typeof value === "string") {
              value = parseFloat(value) || 0;
            } else {
              value = parseFloat(value) || 0;
            }
            // 计算百分比：当前值 / 当前页总和 * 100
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            result +=
              item.marker +
              seriesName +
              ": " +
              formatNumber(value) +
              " (" +
              percent +
              "%)<br/>";
          } else {
            // 如果没有映射，只显示原始值
            result +=
              item.marker +
              seriesName +
              ": " +
              formatNumber(item.value) +
              "<br/>";
          }
        });
        return result;
      }
    },
    legend: {
      data: [
        "总消耗",
        "非赠款消耗",
        "素材总消耗",
        "首发素材消耗",
        "优质素材消耗",
        "低质素材消耗",
        "低效素材消耗",
        "可提升素材消耗"
      ],
      top: 30,
      type: "scroll",
      orient: "horizontal"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "20%",
      containLabel: true
    },
    xAxis: [
      {
        type: "category",
        data: advertiserNames,
        axisLabel: {
          rotate: -45,
          interval: 0,
          textStyle: {
            fontSize: 12
          }
        }
      }
    ],
    yAxis: [
      {
        type: "value"
      }
    ],
    series: [
      {
        name: "总消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: costData,
        itemStyle: {
          color: "#409EFF"
        },
        label: {
          show: true,
          position: "top",
          distance: 5,
          formatter: function (params: any) {
            const totalField = seriesTotalMap["总消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            let value = params.value;
            if (typeof value === "string") {
              value = parseFloat(value) || 0;
            } else {
              value = Number(value) || 0;
            }
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 11,
          lineHeight: 14
        }
      },
      {
        name: "非赠款消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: noGrantCostData,
        itemStyle: {
          color: "#67C23A"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["非赠款消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            let value = params.value;
            if (typeof value === "string") {
              value = parseFloat(value) || 0;
            } else {
              value = Number(value) || 0;
            }
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      },
      {
        name: "素材总消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: materialCostData,
        itemStyle: {
          color: "#E6A23C"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["素材总消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            const value = parseFloat(params.value) || 0;
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      },
      {
        name: "首发素材消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: firstPublishMaterialCostData,
        itemStyle: {
          color: "#F56C6C"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["首发素材消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            const value = parseFloat(params.value) || 0;
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      },
      {
        name: "优质素材消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: highQualityMaterialCostData,
        itemStyle: {
          color: "#909399"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["优质素材消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            const value = parseFloat(params.value) || 0;
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      },
      {
        name: "低质素材消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: poorQualityMaterialCostData,
        itemStyle: {
          color: "#E4E7ED"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["低质素材消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            const value = parseFloat(params.value) || 0;
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      },
      {
        name: "低效素材消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: lowEfficiencyMaterialCostData,
        itemStyle: {
          color: "#C0C4CC"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["低效素材消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            const value = parseFloat(params.value) || 0;
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      },
      {
        name: "可提升素材消耗",
        type: "bar",
        emphasis: {
          focus: "series"
        },
        data: improvableMaterialCostData,
        itemStyle: {
          color: "#9C27B0"
        },
        label: {
          show: function (params: any) {
            const value = parseFloat(params.value) || 0;
            return value > 0;
          } as any,
          position: "inside",
          formatter: function (params: any) {
            const totalField = seriesTotalMap["可提升素材消耗"];
            const totalNum = pageTotal[totalField as keyof typeof pageTotal] || 0;
            const value = parseFloat(params.value) || 0;
            const percent = totalNum > 0
              ? ((value / totalNum) * 100).toFixed(2)
              : "0.00";
            if (value < 10) {
              return percent + "%";
            }
            return `${formatNumber(value)}\n${percent}%`;
          },
          color: "#333",
          fontSize: 10,
          lineHeight: 12
        }
      }
    ]
  } as ECOption;
});

// 视图切换处理
const handleViewChange = (value: string | number | boolean | undefined) => {
  const viewValue = String(value);
  if (viewValue === "chart") {
    getChartData();
  } else if (viewValue === "table") {
    // 切换到表格视图时，刷新表格数据和总计数据
    proTable.value?.getTableList();
    loadTotalData();
  }
};

// 共享搜索处理
const handleSearch = () => {
  if (viewType.value === "table") {
    // 表格视图：刷新表格数据和总计数据
    proTable.value?.getTableList();
    loadTotalData();
  } else if (viewType.value === "chart") {
    // 柱状图视图：刷新柱状图数据
    getChartData();
  }
};

// 共享重置处理
const handleReset = () => {
  initParam.dateRange = undefined;
  initParam.dt = undefined;
  initParam.advertiserId = undefined;
  initParam.advCompanyId = undefined;
  initParam.advCompanyName = undefined;
  // 重置后根据当前视图刷新数据
  handleSearch();
};


// 格式化数字显示
const formatNumber = (value: any) => {
  if (value === null || value === undefined || value === "") return "--";
  const num = Number(value);
  if (isNaN(num)) return "--";
  return num.toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// 计算差值并返回带颜色的渲染内容
const renderChange = (current: any, last: any) => {
  const currentNum = Number(current) || 0;
  const lastNum = Number(last) || 0;
  const diff = currentNum - lastNum;
  const diffFormatted = formatNumber(Math.abs(diff));
  const color = diff > 0 ? "#F56C6C" : diff < 0 ? "#67C23A" : "#333";
  const symbol = diff > 0 ? "+" : diff < 0 ? "-" : "";
  
  return (
    <div style="text-align: right;">
      <div>{formatNumber(current)} / {formatNumber(last)}</div>
      <div style={`font-size: 12px; color: ${color}; margin-top: 4px;`}>
        {diff !== 0 ? `${symbol}${diffFormatted}` : "--"}
      </div>
    </div>
  );
};

// 计算总计数据的差额信息
const getTotalDiff = (current: any, last: any) => {
  const currentNum = Number(current) || 0;
  const lastNum = Number(last) || 0;
  const diff = currentNum - lastNum;
  const diffFormatted = formatNumber(Math.abs(diff));
  const color = diff > 0 ? "#F56C6C" : diff < 0 ? "#67C23A" : "#333";
  const symbol = diff > 0 ? "+" : diff < 0 ? "-" : "";
  
  return {
    current: formatNumber(current),
    last: formatNumber(last),
    diff: diff !== 0 ? `${symbol}${diffFormatted}` : "--",
    color
  };
};

// 计算属性：所有总计数据的差额信息
const totalDiffData = computed(() => {
  const current = totalData.value.current || {};
  const last = totalData.value.last || {};
  
  return {
    cost: getTotalDiff(current.cost || 0, last.cost || 0),
    noGrantCost: getTotalDiff(current.noGrantCost || 0, last.noGrantCost || 0),
    materialCost: getTotalDiff(current.materialCost || 0, last.materialCost || 0),
    firstPublishMaterialCost: getTotalDiff(current.firstPublishMaterialCost || 0, last.firstPublishMaterialCost || 0),
    highQualityMaterialCost: getTotalDiff(current.highQualityMaterialCost || 0, last.highQualityMaterialCost || 0),
    poorQualityMaterialCost: getTotalDiff(current.poorQualityMaterialCost || 0, last.poorQualityMaterialCost || 0),
    lowEfficiencyMaterialCost: getTotalDiff(current.lowEfficiencyMaterialCost || 0, last.lowEfficiencyMaterialCost || 0),
    improvableMaterialCost: getTotalDiff(current.improvableMaterialCost || 0, last.improvableMaterialCost || 0)
  };
});

// 表格配置项（移除搜索配置，因为使用共享搜索表单）
const tableColumns = reactive<ColumnProps<any>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { 
    prop: "advertiserId", 
    label: "广告主ID", 
    width: 200,
    render: scope => {
      return (
        <div>
          <div>{scope.row?.advertiserId || "--"}</div>
          <div style="font-size: 12px; color: #999;">{scope.row?.advertiserName || "--"}</div>
        </div>
      );
    }
  },
  { 
    prop: "cost", 
    label: "总消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.cost, scope.row?.lastCost)
  },
  { 
    prop: "noGrantCost",
    label: "非赠款消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.noGrantCost, scope.row?.lastNoGrantCost)
  },
  { 
    prop: "materialCost", 
    label: "素材总消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.materialCost, scope.row?.lastMaterialCost)
  },
  { 
    prop: "firstPublishMaterialCost", 
    label: "首发素材消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.firstPublishMaterialCost, scope.row?.lastFirstPublishMaterialCost)
  },
  { 
    prop: "highQualityMaterialCost", 
    label: "优质素材消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.highQualityMaterialCost, scope.row?.lastHighQualityMaterialCost)
  },
  { 
    prop: "poorQualityMaterialCost", 
    label: "低质素材消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.poorQualityMaterialCost, scope.row?.lastPoorQualityMaterialCost)
  },
  { 
    prop: "lowEfficiencyMaterialCost", 
    label: "低效素材消耗（当前/上期）",
    width: 220,
    align: "right",
    render: scope => renderChange(scope.row?.lowEfficiencyMaterialCost, scope.row?.lastLowEfficiencyMaterialCost)
  },
  { 
    prop: "improvableMaterialCost", 
    label: "可提升素材消耗（当前/上期）",
    width: 240,
    align: "right",
    render: scope => renderChange(scope.row?.improvableMaterialCost, scope.row?.lastImprovableMaterialCost)
  },
]);
// 批量同步素材消耗
const batchDelete = async (selectedList: any[]) => {
  // if (!selectedList || selectedList.length === 0) {
  //   ElMessage.warning("请先选择要同步的数据");
  //   return;
  // }
  // 可以获取选中的广告主ID列表
  if(selectedList.length > 0) {
    advertiserId.value = [...new Set(selectedList.map(item => item.advertiserId).filter(Boolean))];
    console.log("广告主ID列表：", advertiserId.value);
  }
  const params = {
    title: "同步广告主消耗数据",
    isView: false,
    row: { advertiserId: advertiserId.value || [] },
    api: undefined,
    getTableList: proTable.value?.getTableList
  };
  synchronizationAdvertiserAccountCostDt.value?.acceptParams(params);
};

onMounted(async () => {
  // 初始化默认日期范围
  if (initParam.dateRange && initParam.dateRange !== DateRangeEnum.CUSTOM) {
    const dateRange = calculateDateRange(initParam.dateRange);
    if (dateRange) {
      initParam.dt = dateRange;
    }
  }
  // 如果初始视图是柱状图，加载数据
  if (viewType.value === "chart") {
    getChartData();
  } else if (viewType.value === "table") {
    // 如果初始视图是表格，加载总计数据
    // 注意：表格数据会在 ProTable 组件初始化时自动加载
    // 这里需要等待 ProTable 初始化完成后再加载总计数据
    setTimeout(() => {
      loadTotalData();
    }, 100);
  }
});
</script>

<style scoped lang="scss">
.header-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.view-switch {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.shared-search-form {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.chart-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.total-data-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.total-diff-content {
  text-align: left;

  .total-diff {
    font-size: 12px;
    margin-top: 4px;
  }
}
</style>
