import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getReferralList } from "@/api/distribution";
import type { PaginationProps } from "@pureadmin/table";
import { onMounted, reactive, ref } from "vue";
import type { ReferralQuery } from "../../utils/types";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange,
  resetPagination
} from "@/utils/paginationHelper";

export function useReferral() {
  const form = reactive<ReferralQuery>({
    distributorId: undefined,
    userId: undefined,
    status: undefined,
    startDate: "",
    endDate: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>(initPagination());

  const statusMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
    0: { text: "待生效", type: "warning" },
    1: { text: "已生效", type: "success" },
    2: { text: "已失效", type: "danger" }
  };

  const columns: TableColumnList = [
    {
      label: "分销员名称",
      prop: "distributorName",
      minWidth: 120,
      formatter: ({ distributorName }) => distributorName || "-"
    },
    {
      label: "用户名称",
      prop: "userName",
      minWidth: 120,
      formatter: ({ userName }) => userName || "-"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type as any} size="small">{item.text}</el-tag>;
      }
    },
    {
      label: "首单ID",
      prop: "firstOrderId",
      minWidth: 100,
      formatter: ({ firstOrderId }) => firstOrderId || "-"
    },
    {
      label: "首单金额",
      prop: "firstOrderAmount",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        return row.firstOrderAmount ? (
          <span class="text-red-600 font-bold">¥{row.firstOrderAmount}</span>
        ) : (
          <span class="text-gray-400">-</span>
        );
      }
    },
    {
      label: "首单时间",
      prop: "firstOrderTime",
      minWidth: 160,
      formatter: ({ firstOrderTime }) =>
        firstOrderTime
          ? dayjs(firstOrderTime).format("YYYY-MM-DD HH:mm:ss")
          : "-"
    },
    {
      label: "生效时间",
      prop: "effectiveTime",
      minWidth: 160,
      formatter: ({ effectiveTime }) =>
        effectiveTime
          ? dayjs(effectiveTime).format("YYYY-MM-DD HH:mm:ss")
          : "-"
    },
    {
      label: "失效时间",
      prop: "expireTime",
      minWidth: 160,
      formatter: ({ expireTime }) =>
        expireTime
          ? dayjs(expireTime).format("YYYY-MM-DD HH:mm:ss")
          : "-"
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime
          ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
          : "-"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };

      if (form.distributorId) searchParams.distributorId = form.distributorId;
      if (form.userId) searchParams.userId = form.userId;
      if (form.status !== undefined && form.status !== null)
        searchParams.status = form.status;
      if (form.startDate) searchParams.startDate = form.startDate;
      if (form.endDate) searchParams.endDate = form.endDate;

      const { data } = await getReferralList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = data.total || 0;
      }
    } catch (error) {
      console.error("获取推荐记录列表失败:", error);
      dataList.value = [];
      pagination.total = 0;
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  };

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

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

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    statusMap,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange
  };
}
