input.tsx 14.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
import React, { useEffect, useState, useImperativeHandle, useRef, useMemo } from 'react';

import { Tag, Button, Popover } from 'antd';
import { UserAddOutlined } from '@ant-design/icons';
import './style.less';
import type { UserItem } from './dialog';
import UserSelectorDialog from './dialog';
import { searchUserByAllType, SearchUserAllData } from './service';
import _ from 'lodash';

export type QxUserSelectorProps = {
  cRef?: any;
  onChange?: (data: string | string[], users?: UserItem[]) => void;
  onMounted?: () => void;
  defaultValue?: any;
  disabled?: boolean;
  multiple?: boolean;
  max?: number;
  readOnly?: boolean;
  value?: string | string[];
  defaultData?: UserItem | UserItem[];
  params?: any; //请求body参数
  request: any;
};

type BaseUser = {
  id: string;
  name: string;
};

/**
 * 选人组件
 * @param props
 * @constructor
 */
const QxUserSelector: React.FC<QxUserSelectorProps> = (props) => {
  //弹框是否可见
  const [visible, setVisible] = useState(false);
  const [popVisible, setPopVisible] = useState(false);
  const [popWidth, setPopWidth] = useState(100);
  //常用联系人
  const [favorites, setFavorites] = useState([]);
  //模糊搜索到的人
  const [userList, setUserList] = useState(null);
  //已选择的人员信息
  const [selectUsers, setSelectUsers] = useState<BaseUser[]>([]);
  //存储人员信息,减少重复请求 {[id]:BaseUser}
  const [selectTmpUsersMap, setTmpUsersMap] = useState<Record<string, BaseUser>>({});

  const [value, setValue] = useState<string | string[]>();

  const qxUserSelectorInputRef = useRef<HTMLDivElement>();
  const inputRef = useRef<HTMLInputElement>();

  useEffect(() => {
    setValue(props.defaultValue);
    if (props?.onMounted) {
      props?.onMounted();
    }
  }, []);
  //console.log('QxUserSelector', props.value)

  useImperativeHandle(props.cRef, function () {
    return {
      // 暴露给父组件
      clear: () => {
        setSelectUsers([]);
        setValue(undefined);
      },
      /*//方法触发增加人
      addUsers: (users: BaseUser[]) => {
        const addIds: string[] = selectUsers.map(user => user.id);
        const waitUsers = users.filter((user) => {
          return user.id && !addIds.includes(user.id);
        });
        setSelectUsers([...selectUsers, ...waitUsers]);
      },*/
      //设置人员
      setUsers: (users: BaseUser[]) => {
        if (JSON.stringify(users) === JSON.stringify(selectUsers)) {
          return;
        }
        setSelectUsers(users);
        const ids = users.map((user) => user.id);
        if (JSON.stringify(ids) === JSON.stringify(value)) {
          return;
        }
        props.onChange(ids, users);
      },
    };
  });

  const userId = window.localStorage.getItem('userId');
  const handleFavorites = (data?: UserItem[]) => {
    //如果限制了选择范围,则不能选择常用联系人
    if (props?.params?.range) {
      return;
    }

    if (!userId) {
      return;
    }

    const userName = window.localStorage.getItem('userName');
    const cropCode = window.localStorage.getItem('corpCode');
    const favoritesStorage = window.localStorage.getItem(`${cropCode}_${userId}_favorites`);
    let _favoritesData = [];
    let ids = [];
    if (favoritesStorage) {
      _favoritesData = JSON.parse(favoritesStorage);
      ids = _favoritesData.map((item) => item?.data?.id);
    }
    if (data) {
      data.forEach((item) => {
        const index = ids.indexOf(item.id);
        if (index > -1) {
          const favoritesDatum = _favoritesData[index];
          favoritesDatum.count += 1;
          favoritesDatum.data = item;
          _favoritesData.splice(index, 1);
          _favoritesData.unshift(favoritesDatum);
        } else {
          _favoritesData.unshift({ count: 1, data: item });
        }
      });
    }

    if (_favoritesData.length === 0 && userId) {
      _favoritesData[0] = {
        count: 1,
        data: { id: userId, name: userName || '我自己' },
      };
    }
    if (_favoritesData.length > 0) {
      // _favoritesData.sort((a, b) => b.count - a.count);
      _favoritesData = _favoritesData.splice(0, 5);
    }

    window.localStorage.setItem(`${cropCode}_${userId}_favorites`, JSON.stringify(_favoritesData));
    setFavorites(_favoritesData.map((item) => item.data).filter((o) => o.name !== '系统管理员')); //  如果有重名过滤怎么办 TODO
  };

  //TODO 默认值待优化
  useEffect(() => {
    let _users: BaseUser[] = [];
    const _maps = {};
    let ids: string[];
    if (props.defaultData) {
      if (props.multiple && Array.isArray(props.defaultData)) {
        _users = props.defaultData;
        ids = [];
        props.defaultData.map((item: BaseUser) => {
          ids.push(item.id);
          _maps[item.id] = item;
        });
      } else if (Array.isArray(props.defaultData)) {
        _users = props.defaultData;
        ids = [];
        props.defaultData.map((item: BaseUser) => {
          ids.push(item.id);
          _maps[item.id] = item;
        });
      } else {
        // @ts-ignore
        _users = [props.defaultData];
        // @ts-ignore
        ids = props.defaultData.id;
      }
    }
    setSelectUsers(_users);
    setTmpUsersMap(_maps);
    if (ids && ids.length > 0 && !props.value && props.onChange) {
      props.onChange(ids, _users);
    }

    handleFavorites();
  }, [JSON.stringify(props.defaultData)]);

  useEffect(() => {
    setValue(props.value);
    if (!props.value) {
      setSelectUsers([]);
    }
  }, [props.value]);

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

    handleFavorites(data);

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

  const handleAdd = (user: UserItem) => {
    if ((value || []).indexOf(user?.id) > -1) {
      return;
    }
    let _value: string | string[] = '';
    let _selectUsers: UserItem[] = [];
    if (props.multiple) {
      if (props.max === 1) {
        _value = [user.id];
        _selectUsers = [user];
      } else {
        _value = value ? [...value, user.id] : [user.id];
        _selectUsers = [...selectUsers, user];
      }
    } else {
      _value = user.id;
      _selectUsers = [user];
    }
    setValue(_value);
    setSelectUsers(_selectUsers);

    handleFavorites([user]);

    if (props.onChange) {
      props.onChange(_value, _selectUsers);
    }
    //setPopVisible(false);

    //如果是单选,则直接关闭pop
    if (props.max === 1 || !props.multiple || typeof value === 'string') {
      setPopVisible(false);
    }
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleRemove = (index: number) => {
    let _value: string | string[] = '';
    let _selectUsers: UserItem[] = [];
    if (props.multiple && Array.isArray(value)) {
      _value = [...value];
      _selectUsers = [...selectUsers];
      _value.splice(index, 1);
      _selectUsers.splice(index, 1);
    }

    setValue(_value);
    setSelectUsers(_selectUsers);

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

  useEffect(() => {
    if (popVisible && qxUserSelectorInputRef?.current) {
      setPopWidth(qxUserSelectorInputRef?.current?.clientWidth);
    }
    if (!popVisible && inputRef?.current) {
      inputRef.current.value = '';
      setUserList(null);
    }
  }, [popVisible]);

  const handleSearch = _.debounce((_keywords: string | undefined) => {
    if (!_keywords) {
      setUserList(null);
      return;
    }
    const __keywords: string = _keywords.trim();
    if (!__keywords) {
      setUserList(null);
      return;
    }

    const params: SearchUserAllData = { pageSize: 5, keywords: __keywords };
    if (props?.params?.range) {
      params.range = props?.params?.range;
    }
    searchUserByAllType(props.request, params).then((res) => {
      setUserList(res?.list || []);
    });
  }, 500);

  const userDropContent = useMemo(() => {
    return (
      <div className={'qx-user-selector--input__drop'} style={{ width: popWidth + 'px' }}>
        <dl className={'qx-user-selector-pop-list'}>
          {userList ? (
            userList.length == 0 ? (
              <dd className={'qx-user-selector-pop-empty'}>没有匹配到任何结果</dd>
            ) : (
              <>
                <dt>您可能想找</dt>
                {userList.map((item) => {
                  return (
                    <dd
                      key={item.id}
                      onClick={() => handleAdd(item)}
                      className={(value || []).indexOf(item.id) > -1 ? 'disabled' : null}
                    >
                      {item?.name}
                      {item?.code ? (
                        <span className={'qx-user-selector-code'}>({item?.code})</span>
                      ) : null}
                    </dd>
                  );
                })}
              </>
            )
          ) : null}
          {favorites?.length > 0 ? (
            <>
              <dt>最近联系人</dt>
              {favorites.map((item) => {
                return (
                  <dd
                    key={item.id}
                    onClick={() => handleAdd(item)}
                    className={`text_over ${
                      (value || []).indexOf(item.id) > -1 ? 'disabled' : null
                    }`}
                  >
                    {item?.name}
                    {item?.code ? (
                      <span className={'qx-user-selector-code'}>({item?.code})</span>
                    ) : null}
                  </dd>
                );
              })}
            </>
          ) : null}
          <a
            className={'qx-user-selector-more ant-typography'}
            style={{ paddingLeft: 10 }}
            onClick={() => {
              setPopVisible(false);
              setVisible(true);
            }}
          >
            加载更多
          </a>
        </dl>
      </div>
    );
  }, [popWidth, favorites, props?.params, userList, value]);

  const handleKeyDown = (e) => {
    const { which } = e;
    // Remove value by `backspace`
    if (which === 8 && e.target.value === '') {
      if (Array.isArray(value) && value.length > 0) {
        const _value: string[] = [...value];
        let _selectUsers: UserItem[] = [];

        _selectUsers = [...selectUsers];

        _value.pop();
        _selectUsers.pop();

        setValue(_value);
        setSelectUsers(_selectUsers);

        if (props.onChange) {
          props.onChange(_value, _selectUsers);
        }
      } else if (!Array.isArray(value) && value) {
        setValue([]);
        setSelectUsers([]);

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

  return (
    <>
      <Popover
        content={userDropContent}
        placement={'bottom'}
        visible={
          ((props?.params?.range || !userId) && !userList) || props.readOnly ? false : popVisible
        }
        trigger={'click'}
        overlayClassName={'qx-user-selector--input__pop'}
        onVisibleChange={(v: boolean) => setPopVisible(v)}
      >
        <div
          className={
            'qx-user-selector--input ant-input' +
            `${props.readOnly ? ' qx-user-selector--readonly' : ''}`
          }
          style={{ minHeight: '32px' }}
          ref={qxUserSelectorInputRef}
          onClick={() => setPopVisible(true)}
        >
          <div
            className={
              'qx-user-selector--div ' + `${props?.readOnly ? '' : 'qx-user-selector-overflow'}`
            }
          >
            {selectUsers.map((user: { name: string; id: string }, index: number) => {
              if (!user.name) {
                return null;
              }
              return (
                <Tag
                  color={'blue'}
                  closable={!props.readOnly}
                  key={user.id}
                  onClose={() => handleRemove(index)}
                  style={{
                    maxWidth: `calc(100%)`,
                    height: '22px',
                  }}
                >
                  <span
                    style={{
                      display: 'inline-block',
                      maxWidth: `calc(100% - ${!props.readOnly ? 15 : 0}px)`,
                      textOverflow: 'ellipsis',
                      overflow: 'hidden',
                      height: 20,
                      lineHeight: '20px',
                    }}
                    title={user.name}
                  >
                    {user.name}
                  </span>
                </Tag>
              );
            })}
            {props.readOnly ? null : (
              <div className="qx-select-selection-search">
                <input
                  ref={inputRef}
                  type="text"
                  disabled={props.readOnly || props.disabled}
                  className={'qx-user-input__box'}
                  placeholder={'搜索'}
                  onKeyDown={(e) => handleKeyDown(e)}
                  onChange={(e) => {
                    handleSearch(e.target?.value);
                  }}
                  onFocus={() => {
                    setPopVisible(true);
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                  maxLength={20}
                />
                <Button
                  className={'qx-user-input__icon'}
                  size={'small'}
                  onClick={(e) => {
                    e.stopPropagation();
                    setPopVisible(false);
                    setVisible(true);
                  }}
                  type={'text'}
                  icon={<UserAddOutlined style={{ color: '#40A9FC' }} />}
                />
              </div>
            )}
          </div>
        </div>
      </Popover>
      {!props.readOnly ? (
        <UserSelectorDialog
          key={visible + ''}
          visible={visible}
          multiple={props.multiple}
          selectedData={selectUsers}
          params={props.params}
          request={props.request}
          onOk={handleOk}
          max={props.max}
          onCancel={handleCancel}
        />
      ) : null}
    </>
  );
};

export default QxUserSelector;