input.tsx 2.6 KB
import React, { useEffect, useState } from 'react';

import { Checkbox, Input, Tag } from 'antd';
import { ApartmentOutlined } from '@ant-design/icons';
/*
import './index.less';
*/
import PosSelectorDialog from './dialog';

export type QxPosSelectorProps = {
  onChange?: (data: any) => void;
  defaultValue?: any;
  disabled?: boolean;
  multiple?: boolean;
  readOnly?: boolean;
  name?: string;
  data?: []; //请求body参数
  request: any;
};

/**
 * 表单设计器(XRender)
 * @constructor
 */
const QxPosSelector: React.FC<QxPosSelectorProps> = (props) => {
  const [selectOrgs, setSelectOrgs] = useState([]);
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState<string | string[]>();

  useEffect(() => {
    setValue(props.defaultValue);
  }, []);

  // getUserList()
  const handleOk = (keys: [], data: []) => {
    let _value: [] | string = keys;
    if (!props.multiple && keys && keys.length > 0) {
      // @ts-ignore
      _value = keys[0];
    }
    setValue(_value);
    setSelectOrgs(data);
    setVisible(false);
    if (props.onChange) {
      props.onChange(_value);
    }
  };

  const handleCancel = () => {
    setVisible(false);
  };
  const handleRemove = (index: number) => {
    let _value: string | string[] = '';
    let _selected = [];
    if (props.multiple) {
      // @ts-ignore
      _value = [...value];
      _selected = [...selectOrgs];
      _value.splice(index, 1);
      _selected.splice(index, 1);
    }

    setValue(_value);
    setSelectOrgs(_selected);

    if (props.onChange) {
      props.onChange(_value);
    }
  };

  return (
    <>
      {props.name ? (
        props.multiple && typeof value !== 'string' ? (
          <Checkbox.Group name={props.name} value={value} style={{ display: 'none' }} />
        ) : (
          <Input style={{ display: 'none' }} value={value} />
        )
      ) : null}
      <div
        className={'qx-user-selector ant-input'}
        style={{ minHeight: '33px' }}
        onClick={() => setVisible(true)}
      >
        <ApartmentOutlined style={{ paddingRight: '5px', color: '#999' }} />
        {selectOrgs.map((org: { title: string; key: string }, index) => (
          <Tag closable color={'blue'} key={org.key} onClose={() => handleRemove(index)}>
            {org.title}
          </Tag>
        ))}
      </div>
      {props.readOnly ? null : (
        <PosSelectorDialog
          visible={visible}
          multiple={props.multiple}
          data={props.data}
          onOk={handleOk}
          request={props.request}
          onCancel={handleCancel}
        />
      )}
    </>
  );
};

export default QxPosSelector;