<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      row-key="materialId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" plain @click="batchDelete(scope.selectedList)"> 批量同步素材消耗 </el-button>
      </template>
      <!-- Expand -->
      <!-- <template #expand="scope">
          {{ scope.row }}
        </template> -->
      <!-- usernameHeader -->
      <!-- <template #usernameHeader="scope">
          <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
            {{ scope.column.label }}
          </el-button>
        </template> -->
      <!-- createTime -->
      <!-- <template #createTime="scope">
          <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template> -->
      <!-- 表格操作 -->
      <!-- <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
          <el-button type="primary" link :icon="Refresh" @click="resetPass(scope.row)">重置密码</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
        </template> -->
    </ProTable>
    <SyncMaterialConsumption ref="syncMaterialConsumption" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { ResMaterialCostList } from "@/api/modules/dataManage";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { getUserGender } from "@/api/modules/user";
import { genderType, materialMode, materialType, materialAnalysisType } from "@/utils/dict";
import { filterEnum } from "@/utils";

import { getMaterialCostList } from "@/api/modules/dataManage";
import SyncMaterialConsumption from "./components/synchronization.vue";
const syncMaterialConsumption = ref<any>();
// ProTable 实例
const proTable = ref<ProTableInstance>();

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

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 content && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    content: data?.content || [],
    total: Number(data?.total) || 0
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：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.dtStart = newParams.dt[0]);
  newParams.dt && (newParams.dtEnd = newParams.dt[1]);
  delete newParams.dt;
  return getMaterialCostList(newParams);
};

// 表格配置项
type MaterialCostRow = ResMaterialCostList & {
  analysisTypeList?: string[] | string;
};

const columns = reactive<ColumnProps<MaterialCostRow>[]>([
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "dt",
    label: "获取时间",
    width: 160,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "daterange", valueFormat: "YYYY-MM-DD" }
    }
  },
  {
    prop: "advertiserInfo.advertiserId",
    label: "广告主ID",
    search: { el: "input" },
    width: 200,
    render: scope => {
      return (
        <div>
          {scope.row?.advertiserInfo?.advertiserId}
          <div style="font-size: 12px; color: #999;">{scope.row.advertiserInfo.advertiserName}</div>
        </div>
      );
    }
  },
  // { prop: "advertiserInfo.advertiserName", label: "广告主名称", width: 160 },
  {
    prop: "advCompanyId",
    label: "广告主公司ID",
    search: { el: "input" },
    isShow: false
  },
  {
    prop: "advCompanyName",
    label: "广告主公司名称",
    search: { el: "input" },
    isShow: false
  },
  {
    prop: "materialId",
    label: "素材ID",
    width: 200,
    search: { el: "input" },
    render: scope => {
      return (
        <div>
          {scope.row?.materialId || "--"}
          <div style="font-size: 12px; color: #999;">{scope.row?.materialName || "--"}</div>
        </div>
      );
    }
  },
  // { prop: "materialName", label: "素材名称", width: 160 },
  {
    prop: "analysisTypeList",
    label: "素材建议",
    width: 200,
    render: scope => {
      const list = scope.row?.analysisTypeList as any;
      const values: any[] = Array.isArray(list) ? list : list ? [list] : [];
      if (values.length === 0) return "--";
      return (
        <div style="display: flex; flex-wrap: wrap; gap: 6px; justify-content: center;">
          {values.map(v => (
            <el-tag key={String(v)} size="small">
              {filterEnum(v, materialAnalysisType)}
            </el-tag>
          ))}
        </div>
      );
    }
  },
  { prop: "materialMode", label: "素材模式", width: 160, enum: materialMode },
  { prop: "materialType", label: "素材类型", width: 160, enum: materialType },
  { prop: "statCost", label: "消耗", width: 160 },
  { prop: "showCnt", label: "展示次数", width: 160 },
  { prop: "ctr", label: "点击率", width: 160 },
  { prop: "clickCnt", label: "点击次数", width: 160 },
  { prop: "ecpConvertRate", label: "转化率", width: 160 },
  { prop: "ecpConvertCnt", label: "转化次数", width: 160 },
  { prop: "ecpCpaPlatform", label: "转化成本", width: 160 },
  {
    prop: "createTime",
    label: "素材创建时间",
    width: 180,
    render: scope => {
      const v = scope.row?.createTime;
      if (!v) return "-";
      const d = dayjs(v);
      return d.isValid() ? d.format("YYYY-MM-DD HH:mm:ss") : String(v);
    }
  },
  { prop: "duration", label: "视频时长", width: 160 },
  { prop: "relatedAdCnt", label: "关联广告数量", width: 160 },
  { prop: "relatedCreativeCnt", label: "关联创意数量", width: 160 }
  // {
  //   prop: "username",
  //   label: "用户姓名",
  //   search: { el: "input", tooltip: "我是搜索提示" },
  //   render: scope => {
  //     return (
  //       <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
  //         {scope.row.username}
  //       </el-button>
  //     );
  //   }
  // },
  // {
  //   prop: "gender",
  //   label: "性别",
  //   // 字典数据（本地数据）
  //   enum: genderType,
  //   // 字典请求不带参数
  //   // enum: getUserGender,
  //   // 字典请求携带参数
  //   // enum: () => getUserGender({ id: 1 }),
  //   search: { el: "select", props: { filterable: true } },
  //   fieldNames: { label: "genderLabel", value: "genderValue" }
  // },
  // { prop: "idCard", label: "身份证号", search: { el: "input" } },
  // { prop: "email", label: "邮箱" },
  // { prop: "address", label: "居住地址" },
  // {
  //   prop: "createTime",
  //   label: "创建时间",
  //   width: 180,
  //   search: {
  //     el: "date-picker",
  //     span: 2,
  //     props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
  //   }
  // },
]);
// 批量同步素材消耗
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.advertiserInfo.advertiserId))];
  console.log("广告主ID列表：", advertiserId.value);
}
  const params = {
    title: "同步素材消耗",
    isView: false,
    row: { advertiserId: advertiserId.value || [] },
    api: undefined,
    getTableList: proTable.value?.getTableList
  };
  syncMaterialConsumption.value?.acceptParams(params);
};

onMounted(async () => {});
</script>
