/* eslint-disable eqeqeq */
/* eslint-disable import/order */
/* eslint-disable react/jsx-boolean-value */
/* eslint-disable indent */
import React, { useState, useEffect } from 'react';
import {
  Form,
  Modal,
  Input,
  Select,
  AutoComplete,
  Button,
  notification,
  message,
  Card,
  Space,
  Tooltip,
  Row,
  Col,
} from 'antd';
import styles from '../dimensionsConfig.less';

import { AddVectorData, GetProjectNames } from '@/services/webConfig/api';
import { CloseCircleOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible } = props;
  const [loading, setLoading] = useState(false);
  const [attributes, setAttributes] = useState([]);
  const [workList, setWorkList] = useState([]);
  const [allData, setAllData] = useState([]);
  const [gsIp, setGsIp] = useState([]);
  const [ports, setPorts] = useState('');
  const [projectNmme, setProjectNmme] = useState([]);
  const [loadingProject, setLoadingProject] = useState(false);
  const [form] = Form.useForm();
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        let attributesObj = {};
        if (obj.users) {
          obj.users.map(item => {
            attributesObj[item.nodeName] = item.nodeValue;
          });
        }

        // attributes.map((item, index) => {
        //   let key = obj[`key${index}`];
        //   attributesObj[`${key}`] = obj[`value${index}`];
        // });
        if (type === 'add') {
          let url = allData[obj.name].fileName
            ? `http://${obj.ip}:${obj.port}/${obj.projectName}/${obj.name}/${
                allData[obj.name].fileName
              }`
            : `http://${obj.ip}:${obj.port}/${obj.projectName}/${obj.name}`;
          let query = {
            type: obj.type,
            projectName: obj.projectName,
            name: obj.name,
            url,
            attributes: attributesObj || {},
            ip: obj.ip,
            port: obj.port,
          };
          AddVectorData(query)
            .then(res => {
              setLoading(false);
              if (res.msg === '') {
                form.resetFields();
                callBackSubmit();
                notification.success({
                  message: '提示',
                  duration: 3,
                  description: '新增成功',
                });
                handlelocalStorage('add', obj.ip, obj.projectName);
              } else {
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: res.msg,
                });
              }
            })
            .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);
        setAttributes([]);
        setProjectNmme([]);
        setWorkList([]);
        setPorts('');
        let localIps = ['192.168.12.97'];
        let port = localIps.includes(gsIp) ? '8083' : '8088';
        form.resetFields();
        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: 4,
    },
    wrapperCol: {
      span: 18,
    },
  };

  const selectIp = value => {
    let localIps = ['192.168.12.97'];
    let port = localIps.includes(value) ? '8083' : '8088';
    form.setFieldsValue({ port, serviceadress: value });
    setPorts(port);
  };
  // 获取项目名
  const getProject = () => {
    const obj = form.getFieldsValue();
    if (obj.ip && obj.port) {
      setLoadingProject(true);
      GetProjectNames({ ip: obj.ip, port: obj.port })
        .then(res => {
          setLoadingProject(false);
          if (res.msg === 'Ok') {
            if (res.data == '{}') {
              notification.info({
                message: '提示',
                duration: 3,
                description: '该地址下项目为空',
              });
            } else {
              notification.success({
                message: '提示',
                duration: 3,
                description: '获取成功',
              });
              let data = Object.values(JSON.parse(res.data));
              setProjectNmme(data);
              if (data.length) {
                form.setFieldsValue({ projectName: data[0] });
                selectProject(data[0]);
              }
            }
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: '获取失败',
            });
          }
        })
        .catch(e => {
          console.log('e', e);
        });
    } else {
      message.warning('未输入ip或port');
    }
  };
  const selectProject = value => {
    const obj = form.getFieldsValue();
    GetProjectNames({ ip: obj.ip, port: obj.port, projectname: value }).then(response => {
      let newArr = JSON.parse(response.data);
      let workArr = Object.keys(newArr.data);
      setAllData(newArr.data);
      if (workArr.length) {
        setWorkList(workArr);
        form.setFieldsValue({ name: workArr[0], type: newArr.data[workArr[0]].type });
      }
    });
  };
  const selectName = value => {
    form.setFieldsValue({ type: allData[value].type });
  };
  // const addExtra = () => {
  //   let attributesArr = [...attributes];
  //   attributesArr.push({});
  //   setAttributes(attributesArr);
  // };
  // const deleteExtr = index => {
  //   let attributesArr = [...attributes];
  //   attributesArr.splice(index, 1);
  //   setAttributes(attributesArr);
  // };
  const inputPort = e => {
    setPorts(e.target.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} style={{ marginBottom: '20px' }}>
          <Item label="IP" name="ip" rules={[{ required: true, message: '请选择ip地址' }]}>
            <AutoComplete placeholder="请输入IP" options={gsIp} onSelect={selectIp} />
          </Item>
          <Item label="端口" name="port" rules={[{ required: true, message: '请输入端口' }]}>
            <div className={styles.imgList}>
              <Input
                placeholder="请输入GIS服务器端口"
                allowClear
                value={ports}
                onChange={inputPort}
              />
            </div>
          </Item>
          <Item
            label="项目名"
            name="projectName"
            rules={[{ required: true, message: '请选择项目名' }]}
          >
            <Select onChange={selectProject} style={{ width: '379px' }}>
              {projectNmme.length
                ? projectNmme.map((item, index) => {
                    return (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    );
                  })
                : ''}
            </Select>
            <Button style={{ marginLeft: '0.5rem' }} onClick={getProject}>
              获取项目名
            </Button>
          </Item>
          <Item
            label="数据源名"
            name="name"
            rules={[{ required: true, message: '请选择数据源名' }]}
          >
            <Select onChange={selectName}>
              {workList.length
                ? workList.map((item, index) => {
                    return (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    );
                  })
                : ''}
            </Select>
          </Item>
          <Item
            label="数据类型"
            name="type"
            rules={[{ required: true, message: '请输入数据类型' }]}
          >
            <Input placeholder="请输入数据类型" allowClear disabled />
          </Item>
          {/* <Button
            size="small"
            style={{ width: '71%', marginLeft: '109px', lineHeight: '32px', height: '32px' }}
            onClick={() => {
              addExtra();
            }}
          >
            新增额外属性
          </Button> */}
          <div
            style={{
              maxHeight: '200px',
              overflowY: 'scroll',
              marginLeft: '66px',
              width: '88%',
            }}
          >
            <Form.List name="users">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, fieldKey, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }}>
                      <div style={{ display: 'flex', alignItems: 'middle' }}>
                        <Form.Item
                          {...restField}
                          name={[name, 'nodeName']}
                          label="键"
                          fieldKey={[fieldKey, 'frist']}
                        >
                          <Input
                            placeholder="请输入名称"
                            style={{ marginLeft: '2px', width: '224px' }}
                          />
                        </Form.Item>
                        <Form.Item
                          {...restField}
                          name={[name, 'nodeValue']}
                          label="值"
                          fieldKey={[fieldKey, 'last']}
                          style={{ marginLeft: '10px' }}
                        >
                          <Input
                            placeholder="请输入值"
                            style={{ marginLeft: '2px', width: '224px' }}
                          />
                        </Form.Item>
                        <Tooltip title="移除额外属性">
                          <MinusCircleOutlined
                            onClick={() => remove(name)}
                            style={{ marginLeft: '20px', marginTop: '11px', fontSize: '20px' }}
                          />
                        </Tooltip>
                      </div>
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                      style={{ width: '489px', marginLeft: '43px' }}
                    >
                      新增额外属性
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
            {/* {attributes.length
              ? attributes.map((item, index) => {
                  return (
                    <div key={index} className={styles.containerFileds}>
                      <Item
                        label="键"
                        name={`key${index}`}
                        style={{ width: '100%', marginTop: '24px' }}
                      >
                        <Input placeholder="" allowClear />
                      </Item>
                      <Item
                        label="值"
                        name={`value${index}`}
                        style={{ width: '100%', marginTop: '24px' }}
                      >
                        <Input placeholder="" allowClear />
                      </Item>
                      <CloseCircleOutlined
                        onClick={() => {
                          deleteExtr(index);
                        }}
                        style={{
                          fontSize: '16px',
                          color: 'red',
                          cursor: 'pointer',
                        }}
                      />
                    </div>
                  );
                })
              : ''} */}
          </div>
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;
