/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable no-unused-vars */
/* 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 NewEditModal = props => {
  const { callBackSubmit = () => {}, type, formObj, visible, baseMap, name } = 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 [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) {
        let obj = form.getFieldsValue();
        let arr = {};
        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,
              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.gis,
            }),
          };
        } else {
          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: '',
              baseLayer: '',
              proxyUrl: '',
              levelStart: '',
              origin: '',
              resolution: '',
              tileMatrix: '',
              levelEnd: '',
              levelEndEnlarge: '',
              m_Ip: '',
              m_Port: '',
              m_User: '',
              m_Pwd: '',
              gsAppName: '',
            }),
          };
        }

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

  const onFinish = value => {};
  useEffect(() => {
    console.log(formObj);
    setAlpha(formObj.alpha);
    let aa;
    if (formObj.baseLayer) {
      let index = formObj.baseLayer.lastIndexOf(':');
      aa = formObj.baseLayer.substring(0, index);
      console.log(aa);
    }
    console.log(formObj.baseLayer);
    if (formObj.baseLayer) {
      setMapType(1);
    } else {
      setMapType(0);
    }
    if (formObj.m_User) {
      setAdvanced(1);
      setCurrent(true);
    } else {
      setAdvanced(0);
      setCurrent(false);
    }

    switch (type) {
      case 'edit':
        form.setFieldsValue({
          ...formObj,
          IP: formObj.m_Ip,
          gis: 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,
        });
        let index = formObj.icon.lastIndexOf('/');
        console.log(index);
        let str = formObj.icon.substring(index + 1, formObj.icon.length);
        console.log(str);
        let defaultIndex = arr.filter((item, index) => {
          if (item.indexOf(str) != -1) {
            return item;
          }
        });
        console.log(defaultIndex);
        if (str.indexOf(1) != -1) {
          setPickItem(0);
        } else if (str.indexOf(2) != -1) {
          setPickItem(1);
        } else if (str.indexOf(3) != -1) {
          setPickItem(2);
        } else if (str.indexOf(4) != -1) {
          setPickItem(3);
        }
        setRadio(defaultIndex[0]);
        break;
      default:
        break;
    }
  }, [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 => {
    console.log(e.target.value);
    setRadio(e.target.value);
  };
  const handleChange = value => {
    // form.setFieldsValue({
    //   label: servicenameToType(value),
    //   servicename: servicenameToType(value),
    // });
    console.log(value);
    if (value == 'google-user' || value == 'pipenet-tile') {
      setMapType(1);
      console.log(form.getFieldsValue().IP);
      console.log(form.getFieldsValue().gis);
      if (!form.getFieldsValue().IP) {
        form.setFieldsValue({
          IP: '192.168.12.7',
          gis: 'geoserver217',
          proxy: 'javasvc.panda-water.cn/geoserver',
          levelEndEnlarge: false,
          Port: '8080',
          User: 'admin',
          Pwd: 'geoserver',
        });
      }
    } else {
      setMapType(0);
    }
  };
  // 添加地图类型
  const servicenameToType = type => {
    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 '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());
      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) {
      setCurrent(true);
      setAdvanced(1);
    } else {
      setCurrent(false);
      setAdvanced(0);
    }
    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' }}
      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>
            </Select>
          </Item>
          <Item
            label="服务名"
            name="servicename"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input placeholder="请输入服务名称" disabled />
          </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">
            {console.log(formObj.alpha)}
            <Slider
              marks={marks}
              min={0}
              max={100}
              onChange={onChange}
              tipFormatter={tipFormatter}
              // // tooltipVisible={true}
              defaultValue={formObj.alpha * 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 NewEditModal;
