import { CloseOutlined } from '@ant-design/icons';
import { Button, Col, Row, Space } from 'antd';
import { useMemo, useState } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import UserSelect from '.';
import { formatUserRender } from '../utils';

export interface UserSelectListProps {
  state?: 0 | 1;
  value?: any[];
  width?: number | string;
  onChange?: (v?: any[]) => void;
}

const UserSelectList = (props: UserSelectListProps) => {
  const { state, value: parentVal, width = '100%', onChange: parentChange } = props;

  const { formatMessage } = useIntl();

  const [selfValue, setSelfValue] = useState<any[]>(parentVal ?? []);

  // 受控判断
  const yxVal = parentVal === undefined ? selfValue : parentVal;

  const value = useMemo(() => {
    if (yxVal) {
      return Array.isArray(yxVal) ? yxVal : [yxVal];
    }
    return [];
  }, [yxVal]);

  const onChange = (v: any[]) => {
    parentChange?.(v);
    setSelfValue(v);
  };

  const onDel = (id: number) => {
    const newUsers = value.filter((item) => item.id !== id);
    onChange(newUsers);
  };

  const [userSelect, setUserSelect] = useState<any[]>([]);

  return (
    <Space direction={'vertical'} style={{ width }}>
      <Row>
        <Col span={20}>
          <UserSelect
            mode={'multiple'}
            state={state}
            value={userSelect}
            placeholder={formatMessage({ id: 'component.user.bind.data.input' })}
            onChange={setUserSelect}
          />
        </Col>
        <Col span={4}>
          <Button
            type={'primary'}
            disabled={(userSelect?.length ?? 0) <= 0}
            onClick={() => {
              const newUsers = userSelect?.reduce(
                (pre: any[], cur) => {
                  if (!pre.find((u: any) => u.id === cur.id)) {
                    pre.push(cur);
                  }
                  return pre;
                },
                [...value],
              );
              onChange(newUsers ?? []);
              setUserSelect([]);
            }}
          >
            <FormattedMessage id={'component.userSelectList.add'} />
          </Button>
        </Col>
      </Row>

      <div style={{ minHeight: 100 }}>
        <Space direction={'vertical'}>
          {value.map((item) => (
            <Space key={item.id}>
              {formatUserRender(item)}
              <CloseOutlined onClick={() => onDel(item.id)} />
            </Space>
          ))}
        </Space>

        {value.length === 0 && (
          <div style={{ color: '#999', marginLeft: 10 }}>
            <FormattedMessage id={'component.user.bind.data.empty'} />
          </div>
        )}
      </div>
    </Space>
  );
};

export default UserSelectList;
