<script setup lang="ts">
import { ref, onMounted, reactive, h } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  getReportList,
  generateReport,
  exportReport
} from "@/api/distribution";
import type { PaginationProps } from "@pureadmin/table";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange
} from "@/utils/paginationHelper";
import { message } from "@/utils/message";
import Refresh from "~icons/ep/refresh";

defineOptions({
  name: "DistributionReport"
});

const loading = ref(false);
const dataList = ref([]);
const pagination = reactive<PaginationProps>(initPagination());
const selectedMonth = ref("");

const columns: TableColumnList = [
  {
    label: "分销员名称",
    prop: "distributorName",
    minWidth: 120,
    formatter: ({ distributorName }) => distributorName || "-"
  },
  {
    label: "月份",
    prop: "yearMonth",
    minWidth: 100,
    formatter: ({ yearMonth }) => yearMonth || "-"
  },
  {
    label: "总拉新数",
    prop: "totalReferrals",
    minWidth: 90,
    formatter: ({ totalReferrals }) => totalReferrals ?? "-"
  },
  {
    label: "有效用户数",
    prop: "validReferrals",
    minWidth: 90,
    formatter: ({ validReferrals }) => validReferrals ?? "-"
  },
  {
    label: "待确认数",
    prop: "pendingReferrals",
    minWidth: 90,
    formatter: ({ pendingReferrals }) => pendingReferrals ?? "-"
  },
  {
    label: "已过期数",
    prop: "expiredReferrals",
    minWidth: 90,
    formatter: ({ expiredReferrals }) => expiredReferrals ?? "-"
  },
  {
    label: "总佣金(¥)",
    prop: "totalCommission",
    minWidth: 110,
    cellRenderer: ({ row }) => {
      return row.totalCommission !== undefined &&
        row.totalCommission !== null
        ? h("span", { class: "text-red-600 font-bold" }, `¥${Number(row.totalCommission).toFixed(2)}`)
        : h("span", { class: "text-gray-400" }, "-");
    }
  },
  {
    label: "已结算佣金(¥)",
    prop: "settledCommission",
    minWidth: 120,
    cellRenderer: ({ row }) => {
      return row.settledCommission !== undefined &&
        row.settledCommission !== null
        ? h("span", {}, `¥${Number(row.settledCommission).toFixed(2)}`)
        : h("span", { class: "text-gray-400" }, "-");
    }
  },
  {
    label: "待结算佣金(¥)",
    prop: "pendingCommission",
    minWidth: 120,
    cellRenderer: ({ row }) => {
      return row.pendingCommission !== undefined &&
        row.pendingCommission !== null
        ? h("span", {}, `¥${Number(row.pendingCommission).toFixed(2)}`)
        : h("span", { class: "text-gray-400" }, "-");
    }
  }
];

async function onSearch() {
  loading.value = true;
  try {
    const searchParams: any = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    if (selectedMonth.value) {
      searchParams.yearMonth = selectedMonth.value;
    }
    const { data } = await getReportList(searchParams);
    if (data) {
      dataList.value = data.list || [];
      pagination.total = Number(data.total) || 0;
    }
  } catch (error) {
    console.error("获取月度报表列表失败:", error);
    dataList.value = [];
    pagination.total = 0;
  } finally {
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
}

async function handleGenerate() {
  if (!selectedMonth.value) {
    message("请先选择月份", { type: "warning" });
    return;
  }
  try {
    await generateReport(selectedMonth.value);
    message("报表生成成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.error("生成报表失败:", error);
    message("生成报表失败", { type: "error" });
  }
}

async function handleExport() {
  if (!selectedMonth.value) {
    message("请先选择月份", { type: "warning" });
    return;
  }
  try {
    const res = await exportReport(selectedMonth.value);
    const blob = new Blob([res as any], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `分销月度报表_${selectedMonth.value}.xlsx`;
    link.click();
    window.URL.revokeObjectURL(url);
    message("导出成功", { type: "success" });
  } catch (error) {
    console.error("导出报表失败:", error);
    message("导出报表失败", { type: "error" });
  }
}

function handleSizeChange(val: number) {
  handlePageSizeChange(val, pagination, onSearch);
}

function handleCurrentChange(val: number) {
  handleCurrentPageChange(val, pagination, onSearch);
}

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

<template>
  <div class="main">
    <!-- 顶部操作栏 -->
    <div class="search-form bg-bg_color w-full pl-8 pt-[12px] pb-[12px] overflow-auto">
      <el-form :inline="true">
        <el-form-item label="选择月份：">
          <el-date-picker
            v-model="selectedMonth"
            type="month"
            format="YYYY-MM"
            value-format="YYYY-MM"
            placeholder="请选择月份"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleGenerate"
          >
            生成报表
          </el-button>
          <el-button @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <PureTableBar
      title="月度报表"
      :columns="columns"
      @refresh="onSearch"
    >
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          row-key="id"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          align-whole="center"
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        />
      </template>
    </PureTableBar>
  </div>
</template>

<style lang="scss" scoped>
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
