import {
  Input,
  Modal,
  Table,
  TableColumnsType,
  TablePaginationConfig,
  Button,
  Select,
} from "antd";
import React, { useRef, useState } from "react";
import { useRequest } from "ahooks";
import { SearchOutlined } from "@ant-design/icons";

export default function SelectModal({
  api,
  columns,
  onSuccess,
  onChange,
  defaultParams,
  value,
  disabled,
  labelKey = "name",
  valueKey = "id",
  multiple,
  trigger,
  defaultOpen,
  onClose,
}: {
  api: (params: any) => Promise<any>;
  columns: TableColumnsType<any>;
  onSuccess: (data: any, params: any[]) => any[];
  onChange?: (data: any) => void;
  defaultParams?: [params: any];
  value?: any;
  disabled?: boolean;
  labelKey?: string;
  valueKey?: string;
  multiple?: boolean;
  trigger?: React.ReactNode;
  defaultOpen?: boolean;
  onClose?: () => void;
}) {
  const [open, setOpen] = React.useState(defaultOpen ?? false);
  const [searchKey, setSearchKey] = useState("");
  const [selectedRowRows, setSelectedRowRows] = React.useState<any[]>([]);
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    pageSizeOptions: ["10", "20", "30", "40"],
    total: 0,
  });
  const dataRef = useRef<any[]>([]);

  // 获取数据
  const { loading, run } = useRequest(api, {
    defaultParams,
    debounceWait: 500,
    onSuccess(data, params) {
      const result = onSuccess(data, params);
      setDataSource(result);
      dataRef.current = result;
      setPagination((state) => ({
        ...state,
        total: data?.result.totalCount || result.length,
      }));
    },
  });

  // 选中处理
  const handleSlected = (_keys: React.Key[], rows: any[]) => {
    setSelectedRowRows(rows);
  };

  // 分页处理
  const handleChange = (pagination: TablePaginationConfig) => {
    setPagination(pagination);
    // if (defaultParams) {
    //   run({
    //     currentPage: pagination.current,
    //     pageSize: pagination.pageSize,
    //   });
    // }
  };

  // 搜索
  const handleSearch = () => {
    // setPagination({
    //   current: 1,
    //   pageSize: pagination.pageSize,
    //   total: 0,
    // });
    // run({
    //   currentPage: 1,
    //   pageSize: pagination.pageSize,
    //   filters: [
    //     {
    //       name: labelKey || "name",
    //       value: searchKey,
    //     },
    //   ],
    // });
    setDataSource(
      dataRef.current.filter((item) => item[labelKey].includes(searchKey))
    );
  };

  const handleOk = () => {
    const values = selectedRowRows.map((item) => item[valueKey || "id"]);
    onChange?.(multiple ? values : values?.[0]);
    setOpen(false);
  };
  // 打开模态框
  const handleOpen = () => {
    if (disabled) return;

    setOpen(true);
    run({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  // 关闭模态框
  const handleClose = () => { 
    setOpen(false);
    onClose?.();
  };

  return (
    <>
      <Modal
        open={open}
        title="请选择"
        footer={
          <div>
            <Button className="m-r-8px" onClick={handleClose}>
              取消
            </Button>
            <Button type="primary" onClick={handleOk}>
              确定
            </Button>
          </div>
        }
        closable={false}
      >
        <Input
          suffix={<SearchOutlined />}
          placeholder="关键字搜索"
          value={searchKey}
          onChange={(e) => setSearchKey(e.target.value)}
          onBlur={handleSearch}
          onPressEnter={handleSearch}
          className="mb-8px"
        />
        <Table
          dataSource={dataSource}
          columns={columns}
          rowKey={"id"}
          rowSelection={{
            type: multiple ? "checkbox" : "radio",
            onChange: handleSlected,
          }}
          scroll={{
            y: 300,
          }}
          pagination={{
            ...pagination,
          }}
          loading={loading}
          onChange={handleChange}
        />
      </Modal>
      {/* 触发器 */}
      {trigger ? (
        <span onClick={handleOpen}>{trigger}</span>
      ) : (
        <Select
          options={dataSource.map((item: any) => ({
            label: item[labelKey],
            value: item[valueKey],
          }))}
          styles={{
            popup: {
              root: { display: "none" },
            },
          }}
          placeholder="请选择"
          onClick={handleOpen}
          mode={multiple ? "multiple" : undefined}
          value={value}
          disabled={disabled}
        />
      )}
    </>
  );
}
