import React, { Fragment, useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Form, Input, InputNumber, Select } from '@easyv/antd';
import message from 'components/message';
import { getDatabases, testDatabaseConnect } from 'models/source';
import { objectValueTrim } from 'utils/utils';
import EasyvButton from 'components/EasyvButton';
import styles from './SourceEditModal.less';

const FormItem = Form.Item;
const Option = Select.Option;

interface SqlValue {
  database?: string;
  host?: string;
  user?: string;
  password?: string;
  port?: number | string;
  id?: number | string;
}

function SqlForm({
  type,
  value = {},
  dispatch,
  onPassword,
  isEdit = false,
}: {
  onPassword: Function;
  type: string;
  value?: SqlValue;
  dispatch: Function;
  isEdit: boolean;
}) {
  const [databaseList, setDataBaseList] = useState([]);
  const [database, setDatabase] = useState<string>('');
  const [_value, setValue] = useState<SqlValue>(value);
  const [loading, setLoading] = useState(false);
  const [testing, setTesting] = useState(false);

  useEffect(() => {
    if (value.database) {
      setDatabase(value.database);
    }
  }, [value.database]);
  const getDatabaseList = async () => {
    setLoading(true);
    const result = await dispatch(getDatabases(objectValueTrim({ ..._value, type })));
    setLoading(false);

    if (result) {
      message.success('获取成功');
      setDataBaseList(result);
    }
  };

  const testDataSourceConnection = async () => {
    setTesting(true);
    const param = objectValueTrim({ ..._value, database, type });
    const result = await dispatch(testDatabaseConnect(param));
    setTesting(false);

    if (result) {
      message.success('连接成功');
    }
  };
  const handleChange = (name) => (e) => {
    const value = e.target.value;
    setValue((prev) => ({ ...prev, [name]: value }));
  };

  const handleNumChange = (name) => (value) => {
    setValue((prev) => ({ ...prev, [name]: value }));
  };

  const getDatabaseDisabled =
    !_value.host || !_value.port || !_value.user || loading || (isEdit ? false : !_value.password);
  const testConnectDisabled = getDatabaseDisabled || !database || testing;

  return (
    <Fragment>
      <FormItem
        label="连接地址"
        name="host"
        rules={[{ required: true, message: '请输入连接地址!', whitespace: true }]}>
        <Input
          placeholder={
            type === 'mssql' ? '使用ip\\instance连接实例时，请勿填写端口号' : '请输入数据源连接地址'
          }
          onChange={handleChange('host')}
        />
      </FormItem>
      <FormItem
        label="端口"
        name="port"
        rules={[{ required: true, message: '请输入端口!', whitespace: true, type: 'number' }]}>
        <InputNumber
          width={'100%'}
          placeholder={type === 'mssql' ? '1433' : '请输入数据源端口'}
          onChange={handleNumChange('port')}
        />
      </FormItem>
      <FormItem
        label="用户名"
        name="user"
        rules={[{ required: true, message: '请输入用户名!', whitespace: true }]}>
        <Input onChange={handleChange('user')} placeholder="请输入数据源用户名" />
      </FormItem>
      <FormItem
        label="密码"
        name="password"
        rules={[{ required: isEdit ? false : true, message: '请输入密码!', whitespace: true }]}>
        <Input
          type="password"
          onFocus={(e: any) => {
            onPassword?.(e);
          }}
          onBlur={(e: any) => {
            onPassword?.(e);
          }}
          placeholder="请输入数据源密码"
          onChange={handleChange('password')}
        />
      </FormItem>

      <FormItem label="数据库名" style={{ marginBottom: 7 }}>
        <div style={{ display: 'flex' }}>
          <EasyvButton
            theme="default"
            disabled={getDatabaseDisabled}
            style={{ marginRight: 15 }}
            onClick={getDatabaseList}>
            {loading ? '正在获取' : '获取数据库列表'}
          </EasyvButton>
          <FormItem
            style={{ marginBottom: 0 }}
            name="database"
            rules={[{ required: true, message: '请选择数据库' }]}>
            <Select
              dropdownClassName={styles.selectStyle}
              placeholder="请选择数据库"
              style={{ width: 165 }}
              onChange={(value: string) => setDatabase(value)}>
              {databaseList.map((item) => {
                return (
                  <Option key={item} value={item}>
                    {item}
                  </Option>
                );
              })}
            </Select>
          </FormItem>
        </div>
      </FormItem>
      <FormItem colon={false} label="  ">
        <EasyvButton
          theme="default"
          disabled={testConnectDisabled}
          style={{ width: 114 }}
          onClick={testDataSourceConnection}>
          {testing ? '正在连接' : '测试连接'}
        </EasyvButton>
      </FormItem>
    </Fragment>
  );
}

export default connect()(SqlForm);
