/* eslint-disable prefer-destructuring */
/* eslint-disable camelcase */
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable no-else-return */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable indent */
/* eslint-disable react/jsx-boolean-value */
/* eslint-disable no-case-declarations */
/* eslint-disable no-shadow */
import React, { useState, useEffect } from 'react';
import {
  Form,
  Modal,
  Input,
  Select,
  notification,
  Slider,
  InputNumber,
  Row,
  Col,
  Image,
  Radio,
  Button,
  Switch,
  Empty,
  TreeSelect,
} from 'antd';
import styles from '../SchemeConfig.less';

import classnames from 'classnames';
import {
  SetServiceConfig,
  GetCustomBaseMapList,
  GetGridSetList,
  GetCustomBaseMapByName,
} from '@/services/webConfig/api';

const { Item } = Form;
const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible, name, onCancel } = props;
  const [loading, setLoading] = useState(false);
  const [alpha, setAlpha] = useState(1);
  const [advanced, setAdvanced] = useState(0);
  const [spaceData, setSpaceData] = useState([]);
  const [keyData, setKeyData] = useState([]);
  const [data, setData] = useState([]);
  const [areaData, setAreaData] = useState([]);
  const [o, setO] = useState('');
  const [r, setR] = useState('');
  const [current, setCurrent] = useState(false);
  const [form] = Form.useForm();

  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        let arr = {};
        // 连点
        if (obj.servicename) {
          arr = {
            servicename: obj.servicename,
            terminalType: 'base',
            isBaseMap: true,
            jsonCfg: JSON.stringify({
              alpha,
              label: obj.label,
              url: obj.url,
              taggingUrl: obj.taggingUrl,
              icon: obj.icon,
              type: 'google-user',
              extent: obj.range,
              baseLayer: obj.layer,
              proxyUrl: obj.proxy,
              levelStart: obj.levelStart,
              origin: obj.origin,
              isVector: 1,
              resolution: obj.resolution,
              tileMatrix: obj.coordinate,
              levelEnd: obj.levelEnd,
              levelEndEnlarge: obj.levelEndEnlarge,
              m_Ip: obj.IP,
              m_Port: obj.Port,
              m_User: obj.User,
              m_Pwd: obj.Pwd,
              gsAppName: obj.gsAppName,
            }),
          };

          SetServiceConfig(arr)
            .then(res => {
              if (res.code == '0') {
                onCancel();
                setLoading(false);
                form.resetFields();
                callBackSubmit();
                notification.success({
                  message: '提示',
                  duration: 3,
                  description: res.message || type == 'add' ? '新增成功' : '编辑成功',
                });
              } else {
                setLoading(false);
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: res.message || type == 'add' ? '新增失败' : '编辑失败',
                });
              }
            })
            .catch(err => {
              setLoading(false);
            });
        }
      }
    });
  };

  useEffect(() => {
    if (visible) {
      setAlpha(1);
      let aa;
      if (formObj?.baseLayer) {
        let index = formObj.baseLayer.lastIndexOf(':');
        aa = formObj.baseLayer.substring(0, index);
      }
      if (formObj?.m_User) {
        setAdvanced(1);
        setCurrent(true);
      } else {
        setAdvanced(0);
        setCurrent(false);
      }

      switch (type) {
        case 'add':
          form.setFieldsValue({
            servicename: '',
            label: '',
            gsAppName: 'geoserver217',
            IP: '192.168.12.7',
            proxy: 'javasvc.panda-water.cn/geoserver',
            Port: '8088',
            User: 'admin',
            Pwd: 'geoserver',
            isTainDiTu: 0,
            levelEndEnlarge: false,
          });

          break;
        case 'edit':
          form.setFieldsValue({
            ...formObj,
            isTainDiTu: formObj.isTainDiTu,
            IP: formObj.m_Ip,
            gsAppName: formObj.gsAppName,
            layer: formObj.baseLayer,
            coordinate: formObj.tileMatrix,
            range: formObj.extent,
            proxy: formObj.proxyUrl,
            Port: formObj.m_Port,
            User: formObj.m_User,
            Pwd: formObj.m_Pwd,
            workSpance: aa,
          });
          choose('', {
            Port: formObj.m_Port,
            User: formObj.m_User,
            Pwd: formObj.m_Pwd,
            IP: formObj.m_Ip,
            gsAppName: formObj.gsAppName,
          });
          break;
        default:
          break;
      }
    } else {
      setKeyData([]);
      setData([]);
      setAreaData([]);
      form.resetFields();
    }
  }, [visible]);

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

  // 选择坐标系
  const handleCoordinate = e => {
    let work = form.getFieldsValue().workSpance;
    let lay = form.getFieldsValue().layer;
    let index = lay.indexOf(':');
    let result = lay.substr(index + 1, lay.length);
    getGetCustomBaseMapByName(work, result, e);
  };
  // 选择图层
  const handleLayer = e => {
    let index = e.indexOf(':');
    let result = e.substr(index + 1, e.length);
    let work = form.getFieldsValue().workSpance;
    getGetGridSetList(work, result);
  };
  // 选择工作空间
  const handleWorkSpance = e => {
    setData(spaceData[e]);
    form.setFieldsValue({ layer: spaceData[e][0] });
    let aa = form.getFieldsValue().layer;
    let index = aa.indexOf(':');
    let result = aa.substr(index + 1, aa.length);
    getGetGridSetList(e, result);
  };

  const getGetGridSetList = (a, bb) => {
    let obj = form.getFieldsValue();
    let aa = form.getFieldsValue().layer;
    let result;
    if (aa) {
      let index = aa.indexOf(':');
      result = aa.substr(index + 1, aa.length);
    }
    GetGridSetList({
      m_Port: obj.Port || '8088',
      m_User: obj.User || 'admin',
      m_Pwd: obj.Pwd || 'geoserver',
      m_Ip: obj.IP || '192.168.12.7',
      gsAppName: obj.gsAppName || 'geoserver217',
      layerName: bb,
      workSpaceName: a,
    }).then(res => {
      let data = [];
      res.results.map(i => {
        data.push(i.gridSetName);
      });
      setAreaData(data);
      form.setFieldsValue({ coordinate: data[0] });
      getGetCustomBaseMapByName(a, bb, data[0]);
    });
  };

  const getGetCustomBaseMapByName = (a, bb, cc) => {
    let obj = form.getFieldsValue();
    GetCustomBaseMapByName({
      m_Port: obj.Port || '8088',
      m_User: obj.User || 'admin',
      m_Pwd: obj.Pwd || 'geoserver',
      m_Ip: obj.IP || '192.168.12.7',
      gsAppName: obj.gsAppName || 'geoserver217',
      layerName: bb,
      workSpaceName: a,
      gridSet: cc,
    }).then(res => {
      let aa = res.results.coords;
      setO(`-${JSON.parse(aa)[2]},${JSON.parse(aa)[3]}`);
      setR(res.results.resolutions);
      form.setFieldsValue({
        range: JSON.parse(aa).toString(),
        resolution: res.results.resolutions,
        origin: `-${JSON.parse(aa)[2]},${JSON.parse(aa)[3]}`,
        levelStart: '3',
      });
    });
  };
  const change = (e, event) => {
    if (e) {
      setAdvanced(1);
      setCurrent(true);
    } else {
      setAdvanced(0);
      setCurrent(false);
    }
  };

  const choose = (e, value) => {
    let obj = value ? value : form.getFieldsValue();
    GetCustomBaseMapList({
      m_Port: obj.Port || '8088',
      m_User: obj.User || 'admin',
      m_Pwd: obj.Pwd || 'geoserver',
      m_Ip: obj.IP || '192.168.12.7',
      gsAppName: obj.gsAppName,
    }).then(res => {
      if (res.IsSuccess == true) {
        if (value) {
          setKeyData(Object.keys(res.results));
          let aa = Object.keys(res.results)[0];
          setData(res.results[aa]);
          let bb = res.results[aa];
          let index = bb[0].indexOf(':');
          let result = bb[0].substr(index + 1, bb[0].length);
          getGetGridSetList(aa, result);
        } else {
          setSpaceData(res.results);
          setKeyData(Object.keys(res.results));
          let aa = Object.keys(res.results)[0];
          setData(res.results[aa]);
          let bb = res.results[aa];
          let index = bb[0].indexOf(':');
          let result = bb[0].substr(index + 1, bb[0].length);
          getGetGridSetList(aa, result);
          form.setFieldsValue({ workSpance: aa, layer: bb[0] });
        }

        // if (e) {
        //   let index = formObj.baseLayer.lastIndexOf(':');
        //   handleWorkSpance(formObj.baseLayer.substring(0, index));
        //   handleLayer(formObj.baseLayer);
        //   handleCoordinate(formObj.tileMatrix);
        // }
      } else {
        setSpaceData([]);
        setKeyData([]);
        setData([]);
        setAreaData([]);
        form.setFieldsValue({
          workSpance: '',
          layer: '',
          coordinate: '',
          range: '',
          levelStart: '',
          levelEnd: '',
          origin: '',
          resolution: '',
        });
        notification.error({
          message: '提示',
          duration: 3,
          description: res.EMessage,
        });
      }
    });
  };

  return (
    <Modal
      title={`${type === 'add' ? '新增' : '编辑'}切片管网`}
      bodyStyle={{ width: '100%', maxHeight: '600px', overflow: 'scroll', minHeight: '300px' }}
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender={true}
      getContainer={false}
    >
      {visible && (
        <Form form={form} {...layout}>
          <Item
            label="服务名"
            name="servicename"
            rules={[
              {
                required: true,
                validator: (rule, value) => {
                  if (type !== 'edit' && name.indexOf(form.getFieldsValue().servicename) != -1) {
                    return Promise.reject('服务名称已存在');
                  } else if (form.getFieldsValue().servicename == '') {
                    return Promise.reject('服务名称不能为空');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input placeholder="请输入服务名称" allowClear disabled={type === 'edit'} />
          </Item>
          <Item label="标签" name="label" rules={[{ required: true, message: '请输入标签' }]}>
            <Input placeholder="请输入标签名" allowClear />
          </Item>
          <Item label="ip地址" name="IP" rules={[{ required: true, message: '请输入ip地址' }]}>
            <Input placeholder="请输入ip地址" allowClear />
          </Item>
          <Row>
            <Col span={16}>
              <Item
                label="geoserver名"
                name="gsAppName"
                rules={[{ required: true, message: '请选择缩略图' }]}
                labelCol={{ span: 6 }}
              >
                <Input placeholder="请输入gis服务器名" allowClear />
              </Item>
            </Col>
            <Col span={8}>
              <Item>
                <Button style={{ width: '100%' }} onClick={choose}>
                  选择工作空间
                </Button>
              </Item>
            </Col>
          </Row>
          <Item
            label="工作空间"
            name="workSpance"
            rules={[{ required: true, message: '请选择工作空间' }]}
          >
            <Select onChange={handleWorkSpance}>
              {keyData
                ? keyData.map((item, index) => (
                    <Option value={item} key={index}>
                      {item}
                    </Option>
                  ))
                : ''}
            </Select>
          </Item>
          <Item label="图层名" name="layer" rules={[{ required: true, message: '请选择图层名' }]}>
            <Select onChange={handleLayer} showSearch>
              {data
                ? data.map((item, index) => (
                    <Option value={item} key={index}>
                      {item}
                    </Option>
                  ))
                : ''}
            </Select>
          </Item>
          <Item
            label="坐标系名"
            name="coordinate"
            rules={[{ required: true, message: '请选择坐标系名' }]}
          >
            <Select onChange={handleCoordinate}>
              {areaData
                ? areaData.map((item, index) => (
                    <Option value={item} key={index}>
                      {item}
                    </Option>
                  ))
                : ''}
            </Select>
          </Item>

          <Item
            label="底图范围"
            name="range"
            rules={[{ required: true, message: '请选择底图范围' }]}
          >
            <Input placeholder="xmin,ymin,xmax,ymax" allowClear />
          </Item>
          <Item
            label="起始级别"
            name="levelStart"
            rules={[{ required: true, message: '请选择起始级别' }]}
          >
            <Input placeholder="最初显示级别" allowClear />
          </Item>
          <Item
            label="最大级别"
            name="levelEnd"
            // rules={[{ required: true, message: '请选择最大级别' }]}
          >
            <Input placeholder="最大显示级别" allowClear />
          </Item>
          <Item
            label="放大级别后继续放大"
            name="levelEndEnlarge"
            // rules={[{ required: true }]}
            labelCol={{ span: 7 }}
          >
            <Radio.Group>
              <Radio value={false}>否</Radio>
              <Radio value={true}>是</Radio>
            </Radio.Group>
          </Item>
          <Item label="代理url" name="proxy" rules={[{ required: true, message: '请选择缩略图' }]}>
            <Input placeholder="请输入URL" allowClear />
          </Item>
          <Switch
            checkedChildren="高级设置"
            unCheckedChildren="高级设置"
            onChange={change}
            checked={current}
            style={{ marginLeft: '40px', marginBottom: '15px' }}
          />
          {advanced === 1 ? (
            <>
              <Item
                label="端口号"
                name="Port"
                rules={[{ required: true, message: '请输入端口号' }]}
              >
                <Input placeholder="请输入端口号" allowClear />
              </Item>
              <Item
                label="用户名"
                name="User"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" allowClear />
              </Item>
              <Item label="密码" name="Pwd" rules={[{ required: true, message: '请输入密码' }]}>
                <Input placeholder="请输入密码" allowClear />
              </Item>
              <Item label="原点" name="origin" rules={[{ required: true, message: '请输入原点' }]}>
                <Input placeholder="左上角" disabled />
              </Item>
              <Item
                label="分辨率"
                name="resolution"
                rules={[{ required: true, message: '请输入分辨率' }]}
              >
                <Input placeholder="0级分辨率" disabled />
              </Item>
            </>
          ) : (
            ''
          )}
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;
