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

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

  const commissionTypeMap: Record<number, { text: string; type: "success" | "warning" | "danger" | "info" | "primary" }> = {
    0: { text: "拉新奖励", type: "primary" },
    1: { text: "消费提成", type: "success" }
  };

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

  const columns: TableColumnList = [
    {
      label: "分销员名称",
      prop: "distributorName",
      minWidth: 120,
      formatter: ({ distributorName }) => distributorName || "-"
    },
    {
      label: "用户名称",
      prop: "userName",
      minWidth: 120,
      formatter: ({ userName }) => userName || "-"
    },
    {
      label: "佣金类型",
      prop: "commissionType",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item =
          commissionTypeMap[row.commissionType] || { text: "未知", type: "info" };
        return <el-tag type={item.type as any} size="small">{item.text}</el-tag>;
      }
    },
    {
      label: "佣金金额",
      prop: "amount",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        return row.amount ? (
          <span class="text-red-600 font-bold">¥{row.amount}</span>
        ) : (
          <span class="text-gray-400">-</span>
        );
      }
    },
    {
      label: "订单金额",
      prop: "orderAmount",
      minWidth: 100,
      formatter: ({ orderAmount }) =>
        orderAmount ? `¥${orderAmount}` : "-"
    },
    {
      label: "提成比例",
      prop: "rate",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        return row.rate !== undefined && row.rate !== null ? (
          <span>{row.rate}%</span>
        ) : (
          <span class="text-gray-400">-</span>
        );
      }
    },
    {
      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: "结算时间",
      prop: "settleTime",
      minWidth: 160,
      formatter: ({ settleTime }) =>
        settleTime ? dayjs(settleTime).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.commissionType !== undefined && form.commissionType !== null)
        searchParams.commissionType = form.commissionType;
      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 getCommissionList(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);
    }
  }

  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,
    commissionTypeMap,
    statusMap,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange
  };
}
