/* eslint-disable prefer-promise-reject-errors */
import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification } from 'antd';
import { AddConnString, EditConnString, SaveMainServer } from '@/services/database/api';

const { Item } = Form;
const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible, keepName } = props;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        if (type === 'add') {
          SaveMainServer({
            ...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();
    SaveMainServer({
      ...obj,
    })
      .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 => {};
  useEffect(() => {
    if (visible) {
      switch (type) {
        case 'add':
          if (keepName.indexOf('mainserver') == -1) {
            form.setFieldsValue({ name: 'mainserver' });
          }
          break;
        case 'edit':
          form.setFieldsValue({ ...formObj });
          break;
        default:
          break;
      }
    } else {
      form.resetFields();
    }
  }, [visible]);
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 19,
    },
  };
  return (
    <Modal
      title={`${type === 'add' ? '添加' : '编辑'}主站配置连接`}
      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}>
          {type === 'add' ? (
            <Item
              label="标签"
              name="name"
              rules={[
                { required: true, message: '请输入标签' },
                {
                  validator: (rule, value) => {
                    if (keepName.indexOf(form.getFieldValue().name) != -1) {
                      return Promise.reject('标签名已存在');
                    }
                    return Promise.resolve();
                  },
                },
                {
                  validator: (rule, value) => {
                    let aa = form.getFieldValue().name.substr(0, 1);
                    var regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。
                    if (regPos.test(aa)) {
                      return Promise.reject('标签名不能以数字开头');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="请输入标签" allowClear />
            </Item>
          ) : (
            <Item label="标签" name="name" rules={[{ required: true, message: '请输入标签' }]}>
              <Input placeholder="请输入标签" allowClear disabled />
            </Item>
          )}
          <Item
            label="Url地址"
            name="url"
            rules={[
              { required: true, message: '请输入url地址' },
              { type: 'url', message: '请输入完整url' },
            ]}
            style={{ width: '100%' }}
          >
            <Input placeholder={`如：${window.location.origin}`} />
          </Item>
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;
