/* 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,
} from 'antd';
import styles from '../SchemeConfig.less';
import thumbnail_1 from '@/assets/images/thumbnail/thumbnail_1.jpg';
import thumbnail_2 from '@/assets/images/thumbnail/thumbnail_2.jpg';
import thumbnail_3 from '@/assets/images/thumbnail/thumbnail_3.jpg';
import thumbnail_4 from '@/assets/images/thumbnail/thumbnail_4.jpg';
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, baseMap, name, onCancel } = props;
  const [loading, setLoading] = useState(false);
  const [radio, setRadio] = useState();
  const [alpha, setAlpha] = useState(1);
  const [mapType, setMapType] = useState(0);
  const [advanced, setAdvanced] = useState(0);
  const [spaceData, setSpaceData] = useState([]);
  const [keyData, setKeyData] = useState([]);
  const [data, setData] = useState([]);
  const [areaData, setAreaData] = useState([]);
  const [pickItem, setPickItem] = useState('');
  const [o, setO] = useState('');
  const [r, setR] = useState('');
  const [current, setCurrent] = useState(false);
  const [form] = Form.useForm();
  const arr = [
    'assets/images/thumbnail/thumbnail_1.jpg',
    'assets/images/thumbnail/thumbnail_2.jpg',
    'assets/images/thumbnail/thumbnail_3.jpg',
    'assets/images/thumbnail/thumbnail_4.jpg',
  ];

  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        let arr = {};
        console.log(obj.servicename);
        // 连点
        if (obj.servicename) {
          if (mapType == 1) {
            arr = {
              servicename: obj.servicename,
              terminalType: 'base',
              isBaseMap: true,
              jsonCfg: JSON.stringify({
                alpha: alpha,
                label: obj.label,
                url: obj.url,
                icon: obj.icon,
                type: obj.type,
                extent: obj.range,
                baseLayer: obj.layer,
                proxyUrl: obj.proxy,
                levelStart: obj.levelStart,
                origin: obj.origin || o,
                resolution: obj.resolution || r,
                tileMatrix: obj.coordinate,
                levelEnd: obj.levelEnd,
                levelEndEnlarge: obj.levelEndEnlarge,
                m_Ip: obj.IP,
                m_Port: obj.Port || '8080',
                m_User: obj.User || 'admin',
                m_Pwd: obj.Pwd || 'geoserver',
                gsAppName: obj.gis,
              }),
            };
          } else {
            let url = '';
            if (obj.type == 'streetPurplishBlue') {
              url = '//map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer';
            } else if (obj.type == 'streetGray') {
              url = '//map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer';
            } else if (obj.type == 'streetWarm') {
              url = '//map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetWarm/MapServer';
            }
            arr = {
              servicename: obj.servicename,
              terminalType: 'base',
              isBaseMap: true,
              jsonCfg: JSON.stringify({
                alpha: alpha,
                label: obj.label,
                url: url,
                icon: obj.icon,
                type: obj.type,
              }),
            };
          }

          SetServiceConfig(arr)
            .then(res => {
              if (res.msg === 'Ok') {
                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);
            });
        }
      }
    });
  };

  const onFinish = value => {};
  useEffect(() => {
    setLoading(false);
    setMapType(0);
    setAdvanced(0);
    setCurrent(false);
    setPickItem('');
    setAlpha(1);
    console.log(baseMap);
    switch (type) {
      case 'add':
        setRadio('');
        form.resetFields();
        form.setFieldsValue({
          servicename: '高德地形',
          label: '高德地形',
          type: 'amap-v',
          gis: 'geoserver217',
          IP: '192.168.12.7',
          proxy: 'javasvc.panda-water.cn/geoserver',
          Port: '8080',
          User: 'admin',
          Pwd: 'geoserver',
          levelEndEnlarge: false,
        });

        break;
      case 'edit':
        console.log(formObj);
        form.setFieldsValue({ ...formObj });
        let index = formObj.icon.lastIndexOf('/');
        let str = formObj.icon.substring(index + 1, formObj.icon.length);
        let defaultIndex = arr.filter((item, index) => {
          if (item.indexOf(str) !== -1) {
            return index;
          }
        });
        setRadio(defaultIndex[0]);
        break;
      default:
        break;
    }
    // if (form.getFieldsValue('').servicename && baseMap.indexOf(form.getFieldsValue('').servicename) == 2 || baseMap.indexOf(form.getFieldsValue('').servicename) == 3) {
    //   setMapType(1)
    // }
    // else {
    //   setMapType(0)
    // }
  }, [visible]);

  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 18,
    },
  };
  const onChange = value => {
    let silderData = value == 100 ? 1 : value / 100;
    setAlpha(silderData);
  };
  const tipFormatter = value => {
    return `${value}%`;
  };

  const imgURL = [
    {
      url: thumbnail_1,
    },
    {
      url: thumbnail_2,
    },
    {
      url: thumbnail_3,
    },
    {
      url: thumbnail_4,
    },
  ];

  const radioChange = e => {
    setRadio(e.target.value);
  };
  const handleChange = value => {
    console.log(value);
    setAdvanced(0);
    setCurrent(false);
    form.setFieldsValue({
      label: servicenameToType(value),
      servicename: servicenameToType(value),
    });
    if (value == 'google-user' || value == 'pipenet-tile') {
      setMapType(1);
    } else {
      setMapType(0);
    }
  };
  // 添加地图类型
  const servicenameToType = type => {
    // console.log(name);
    // let random = Math.floor(Math.random() * 100) + 1;
    // if (type == 'google-v') {
    //   let aa = `谷歌地形${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `谷歌地形${random}`;
    //   }
    // } else if (type == 'google-i-a') {
    //   let aa = `谷歌影像(注记)${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `谷歌影像(注记)${random}`;
    //   }
    // } else if (type == 'google-i') {
    //   let aa = `谷歌影像${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `谷歌影像${random}`;
    //   }
    // } else if (type == 'amap-i') {
    //   let aa = `高德影像${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `高德影像${random}`;
    //   }
    // } else if (type == 'amap-v') {
    //   let aa = `高德地形${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `高德地形${random}`;
    //   }
    // } else if (type == 'tianditu-i-ia') {
    //   let aa = `天地图影像${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `天地图影像${random}`;
    //   }
    // } else if (type == 'tianditu-v-va') {
    //   let aa = `天地图地形${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `天地图地形${random}`;
    //   }
    // } else if (type == 'google-user') {
    //   let aa = `自定义底图${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `自定义底图${random}`;
    //   }
    // } else if (type == 'pipenet-tile') {
    //   let aa = `地形图${random}`;
    //   if (name.indexOf(aa) != -1) {
    //     servicenameToType(type);
    //   } else {
    //     return `地形图${random}`;
    //   }
    // }

    switch (type) {
      case 'google-v':
        return '谷歌地形';
      case 'google-i-a':
        return '谷歌影像(注记)';
      case 'google-i':
        return '谷歌影像';
      case 'amap-i':
        return '高德影像';
      case 'amap-v':
        return '高德地形';
      case 'tianditu-i-ia':
        return '天地图影像';
      case 'tianditu-v-va':
        return '天地图地形';
      case 'streetPurplishBlue':
        return 'GeoQ午夜蓝';
      case 'streetGray':
        return 'GeoQ水墨灰';
      case 'streetWarm':
        return 'GeoQ暖色';
      // case 'google-user':
      //   return;
      // case 'pipenet-tile':
      //   return;
      default:
        return;
    }
  };
  // 选择坐标系
  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);
    console.log(result);
    getGetCustomBaseMapByName(work, result, e);
  };
  // 选择图层
  const handleLayer = e => {
    let index = e.indexOf(':');
    let result = e.substr(index + 1, e.length);
    console.log(result);
    let work = form.getFieldsValue().workSpance;
    console.log(work);
    getGetGridSetList(work, result);
  };
  // 选择工作空间
  const handleWorkSpance = e => {
    console.log(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);
    console.log(result);
    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);
      console.log(result);
    }
    GetGridSetList({
      m_Port: obj.Port || '8080',
      m_User: obj.User || 'admin',
      m_Pwd: obj.Pwd || 'geoserver',
      m_Ip: obj.IP || '192.168.12.7',
      gsAppName: obj.gis || 'geoserver217',
      layerName: bb,
      workSpaceName: a,
    }).then(res => {
      let data = [];
      console.log(res.results);
      res.results.map(i => {
        data.push(i.gridSetName);
      });
      console.log(data);
      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 || '8080',
      m_User: obj.User || 'admin',
      m_Pwd: obj.Pwd || 'geoserver',
      m_Ip: obj.IP || '192.168.12.7',
      gsAppName: obj.gis || 'geoserver217',
      layerName: bb,
      workSpaceName: a,
      gridSet: cc,
    }).then(res => {
      let aa = res.results.coords;
      console.log(JSON.parse(aa)[2]);
      console.log(JSON.parse(aa)[3]);
      console.log(JSON.parse(aa).toString());
      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);
    }
    console.log(e);
    console.log(event);
  };

  const choose = () => {
    let obj = form.getFieldsValue();
    GetCustomBaseMapList({
      m_Port: obj.Port || '8080',
      m_User: obj.User || 'admin',
      m_Pwd: obj.Pwd || 'geoserver',
      m_Ip: obj.IP || '192.168.12.7',
      gsAppName: obj.gis,
    }).then(res => {
      if (res.IsSuccess == true) {
        console.log(res.results);
        console.log(Object.keys(res.results));
        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);
        console.log(result);
        getGetGridSetList(aa, result);
        form.setFieldsValue({ workSpance: aa, layer: bb[0] });
      } else {
        setSpaceData([]);
        setKeyData([]);
        setData([]);
        setAreaData([]);
        form.setFieldsValue({
          workSpance: '',
          layer: '',
          coordinate: '',
          range: '',
          levelStart: '',
          levelEnd: '',
          origin: '',
          resolution: '',
        });
        notification.error({
          message: '提示',
          duration: 3,
          description: res.EMessage,
        });
      }
    });
  };

  const title = (
    <span>
      透明度<span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>{alpha}</span>
    </span>
  );

  const marks = {
    0: '0%',
    100: '100%',
  };
  return (
    <Modal
      title="添加基础底图"
      bodyStyle={{ width: '100%', maxHeight: '600px', overflow: 'scroll', minHeight: '360px' }}
      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="类型" name="type" rules={[{ required: true, message: '请选择服务名' }]}>
            <Select onChange={handleChange}>
              <Option value="amap-v">高德地形(amap-v)</Option>
              <Option value="amap-i">高德影像(amap-i)</Option>
              <Option value="tianditu-v-va">天地图地形(tianditu-v-va)</Option>
              <Option value="tianditu-i-ia">天地图影像(tianditu-i-ia)</Option>
              <Option value="pipenet-tile">矢量底图切片(pipenet-tile)</Option>
              <Option value="google-user">自定义底图(google-user)</Option>
              <Option value="streetPurplishBlue">GeoQ午夜蓝(streetPurplishBlue)</Option>
              <Option value="streetGray">GeoQ水墨灰(streetGray)</Option>
              <Option value="streetWarm">GeoQ暖色(streetWarm)</Option>
            </Select>
          </Item>
          <Item
            label="服务名"
            name="servicename"
            rules={[
              {
                required: true,
                validator: (rule, value) => {
                  if (name.indexOf(form.getFieldsValue().servicename) != -1) {
                    return Promise.reject('服务名称已存在');
                  } else if (form.getFieldsValue().servicename == '') {
                    return Promise.reject('服务名称不能为空');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input placeholder="请输入服务名称" allowClear />
          </Item>
          <Item label="标签" name="label" rules={[{ required: true, message: '请输入标签' }]}>
            <Input placeholder="请输入标签名" allowClear />
          </Item>
          {/* <Item label="URL" name="url">
            <Input placeholder="请输入URL" allowClear />
          </Item> */}
          <Item label="透明度" name="alpha">
            <Slider
              marks={marks}
              min={0}
              max={100}
              onChange={onChange}
              // step={0.1}
              tipFormatter={tipFormatter}
              // tooltipVisible
              defaultValue={100}
            />
          </Item>
          <Item
            label="选择缩略图"
            name="icon"
            rules={[{ required: true, message: '请选择缩略图' }]}
          >
            <div style={{ display: 'flex', justifyContent: 'space-around' }}>
              {imgURL.map((item, index) => {
                return (
                  <div
                    className={classnames({
                      [styles.imgHidden]: index !== pickItem,
                      [styles.imgItem]: index === pickItem,
                    })}
                    key={index}
                  >
                    <img
                      width="100"
                      height="63"
                      src={item.url}
                      onClick={e => {
                        setPickItem(index);
                        form.setFieldsValue({ icon: arr[index] });
                      }}
                    />
                    {/* <Radio.Group options={item} onChange={radioChange} value={radio}>
                      <Radio value={arr[index]} />
                    </Radio.Group> */}
                  </div>
                );
              })}
            </div>
          </Item>
          {/* <Item label="缩略图" name="icon" rules={[{ required: true, message: '请选择缩略图' }]}>
            <Input placeholder="请输入URL" disabled />
          </Item> */}
          {mapType === 1 ? (
            <>
              <Item label="ip地址" name="IP" rules={[{ required: true, message: '请输入ip地址' }]}>
                <Input placeholder="请输入ip地址" allowClear />
              </Item>
              <Row>
                <Col span={16}>
                  <Item
                    label="geoserver名"
                    name="gis"
                    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) => {
                        return (
                          <Option value={item} key={index}>
                            {item}
                          </Option>
                        );
                      })
                    : ''}
                </Select>
              </Item>
              <Item
                label="图层名"
                name="layer"
                rules={[{ required: true, message: '请选择图层名' }]}
              >
                <Select onChange={handleLayer}>
                  {data
                    ? data.map((item, index) => {
                        return (
                          <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) => {
                        return (
                          <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;