// utils/tableConfigFactory.tsx
import React from "react";
import { ProColumns } from "@ant-design/pro-components";
import { Tag } from "antd";
import { history, useIntl } from "@umijs/max";
import { ICONS, IconType } from "@/constants/antd/icons";
import {
  TableAction,
  ToolbarAction,
} from "@/components/EnhancedProTable/types";

/**
 * 创建操作配置的辅助函数
 */
const createAction = <T extends { id: number }>(
  key: string,
  label: string,
  iconType: IconType,
  onClick: (record: T) => void,
  options: Partial<TableAction<T>> = {}
): TableAction<T> => ({
  key,
  label,
  // icon: ICONS[iconType],
  onClick,
  ...options,
});

/**
 * 创建工具栏操作的辅助函数
 */
const createToolbarAction = (
  key: string,
  label: string,
  iconType: IconType,
  onClick: (selectedKeys: React.Key[], selectedRows: any[]) => void,
  options: Partial<ToolbarAction> = {}
): ToolbarAction => ({
  key,
  label,
  // icon: ICONS[iconType],
  onClick,
  ...options,
});

/**
 * 通用列配置工厂
 */
export const createCommonColumns = <T extends Record<string, any>>(): Partial<
  ProColumns<T>
>[] => [
  {
    title: "创建时间",
    dataIndex: "created_at",
    valueType: "dateTime",
    sorter: true,
    hideInSearch: true,
    width: 180,
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    valueType: "dateTime",
    hideInSearch: true,
    hideInTable: true,
    width: 180,
  },
  {
    title: "状态",
    dataIndex: "status",
    valueType: "select",
    valueEnum: {
      active: { text: "启用", status: "Success" },
      inactive: { text: "禁用", status: "Error" },
      pending: { text: "待审核", status: "Processing" },
    },
  },
];

/**
 * 通用操作配置工厂
 */
export const createCommonActions = <T extends { id: number }>(handlers: {
  onEdit?: (record: T) => void;
  onDelete?: (record: T) => void;
  onView?: (record: T) => void;
  onCopy?: (record: T) => void;
}): TableAction<T>[] => {
  const actions: TableAction<T>[] = [];

  if (handlers.onView) {
    actions.push(createAction("view", "查看", "view", handlers.onView));
  }

  if (handlers.onEdit) {
    actions.push(
      createAction("edit", "编辑", "edit", handlers.onEdit, {
        permission: "edit",
      })
    );
  }

  if (handlers.onCopy) {
    actions.push(
      createAction("copy", "复制", "copy", handlers.onCopy, {
        permission: "copy",
      })
    );
  }

  if (handlers.onDelete) {
    actions.push(
      createAction("delete", "删除", "delete", handlers.onDelete, {
        danger: true,
        permission: "delete",
      })
    );
  }

  return actions;
};

/**
 * 通用工具栏操作工厂
 */
export const createCommonToolbarActions = (handlers: {
  onAdd?: () => void;
  onExport?: (selectedRows: any[]) => void;
  onBatchDelete?: (selectedKeys: React.Key[]) => void;
  onImport?: () => void;
}): ToolbarAction[] => {
  const actions: ToolbarAction[] = [];
  if (handlers.onAdd) {
    actions.push(
      createToolbarAction(
        "add",
        useIntl().formatMessage({ id: "pages.searchTable.new" }),
        "add",
        handlers.onAdd,
        {
          type: "primary",
          permission: "add",
        }
      )
    );
  }

  if (handlers.onImport) {
    actions.push(
      createToolbarAction("import", "导入", "upload", handlers.onImport, {
        permission: "import",
      })
    );
  }

  if (handlers.onExport) {
    actions.push(
      createToolbarAction(
        "export",
        "导出",
        "export",
        (_, selectedRows) => handlers.onExport!(selectedRows),
        {
          needSelection: true,
        }
      )
    );
  }

  if (handlers.onBatchDelete) {
    actions.push(
      createToolbarAction(
        "batchDelete",
        "批量删除",
        "delete",
        (selectedKeys) => handlers.onBatchDelete!(selectedKeys),
        {
          danger: true,
          needSelection: true,
          permission: "delete",
        }
      )
    );
  }

  return actions;
};

/**
 * 用户表格配置
 */
export const createUserTableConfig = () => {
  const columns: ProColumns<any>[] = [
    {
      title: "头像",
      dataIndex: "avatar",
      valueType: "avatar",
      hideInSearch: true,
      width: 64,
    },
    {
      title: "用户名",
      dataIndex: "username",
      copyable: true,
      ellipsis: true,
      formItemProps: {
        rules: [
          { required: true, message: "请输入用户名" },
          { min: 2, max: 20, message: "用户名长度在 2 到 20 个字符" },
        ],
      },
    },
    {
      title: "邮箱",
      dataIndex: "email",
      copyable: true,
      formItemProps: {
        rules: [
          { required: true, message: "请输入邮箱" },
          { type: "email", message: "请输入正确的邮箱格式" },
        ],
      },
    },
    {
      title: "手机号",
      dataIndex: "phone",
      copyable: true,
      hideInTable: true,
    },
    {
      title: "角色",
      dataIndex: "roles",
      hideInSearch: true,
      render: (_, record) => (
        <>
          {record.roles?.map((role: string) => (
            <Tag key={role} color="blue">
              {role}
            </Tag>
          ))}
        </>
      ),
    },
    ...createCommonColumns(),
  ];

  return { columns };
};

/**
 * 订单表格配置
 */
export const createOrderTableConfig = () => {
  const columns: ProColumns<any>[] = [
    {
      title: "订单号",
      dataIndex: "order_no",
      copyable: true,
      ellipsis: true,
    },
    {
      title: "客户名称",
      dataIndex: "customer_name",
      ellipsis: true,
    },
    {
      title: "订单金额",
      dataIndex: "amount",
      valueType: "money",
      sorter: true,
    },
    {
      title: "订单状态",
      dataIndex: "status",
      valueType: "select",
      valueEnum: {
        pending: { text: "待付款", status: "Warning" },
        paid: { text: "已付款", status: "Processing" },
        shipped: { text: "已发货", status: "Success" },
        completed: { text: "已完成", status: "Success" },
        cancelled: { text: "已取消", status: "Error" },
      },
    },
    ...createCommonColumns(),
  ];

  return { columns };
};
