import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification } from 'antd';
import { AddConnString, EditConnString } from '@/services/database/api';

const { Item } = Form;
const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible } = props;
  const [loading, setLoading] = useState(false);
  const [showReplicaSet, setShowReplicaSet] = useState(false);
  const [form] = Form.useForm();
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        if (type === 'add') {
          AddConnString({
            Type: 'mongodb',
            ...obj,
          })
            .then(res => {
              setLoading(false);
              if (res.code == 0) {
                form.resetFields();
                callBackSubmit();
                notification.success({
                  message: '提示',
                  duration: 3,
                  description: '新增成功',
                });
              } else {
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: res.msg,
                });
              }
            })
            .catch(err => {
              setLoading(false);
              console.error(err);
            });
        } else if (type === 'edit') {
          handleEdit();
        }
      }
    });
  };
  const handleEdit = () => {
    let obj = form.getFieldsValue();
    EditConnString({
      Type: 'mongodb',
      MongoDbType: 'mongodb',
      ...obj,
      oldName: formObj.name,
    })
      .then(res => {
        setLoading(false);
        if (res.code == 0) {
          form.resetFields();
          callBackSubmit();
          notification.success({
            message: '提示',
            duration: 3,
            description: res.message || '编辑成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.message || '编辑失败',
          });
        }
      })
      .catch(err => setLoading(false));
  };
  const onFinish = value => {};
  const handleSelect = e => {
    console.log(e);
    if (e == '单实例') {
      form.setFieldsValue({ port: 27017 });
    }
    if (e == '分片群') {
      form.setFieldsValue({ port: 30000 });
    }
    e === '复制集' ? setShowReplicaSet(true) : setShowReplicaSet(false);
  };
  useEffect(() => {
    switch (type) {
      case 'add':
        form.resetFields();
        break;
      case 'edit':
        console.log(formObj.type);
        formObj.type === '复制集' ? setShowReplicaSet(true) : setShowReplicaSet(false);
        form.setFieldsValue({ ...formObj });
        form.setFieldsValue({ MongoDbType: formObj.type });
        break;
      default:
        break;
    }
    return () => {
      form.getFieldsValue().type === '复制集' ? setShowReplicaSet(true) : setShowReplicaSet(false);
    };
  }, [visible]);
  useEffect(() => {}, [type === 'edit']);
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 19,
    },
  };
  const selectArr = [
    {
      key: '0',
      title: '单实例',
      value: '单实例',
    },
    {
      key: '1',
      title: '复制集',
      value: '复制集',
    },
    {
      key: '2',
      title: '分片群',
      value: '分片群',
    },
  ];
  return (
    <Modal
      title={`${type === 'add' ? '添加' : '编辑'}MongDB数据库配置连接`}
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
    >
      {visible && (
        <Form form={form} {...layout} onFinish={onFinish}>
          <Item
            label="实例类型"
            name="MongoDbType"
            rules={[{ required: true, message: '请选择实例类型' }]}
          >
            <Select onChange={e => handleSelect(e)}>
              {selectArr &&
                selectArr.map(item => (
                  <Option key={item.key} value={item.value}>
                    {item.title}
                  </Option>
                ))}
            </Select>
          </Item>
          <Item label="标签" name="name" rules={[{ required: true, message: '请输入标签' }]}>
            <Input placeholder="请输入标签" allowClear />
          </Item>
          <Item label="IP" name="ip" rules={[{ required: true, message: '请输入IP' }]}>
            <Input placeholder="请输入IP" allowClear />
          </Item>
          <Item label="端口" name="port" rules={[{ required: true, message: '请输入端口号' }]}>
            <Input placeholder="请输入端口号" allowClear />
          </Item>
          <Item
            label="数据库名"
            name="dbName"
            rules={[{ required: true, message: '请输入数据库名' }]}
          >
            <Input placeholder="请输入数据库名" allowClear />
          </Item>
          {showReplicaSet && (
            <Item
              label="复制集名称"
              name="replicaSet"
              rules={[{ required: true, message: '请输入复制集名称' }]}
            >
              <Input placeholder="请输入数据库名" allowClear />
            </Item>
          )}
          {/* <Item
            label="用户名"
            name="userName"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" allowClear />
          </Item>
          <Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input placeholder="请输入密码" allowClear />
          </Item> */}
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;