import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, AutoComplete, Button, notification } from 'antd';
import styles from '../SchemeConfig.less';

import { GetGISServerMapList, publisService } from '@/services/webConfig/api';

const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible, solutionNames } = props;
  const [loading, setLoading] = useState(false);
  const [workSpace, setWorkSpace] = useState('');
  const [serviceName, setServicename] = useState([
    {
      value: 'geoserver',
      item: 'geoserver',
    },
  ]);
  const [workList, setWorkList] = useState([]);
  const [gsIp, setGsIp] = useState([]);
  const [form] = Form.useForm();
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        if (type === 'add') {
          let query = {
            _version: 9999,
            gsIP: obj.serviceadress,
            gsPort: obj.port,
            gsAppName: obj.servicename,
            gsUser: obj.user,
            gsWorkspaceName: obj.workname,
            gsPwd: obj.password,
            serviceName: obj.name,
            solution: solutionNames,
          };
          publisService(query, { timeout: 120000 })
            .then(res => {
              setLoading(false);
              if (res.success) {
                form.resetFields();
                callBackSubmit();
                notification.success({
                  message: '提示',
                  duration: 3,
                  description: '新增成功',
                });
                setWorkList([]);
                handlelocalStorage('add', obj.serviceadress, obj.servicename);
              } else {
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: '新增失败',
                });
              }
            })
            .catch(err => {
              notification.error({
                message: '提示',
                duration: 3,
                description: '新增失败',
              });
              setLoading(false);
            });
        }
      }
    });
  };

  const onFinish = value => {};
  useEffect(() => {
    switch (type) {
      case 'add':
        let gsIp = [];
        let localStorageData = handlelocalStorage('get');
        if (localStorageData) {
          gsIp = localStorageData.map(item => ({
            value: item.gsIp,
            item: item.gsIp,
          }));
        }
        setGsIp(gsIp);
        let localIps = ['192.168.12.7', '192.168.19.100'];
        let port = localIps.includes(gsIp) ? 8080 : 8088;
        form.setFieldsValue({ servicename: serviceName[0].value, port, ...formObj });
        break;
      case 'edit':
        form.setFieldsValue({ ...formObj });
        break;
      default:
        break;
    }
  }, [visible]);

  // 存储到localstorage
  const handlelocalStorage = (type, gsIp, gisAppName) => {
    if (!localStorage) return null;
    let result = JSON.parse(localStorage.getItem('metaData'));
    if (type == 'get') {
      return result;
    }
    if (!result || !result.find(item => item.gsIp == gsIp)) {
      if (!result) result = [];
      result.push({
        gsIp,
        gisAppName: [
          {
            value: gisAppName,
            item: gisAppName,
          },
        ],
      });
      localStorage.setItem('metaData', JSON.stringify(result));
      return;
    }
    let data = result.find(item => item.gsIp == gsIp);
    let isHasGisAppName = data.gisAppName.find(item => item.value == gisAppName);
    if (isHasGisAppName) return;
    data.gisAppName.push({
      value: gisAppName,
      item: gisAppName,
    });
    localStorage.setItem('metaData', JSON.stringify(result));
  };

  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 18,
    },
  };

  // 选择工作空间
  const selectWorkspace = () => {
    let obj = form.getFieldsValue();
    form
      .validateFields(['serviceadress', 'port', 'servicename', 'user', 'password'])
      .then(validate => {
        if (validate) {
          let query = {
            GISServerIP: obj.serviceadress,
            GISServerPort: obj.port,
            gsAppName: obj.servicename,
            gsUser: obj.user,
            gsPwd: obj.password,
            isGeoServer: true,
            _version: 9999,
          };
          GetGISServerMapList(query).then(res => {
            if (Array.isArray(res.data)) {
              const defaultValue = res.data[0] || '';
              form.setFieldsValue({ name: defaultValue, workname: defaultValue });
              setWorkList(res.data);
              setWorkSpace(defaultValue);
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: '获取工作空间失败',
              });
            }
          });
        }
      });
  };
  // 选择工作空间
  const handleWorkspace = value => {
    form.setFieldsValue({
      workname: value,
      name: value,
    });
    setWorkSpace(value);
  };
  const selectIp = value => {
    let localIps = ['192.168.12.7', '192.168.19.100'];
    let port = localIps.includes(value) ? 8080 : 8088;
    form.setFieldsValue({ port, serviceadress: value });
  };
  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}
      forceRender={true}
      getContainer={false}
    >
      {visible && (
        <Form form={form} {...layout} onFinish={onFinish}>
          <Item
            label="GIS服务器地址"
            name="serviceadress"
            rules={[{ required: true, message: '请选择服务名' }]}
          >
            <AutoComplete placeholder="请输入GIS服务器地址" options={gsIp} onSelect={selectIp} />
          </Item>
          <Item
            label="GIS服务器端口"
            name="port"
            rules={[{ required: true, message: '请输入GIS服务器端口' }]}
          >
            <Input placeholder="请输入GIS服务器端口" allowClear />
          </Item>

          <Item
            label="GIS服务器名"
            name="servicename"
            rules={[{ required: true, message: '请输入GIS服务器名' }]}
          >
            <AutoComplete placeholder="Email" options={serviceName} />
          </Item>
          <Item
            label="用户名称"
            name="user"
            rules={[{ required: true, message: '请输入用户名称' }]}
          >
            <Input placeholder="请输入用户名称" allowClear />
          </Item>
          <Item
            label="用户密码"
            name="password"
            rules={[{ required: true, message: '请输入用户密码' }]}
          >
            <Input.Password placeholder="请输入用户密码" allowClear />
          </Item>
          <Item
            label="工作空间名称"
            name="workname"
            rules={[{ required: true, message: '请选择工作空间名称' }]}
          >
            <div className={styles.imgList}>
              <Select onChange={handleWorkspace} value={workSpace} style={{ width: '365px' }}>
                {workList.length
                  ? workList.map((item, index) => {
                      return (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      );
                    })
                  : ''}
              </Select>
              <Button
                style={{ marginLeft: '0.5rem' }}
                onClick={() => {
                  selectWorkspace();
                }}
              >
                选择工作空间
              </Button>
            </div>
          </Item>
          <Item
            label="服务名称"
            name="name"
            rules={[{ required: true, message: '请输入服务名称' }]}
          >
            <Input placeholder="请输入服务名称" allowClear />
          </Item>
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;
