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,
}: {
  api: (params: any) => Promise<any>;
  columns: TableColumnsType<any>;
  onSuccess: (data: any, params: any[]) => any[];
  onChange: (selectedRows: any[]) => void;
  defaultParams?: [params: any];
  value: any;
  disabled: boolean;
}) {
  const [open, setOpen] = React.useState(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"],
  });
  const dataRef = useRef<any[]>([]);

  const { loading, run } = useRequest(api, {
    defaultParams,
    onSuccess(data, params) {
      const result = onSuccess(data, params);
      setDataSource(result);
      dataRef.current = result;
    },
  });
  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 = () => {
    setDataSource(dataRef.current.filter((item) => item.name.includes(searchKey)))
  }

  const handleOk = () => {
    onChange(selectedRowRows);
    setOpen(false);
  };
  return (
    <>
      <Modal
        open={open}
        title="请选择"
        footer={
          <div>
            <Button className="m-r-8px" onClick={() => setOpen(false)}>
              取消
            </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}
        />
        <Table
          dataSource={dataSource}
          columns={columns}
          rowKey={"id"}
          rowSelection={{
            type: "radio",
            onChange: handleSlected,
          }}
          pagination={pagination}
          loading={loading}
          onChange={handleChange}
        />
      </Modal>
      <Select
        dropdownStyle={{ display: "none" }}
        placeholder="请选择"
        onClick={() => !disabled && setOpen(true)}
        value={value.label}
        disabled={disabled}
      />
    </>
  );
}
