import React, { useState } from 'react';
import { Input, Button } from '@easyv/antd';
import message from 'components/message';
import styles from './SynchronizationModal.less';
import { postTemplatePassword } from 'services/template';
import { connect } from 'react-redux';

// eslint-disable-next-line @typescript-eslint/ban-types
function Synchronous({ onAsyncScreens, groupId }: { onAsyncScreens?: Function; groupId?: number }) {
  const [Key, setKey] = useState<string>('');
  const [errorMsg, setErrorMsg] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);

  const onAsync = () => {
    if (!Key) {
      return false;
    }
    setLoading(true);
    const param = { key: Key, type: 'screen' };
    const isApp = /\/app/.test(window.location.pathname);
    if (!isApp && groupId && groupId > 0) {
      // 终端交互模块没有分组
      param['groupId'] = groupId;
    } else if (isApp) {
      param.type = 'mobile';
    }
    postTemplatePassword(param, (error) => {
      setErrorMsg(error.message);
      setLoading(false);
    }).then((res) => {
      if (res) {
        setErrorMsg(``);
        message.success('同步成功');
        onAsyncScreens && onAsyncScreens();
      }
      setLoading(false);
    });
  };
  return (
    <div style={{ marginTop: '-20px' }}>
      <p className={styles.describe}>输入动态口令进行同步应用，口令只能使用一次</p>
      <div className={styles.sync}>
        <Input
          autoFocus
          onChange={(value: React.ChangeEvent<HTMLInputElement>) => setKey(value.target.value)}
          placeholder="输入动态口令"
          onPressEnter={onAsync}></Input>
        <Button loading={loading} onClick={onAsync} type="primary" style={{ marginLeft: '14px', borderRadius: 2 }}>
          同步
        </Button>
      </div>
      {errorMsg && <p style={{ color: '#FF5F5C', lineHeight: '18px', marginTop: 4 }}>{errorMsg}</p>}
    </div>
  );
}

const mapStateToProps = ({ groups }) => {
  return {
    groupId: groups.current
  };
};

// export default Synchronous;
export default connect(mapStateToProps, null)(Synchronous);
