/* eslint-disable react/jsx-boolean-value */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-case-declarations */
/* eslint-disable import/no-duplicates */
/* eslint-disable no-new */
import React, { useEffect, useState, useRef } from 'react';
import { SketchPicker } from 'react-color';
import {
  ArcGISMap,
  ArcGISSceneMap,
  Drawtool,
  EditTool,
  geomUtils,
  PipenetStylesCenter,
  MapImageLayer,
  GraphicsLayer,
  watchUtils,
  SimpleFillSymbol,
  Graphic,
  EditAndDrawPanel,
} from '@wisdom-map/arcgismap';
import { getPipenetLayer } from '@wisdom-map/basemap';
import {
  Form,
  Input,
  Slider,
  InputNumber,
  Select,
  Button,
  Cascader,
  notification,
  Tooltip,
  Radio,
  message,
  Popconfirm,
  Dropdown,
  Menu,
  Space,
  Tag,
  Divider,
} from 'antd';
import {
  EnvironmentOutlined,
  FormOutlined,
  DoubleLeftOutlined,
  DoubleRightOutlined,
  BorderOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import classnames from 'classnames';
import { GetWebSiteConfig } from '@/services/gis/gis';
import { SetServiceConfig, GetSpriteSheet } from '@/services/webConfig/api';
import { formatTimeStr } from 'antd/lib/statistic/utils';
import styles from './index.less';
const { Option } = Select;
const defaultMap = {
  basemaps: [
    {
      id: '高德地形',
      title: '高德地形',
      thumbnailUrl: 'assets/images/thumbnail_2.jpg',
      baseLayers: [
        {
          title: '高德地形',
          icon: '',
          layerType: 'amap-v',
          url: '',
          opacity: 1,
          visible: false,
          useProxy: false,
          proxyUrl: '',
          style: '',
          extent: '',
          baseLayer: '',
          levelStart: '',
          levelEnd: '',
          levelEndEnlarge: false,
          resolution: '',
          origin: '',
          tileMatrix: '',
        },
      ],
    },
  ],
  id: '',
  title: '',
  icon: '',
  layerType: 'PipenetLayer',
  url: '',
  opacity: 1,
  showLegend: true,
  visible: true,
  useProxy: true,
  proxyUrl: '',
  extent: '',
  baseLayer: '',
  levelStart: '',
  levelEnd: null,
  resolution: '',
  origin: '',
  tileMatrix: '',
  wmtsUrl: '',
  schemename: '',
  roles: '',
  areaName: '上海市',
  boundColor: '#86c8f8',
  backgroundColor: '#000000',
  boundWidth: '10px',
  backgroundOpacity: '0.6',
  exportScheme: 'pandagis',
  customFlag: 0,
};
const widgets = [
  {
    label: '缩放',
    right: 20,
    bottom: 130,
    config: {},
  },
  {
    label: '坐标',
    left: 20,
    bottom: 20,
    config: {},
  },
  {
    label: '比例尺',
    left: 60,
    bottom: 70,
    config: {},
  },
  {
    label: '复位',
    right: 20,
    bottom: 90,
    config: {},
  },
  {
    label: '图层',
    right: 20,
    bottom: 50,
    config: {},
  },
  {
    label: '底图切换',
    right: 60,
    bottom: 45,
    config: {},
  },
];
const Map = props => {
  const { visible, onCancel, schemename } = props;
  const [form] = Form.useForm();
  const [canLoadMap, setCanLoadMap] = useState(false); // 是否加载地图
  const [colorArr, setColorArr] = useState([
    { color: '#ffffff', isCheck: false },
    { color: '#000000', isCheck: false },
    { color: '#9E9E9E', isCheck: false },
    { color: '#009688', isCheck: false },
    { color: '#2196f3', isCheck: false },
    { color: '#19233c', isCheck: false },
  ]);
  const [schemeList, setSchemeList] = useState([]);
  const [options, setOptions] = useState([]);
  const [mapsettings, setMapsettings] = useState({});
  const [firstList, setFirstList] = useState({});
  const [setttingsSave, setSetttingsSave] = useState({});
  const [name, setName] = useState('');
  const [Schemename, setSchemename] = useState({});
  const [radio, setRadio] = useState();
  const mapRef = useRef();
  const styleRef = useRef();
  const mapInfo = useRef(null);
  const [keep, setKeep] = useState('');
  const [keepSave, setKeepSave] = useState('');
  const [map, setMap] = useState(null);
  const [color, setColor] = useState('');
  const [colorList, setColorList] = useState('');
  const [keepColor, setKeepColor] = useState('');
  const [radio1, setRadio1] = useState();
  const [area, setArea] = useState('');
  const keep1 = useRef(null);
  const [flag, setFlag] = useState(0);
  const [toolVisible, setToolVisible] = useState(true);
  const [saveFlag, setSaveFlag] = useState(0);
  const [draw, setDraw] = useState(0); // 原方案是否已绘制了自定义行政区
  const [newDraw, setNewDraw] = useState(0);
  const [keepBorderArea, setKeepBorderArea] = useState();
  const [keepType, setKeepType] = useState('');
  const [resultData, setResultData] = useState(null);
  const [keepDraw, setKeepDraw] = useState([]);
  const [butState, setButState] = useState(false); // 绘制按钮状态
  const [load, setLoad] = useState(false);
  const [keepDataDraw, setKeepDataDraw] = useState([]);
  const [areaFlag, setAreaFlag] = useState(0); // 地区改变标识
  const [keepNameArea, setKeepNameArea] = useState(''); // 保存方案初始地区
  const [keepNameCustomPointExtent, setKeepNameCustomPointExtent] = useState(''); // 保存方案初始自定义区域

  useEffect(() => {
    GetWebSiteConfig({ client: 'sandbox' }).then(res => {
      let setttings = {};
      if (res.data.length === 0) {
        res.data.layers = [defaultMap];
        setttings = defaultMap;
      }
      setSchemeList(res.data);
      setMapsettings(res.data);
      setSetttingsSave(res.data);
      res.data.forEach(item => {
        if (item.layerType === 'PipenetLayer') {
          setttings = item;
        }
      });
      let dalist = res.data;
      dalist.forEach(item => {
        if (item.areaName == null) {
          item.areaName = '上海市';
          item.backgroundColor = '#000000';
          item.boundColor = '#86C8F8';
          item.boundWidth = '5px';
          item.backgroundOpacity = '0.6';
        }
      });
      let list = {};
      list.layers = dalist;
      console.log(list);
      debugger;
      setFirstList({ ...list });
      setTimeout(() => {
        form.setFieldsValue({
          areaName: setttings.areaName ? [setttings.areaName] : ['上海市'],
          backgroundColor: setttings.backgroundColor || '#000000',
          backgroundOpacity: setttings.backgroundOpacity * 100 || '60',
          boundColor: setttings.boundColor || '#86C8F8',
          boundWidth: parseInt(setttings.boundWidth) || '5',
          extent: setttings.extent,
          customPointExtent: setttings.customPointExtent,
          schemename: setttings.schemename,
          exportScheme: setttings.exportScheme || 'pandagis',
          customFlag: setttings.customFlag,
        });
        setKeepNameArea(setttings.areaName);

        setKeepBorderArea(setttings.customPointExtent);
        console.log(setttings.customPointExtent);
        if (setttings.customPointExtent) {
          let aa = JSON.parse(setttings.customPointExtent);
          let data = {};
          console.log(aa);
          if (aa && aa.type) {
            setKeepDraw(aa.geometry);
            setKeepNameCustomPointExtent(aa.geometry);
            setKeepType(aa.type);
            data.type = aa.type;
            let rings = [];
            aa.geometry.map(i => {
              rings.push([i.x, i.y]);
            });
            let hh = {};
            hh.rings = rings;
            console.log(hh);
            data.geometry = geomUtils.toGeometry(hh);
            console.log(data);
            setResultData({ ...data });
          }
        } else {
          setKeepNameCustomPointExtent(setttings.customPointExtent);
          setKeepDraw(setttings.customPointExtent);
        }

        if (setttings.customPointExtent) {
          setDraw(1);
        } else {
          setDraw(0);
        }
        setFlag(setttings.customFlag);
        setColorList(setttings.boundColor || '#86C8F8');
        setKeepColor(setttings.boundColor || '#86C8F8');
        setColor(setttings.backgroundColor || '#000000');
        setRadio(setttings.exportScheme || 'pandagis');
        if (setttings.id) {
          setKeep(setttings);
          setName(setttings.id);
          setSchemename(setttings);
        } else {
          setName('');
        }

        setCanLoadMap(true);
      }, 0);
    });
    // 获取城市选择器列表
    window.AMap.plugin('AMap.DistrictSearch', () => {
      let districtSearch = new AMap.DistrictSearch({
        // 关键字对应的行政区级别,country表示国家
        level: 'country',
        //  显示下级行政区级数,1表示返回下一级行政区
        subdistrict: 3,
      });

      // 搜索所有省/直辖市信息
      districtSearch.search('中国', (status, result) => {
        // 查询成功时,result即为对应的行政区信息
        console.log(result, '行政区划信息');
        result.districtList[0].districtList.push({ adcode: '100000', name: '中华人民共和国' });
        setOptions(result.districtList[0].districtList);
      });
    });
  }, []);

  const getData = () => {
    GetWebSiteConfig({ client: 'sandbox' }).then(res => {
      let setttings = {};
      if (res.data.length === 0) {
        res.data.layers = [defaultMap];
        setttings = defaultMap;
      }
      setSchemeList(res.data);
      let dalist = res.data;
      dalist.forEach(item => {
        if (item.areaName == null) {
          item.areaName = '上海市';
          item.backgroundColor = '#000000';
          item.boundColor = '#86C8F8';
          item.boundWidth = '5px';
          item.backgroundOpacity = '0.6';
        }
      });
      let list = {};
      list.layers = dalist;
      console.log(dalist);
      // setFirstList({ ...list });
      setMapsettings(res.data);
      setSetttingsSave(res.data);
      res.data.forEach(item => {
        if (item.schemename === form.getFieldsValue().schemename) {
          setttings = item;
        }
      });
      console.log(setttings);
      setTimeout(() => {
        form.setFieldsValue({
          areaName: setttings.areaName ? [setttings.areaName] : ['上海市'],
          backgroundColor: setttings.backgroundColor || '#000000',
          backgroundOpacity: setttings.backgroundOpacity * 100 || '60',
          boundColor: setttings.boundColor || '#86C8F8',
          boundWidth: parseInt(setttings.boundWidth) || '5',
          extent: setttings.extent,
          customPointExtent: setttings.customPointExtent,
          schemename: setttings.schemename,
          exportScheme: setttings.exportScheme || 'pandagis',
          customFlag: setttings.customFlag,
        });
        setKeepNameArea(setttings.areaName);

        setKeepBorderArea(setttings.customPointExtent);
        if (setttings.customPointExtent) {
          let aa = JSON.parse(setttings.customPointExtent);
          let data = {};
          console.log(aa);
          if (aa && aa.type) {
            setKeepDraw(aa.geometry);
            setKeepNameCustomPointExtent(aa.geometry);
            setKeepType(aa.type);
            data.type = aa.type;
            let rings = [];
            aa.geometry.map(i => {
              rings.push([i.x, i.y]);
            });
            let hh = {};
            hh.rings = rings;
            console.log(hh);
            data.geometry = geomUtils.toGeometry(hh);
            setResultData({ ...data });
          }
        } else {
          setKeepDraw(setttings.customPointExtent);
          setKeepNameCustomPointExtent(setttings.customPointExtent);
        }

        if (setttings.customPointExtent) {
          setDraw(1);
        } else {
          setDraw(0);
        }
        setFlag(setttings.customFlag);
        setColorList(setttings.boundColor || '#86C8F8');
        setKeepColor(setttings.boundColor || '#86C8F8');
        setColor(setttings.backgroundColor || '#000000');
        setRadio(setttings.exportScheme || 'pandagis');
        if (setttings.id) {
          setKeep(setttings);
          setName(setttings.id);
          setSchemename(setttings);
        } else {
          setName('');
        }

        setCanLoadMap(true);
      }, 0);
    });
    // 获取城市选择器列表
    window.AMap.plugin('AMap.DistrictSearch', () => {
      let districtSearch = new AMap.DistrictSearch({
        // 关键字对应的行政区级别,country表示国家
        level: 'country',
        //  显示下级行政区级数,1表示返回下一级行政区
        subdistrict: 3,
      });

      // 搜索所有省/直辖市信息
      districtSearch.search('中国', (status, result) => {
        // 查询成功时,result即为对应的行政区信息
        console.log(result, '行政区划信息');
        result.districtList[0].districtList.push({ adcode: '100000', name: '中华人民共和国' });
        setOptions(result.districtList[0].districtList);
      });
    });
  };

  // 获取地图实例
  const getMapInfo = viewObject => {
    console.log(areaFlag);
    // 切换方案清除自定义绘制管网;
    // const pipenetLayers = viewObject.map.layers.filter(item => {
    //   item.layerType && item.layerType == 'PipenetLayertest';
    // });
    // viewObject.map.removeMany(pipenetLayers);

    // 切换范围类型清除自定义绘制管网
    viewObject.map.layers.forEach(item => {
      if (item.layerType && item.layerType == 'PipenetLayertest') {
        viewObject.map.remove(item);
      }
    });

    console.log(123);
    setMap(viewObject);
    console.log(viewObject);
    debugger;
    watchUtils.watch(viewObject, ['zoom'], newzoom => {
      // 鼠标滚动隐藏管网图
      viewObject.map.layers.find(layer => {
        if (layer.layerType == 'PipenetLayer') {
          layer.visible = false;
        }
      });
    });
    mapInfo.current = viewObject;
    if (form.getFieldsValue().exportScheme == 'pandagis') {
      console.log(mapInfo.current.map.layers);
      let data = mapInfo.current.map.layers.find(
        item => item.layerType && item.layerType == 'PipenetLayertest',
      );
      console.log(data);
      if (!data) {
        // 用户自定义创建的管网图
        let aa = '';
        mapsettings.map(i => {
          if (i.schemename == form.getFieldsValue().schemename) {
            aa = i.id;
          }
        });
        const pandagis1 = new MapImageLayer({
          id: aa,
          url: `/PandaGIS/MapServer/${aa}`,
          layerType: 'PipenetLayertest',
          title: aa,
        });
        viewObject.map.add(pandagis1);
      }
    }
    setRadio1(form.getFieldsValue().customFlag);
    setAreaFlag(0);
  };

  // 选择颜色
  const checkColor = color => {
    form.setFieldsValue({ backgroundColor: color });
    setColor(color);
    console.log(color);
    mapRef.current.updateAreaColor(color);
  };

  // 表单修改后对地图进行配置
  const changeValue = changedFields => {
    console.log(changedFields);
    if (changedFields.length === 0) {
      return;
    }
    let obj = JSON.parse(JSON.stringify(setttingsSave));
    const index = obj.findIndex(item => item.schemename === form.getFieldValue('schemename'));
    switch (changedFields[0].name[0]) {
      case 'backgroundOpacity':
        obj[index].backgroundOpacity = changedFields[0].value / 100;
        mapRef.current.changeBackgroundOpacity(obj[index].backgroundOpacity);
        break;
      case 'boundWidth':
        obj[index].boundWidth = changedFields[0].value;
        mapRef.current.changeBoundWidthValue(obj[index].boundWidth);
        break;
      case 'areaName':
        obj[index].areaName = changedFields[0].value[changedFields[0].value.length - 1];
        setButState(false);
        // 如果地区与范围初始值相等则范围已绘制
        if (radio == 1) {
          if (keepNameArea === changedFields[0].value[changedFields[0].value.length - 1]) {
            if (keepNameArea !== '') {
              mapRef.current.changeAreaName(keepNameArea, keepDraw);
              setDraw(1);
            } else {
              setDraw(0);
              mapRef.current.changeAreaName(obj[index].areaName);
            }
          } else {
            setDraw(0);
            mapRef.current.changeAreaName(obj[index].areaName);
          }
          setAreaFlag(1);
          setFlag(0);
          Drawtool.deactivate(false);
          setArea('');
        } else {
          mapRef.current.changeAreaName(obj[index].areaName);
        }

        setNewDraw(0);
        setResultData(null);

        let aa = { ...firstList };
        aa.layers.map(i => {
          if (i.layerType == 'PipenetLayer') {
            i.layerType = 'dynamic';
            i.areaName = obj[index].areaName;
          }
          if (i.schemename == form.getFieldsValue().schemename) {
            i.backgroundColor = color;
            i.boundColor = colorList;
            i.boundWidth = form.getFieldsValue().boundWidth;
            i.backgroundOpacity = form.getFieldsValue().backgroundOpacity / 100;
            i.layerType = 'PipenetLayer';
          }
        });
        console.log(aa);
        // setFirstList({ ...aa });
        break;
      case 'schemename':
        setKeepDataDraw([]);
        setRadio1('');

        GetWebSiteConfig({ client: 'sandbox' }).then(res => {
          setSchemeList(res.data);
          setMapsettings(res.data);
          setSetttingsSave(res.data);

          let dalist = res.data;
          dalist.forEach(item => {
            if (item.layerType == 'PipenetLayer') {
              item.layerType = 'dynamic';
            }
            if (item.areaName == null) {
              item.areaName = '上海市';
              item.backgroundColor = '#000000';
              item.boundColor = '#86C8F8';
              item.boundWidth = '5px';
              item.backgroundOpacity = '0.6';
              console.log(changedFields[0].value);
            }
            if (item.schemename == changedFields[0].value) {
              item.layerType = 'PipenetLayer';
            }
          });
          console.log(dalist);
          let list = {};
          list.layers = dalist;
          console.log(list);
          debugger;
          setFirstList({ ...list });
        });
        setArea('');
        Drawtool.deactivate(false);

        let setttings;
        obj.forEach(item => {
          if (item.schemename.schemename) {
            item.schemename = item.schemename.schemename;
          }
          if (item.schemename === changedFields[0].value) {
            item.layerType = 'PipenetLayer';
            setttings = item;
            console.log(item);
            setSchemename(item);
            setName(item.id);
            setKeep(item);
          } else {
            item.layerType = 'dynamic';
          }
        });

        form.setFieldsValue({
          areaName: setttings.areaName ? [setttings.areaName] : ['上海市'],
          backgroundColor: setttings.backgroundColor || '#000000',
          backgroundOpacity: setttings.backgroundOpacity * 100 || '60',
          boundColor: setttings.boundColor || '#86C8F8',
          boundWidth: parseInt(setttings.boundWidth) || '5',
          extent: setttings.extent,
          customPointExtent: setttings.customPointExtent,
          exportScheme: setttings.exportScheme || 'pandagis',
          customFlag: setttings.customFlag,
        });
        setKeepNameArea(setttings.areaName);

        if (setttings.customPointExtent) {
          let aa = JSON.parse(setttings.customPointExtent);
          if (aa && aa.type) {
            setKeepDraw(aa.geometry);
            setKeepNameCustomPointExtent(aa.geometry);
            setKeepType(aa.type);
            let data = {};
            data.type = aa.type;
            let rings = [];
            aa.geometry.map(i => {
              rings.push([i.x, i.y]);
            });
            let hh = {};
            hh.rings = rings;
            data.geometry = geomUtils.toGeometry(hh);
            setResultData({ ...data });
          }
        } else {
          setKeepDraw(setttings.customPointExtent);
          setKeepNameCustomPointExtent(setttings.customPointExtent);
        }

        setKeepBorderArea(setttings.customPointExtent);
        setButState(false);
        setNewDraw(0);
        if (setttings.customPointExtent) {
          setDraw(1);
        } else {
          setDraw(0);
        }
        setFlag(setttings.customFlag);
        setColorList(setttings.boundColor || '#86C8F8');
        setKeepColor(setttings.boundColor || '#86C8F8');
        setColor(setttings.backgroundColor || '#000000');
        setRadio(setttings.exportScheme || 'pandagis');
        setRadio1(setttings.customFlag);

        mapRef.current.mapchange(obj);
        break;

      default:
        break;
    }
  };

  // 选择范围
  const onTangleClick = e => {
    let aa = 0;
    Drawtool.activate({
      view: mapInfo.current,
      action: 'extent',
      drawEnd: data => {
        aa = 1;
        setLoad(false);
        setArea(data);
        console.log(data);
        const geom1 = geomUtils.toGeometry({
          type: 'extent',
          xmin: data.rings[0][0][0],
          xmax: data.rings[0][2][0],
          ymin: data.rings[0][1][1],
          ymax: data.rings[0][0][1],
        });
        form.setFieldsValue({
          extent: `${data.rings[0][0][0]},${data.rings[0][1][1]},${data.rings[0][2][0]},${
            data.rings[0][0][1]
          }`,
        });
        mapRef.current.gotoGeometry(geom1);
      },
    });
    setTimeout(() => {
      console.log(aa);
    }, 0);
  };

  const saveCallBack = e => {
    setSaveFlag(1);
    console.log(e);
    if (e.geometry && e.geometry.rings) {
      let geom1 = [];
      e.geometry.rings[0].forEach(i => {
        geom1.push({ x: i[0], y: i[1] });
      });

      let area1 = form.getFieldsValue().areaName;
      mapRef.current.changeAreaName(area1[area1.length - 1], geom1);
      form.setFieldsValue({
        customPointExtent: geom1,
      });
      setKeepNameArea(area1[area1.length - 1]);
      setKeepDraw(geom1);
      setKeepDataDraw(geom1);
      setButState(false);
      setDraw(1);
      let data = {
        geometry: e.geometry,
        type: e.type,
      };
      setKeepType(e.type);
      setResultData({ ...data });
    } else if (e.geometry == null && draw == 0) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '请先绘制范围再保存',
      });
    } else {
      setButState(false);
      let aa = JSON.parse(form.getFieldsValue().customPointExtent);
      form.setFieldsValue({ customPointExtent: aa.geometry });
      console.log(form.getFieldsValue().customPointExtent.geometry);
    }
    Drawtool.deactivate(false);
  };

  // 提交
  const onFinish = () => {
    if (form.getFieldsValue().customFlag == 1 && draw == 0) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '自定义行政区范围未绘制完成',
      });
      return;
    }
    if (radio == 'arcgis') {
      let style = styleRef.current.stylesCompare();
      if (JSON.stringify(style.originalStyle) == JSON.stringify(style.newStyle)) {
        console.log(123);
      } else {
        message.error('请先保存管网前端绘制方案');
        return;
      }
    }
    if (!area) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '请选择复位范围再保存',
      });
      return;
    }

    const obj = form.getFieldsValue();
    let aa = '';
    if (Array.isArray(obj.areaName)) {
      aa = obj.areaName[obj.areaName.length - 1];
    } else {
      aa = obj.areaName;
    }
    let list;
    if (obj.boundColor.hex) {
      list = obj.boundColor.hex;
    } else {
      list = obj.boundColor;
    }

    let data = {};
    if (obj.customPointExtent) {
      if (keepBorderArea && obj.customPointExtent.constructor === Array) {
        data.type = keepType;
        data.geometry = obj.customPointExtent;
      } else if (!keepBorderArea && obj.customPointExtent.constructor === Array) {
        data.type = keepType;
        data.geometry = obj.customPointExtent;
      } else {
        data = obj.customPointExtent;
        console.log(obj.customPointExtent);
      }
    } else if (keepDataDraw.length > 0) {
      data.type = keepType;
      data.geometry = keepDataDraw;
    } else if (keepBorderArea) {
      console.log(keepBorderArea.constructor);
      if (keepBorderArea.constructor === Array) {
        data.type = keepType;
        data.geometry = keepBorderArea;
      } else if (keepBorderArea.constructor === Object) {
        data = keepBorderArea;
      }
      console.log(keepBorderArea);
    } else {
      data = '';
    }
    console.log(data);
    if (JSON.stringify(data) === '{}') {
      data = null;
    }
    const jsConfig = {
      extent: form.getFieldValue('extent'),
      customPointExtent: data,
      areaName: aa,
      boundColor: list,
      boundWidth: `${obj.boundWidth}px`,
      backgroundColor: obj.backgroundColor,
      backgroundOpacity: obj.backgroundOpacity / 100,
      exportScheme: obj.exportScheme == '' ? 'pandagis' : obj.exportScheme,
      customFlag: obj.customFlag,
    };
    SetServiceConfig({
      schemename: obj.schemename,
      terminalType: 'web',
      isBaseMap: false,
      jsonCfg: JSON.stringify(jsConfig),
    }).then(res => {
      if (res.code == '0') {
        SetServiceConfig({
          schemename: obj.schemename,
          terminalType: 'phone',
          isBaseMap: false,
          jsonCfg: JSON.stringify({
            extent: form.getFieldValue('extent'),
            customPointExtent: obj.customPointExtent ? data : keepBorderArea,
          }),
        }).then();
        notification.success({
          message: '提示',
          duration: 3,
          description: '保存成功',
        });
        let mapObj = JSON.parse(JSON.stringify(mapsettings));
        const index = mapObj.findIndex(
          item => item.schemename === form.getFieldValue('schemename'),
        );
        mapObj[index].backgroundOpacity = obj.backgroundOpacity / 100;
        mapObj[index].boundWidth = `${obj.boundWidth}px`;
        mapObj[index].areaName = obj.areaName[obj.areaName.length - 1];
        mapObj[index].backgroundColor = obj.backgroundColor;
        mapObj[index].extent = form.getFieldValue('extent');
        mapObj[index].customPointExtent = obj.customPointExtent;
        mapObj[index].exportScheme = obj.exportScheme;
        mapObj[index].customFlag = obj.customFlag;
        if (obj.customPointExtent) {
          setDraw(1);
        } else {
          setDraw(0);
        }
        setSetttingsSave(mapObj);
        Drawtool.deactivate(false);

        // setArea('');
        setKeepSave('');
        getData();
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const pandagis = new MapImageLayer({
    id: keep.id,
    url: `/PandaGIS/MapServer/${keep.id}`,
    layerType: 'PipenetLayertest',
    title: keep.id,
  });

  const onChange = e => {
    const { layer } = getPipenetLayer(mapInfo.current?.map);
    if (layer) {
      layer.visible = false;
    }
    if (e.target.value == 'arcgis') {
      // 选择前端绘制时,如果界面有自定义的管网图就隐藏,打开组件自动生成前端管网图
      mapInfo.current.map.layers.forEach(item => {
        if (item.layerType && item.layerType == 'PipenetLayertest') {
          mapInfo.current.map.remove(item);
        }
      });
    } else {
      // 选择后端绘制时创建自定义的管网图,前端管网被组件关闭自动销毁
      mapInfo.current.map.add(pandagis);
    }
    setRadio(e.target.value);
  };

  const onChange1 = e => {
    setResultData(null);
    if (e.target.value == 0) {
      let data = form.getFieldsValue().areaName;
      mapRef.current.changeAreaName(data[data.length - 1]);
      setButState(false);
      Drawtool.deactivate();
      setRadio1(e.target.value);
    } else {
      console.log(keepDraw);
      if (keepDraw) {
        let area1 = form.getFieldsValue().areaName;
        mapRef.current.changeAreaName(area1[area1.length - 1], keepDraw);
        let data = {};
        console.log(keepType);
        data.type = keepType;
        let rings = [];
        keepDraw.map(i => {
          rings.push([i.x, i.y]);
        });
        let hh = {};
        hh.rings = rings;
        console.log(hh);
        data.geometry = geomUtils.toGeometry(hh);
        setResultData({ ...data });
      }
      if (draw == 0) {
        setButState(false);
      }
      setRadio1(e.target.value);
    }
    let aa = { ...firstList };
    aa.layers.map(i => {
      if (i.layerType == 'PipenetLayer') {
        i.layerType = 'dynamic';
      }
      if (i.schemename == form.getFieldsValue().schemename) {
        i.backgroundColor = color;
        i.boundColor = colorList;
        i.boundWidth = form.getFieldsValue().boundWidth;
        i.backgroundOpacity = form.getFieldsValue().backgroundOpacity / 100;
        i.layerType = 'PipenetLayer';
      }
    });
    console.log(aa);
    // setFirstList({ ...aa });
  };

  const onSave = e => {
    setKeepSave(e);
  };

  // 颜色选择
  const colorChange = value => {
    form.setFieldsValue({ boundColor: value.hex });
    console.log(value.hex);
    mapRef.current.changeBoundColor(value.hex);
    setColorList(value.hex);
  };

  return (
    <div className={styles.mapContent}>
      <div
        className={classnames({
          [styles.mapTool]: true,
          [styles.mapToolHide]: !toolVisible,
        })}
      >
        {toolVisible && (
          <Form
            form={form}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            labelWrap
            onFieldsChange={changeValue}
            onFinish={onFinish}
          >
            <Form.Item label="切换方案" name="schemename" style={{ marginBottom: '19px' }}>
              <Select placeholder="请选择方案" showSearch>
                {schemeList.map((item, index) => (
                  <Option value={item.schemename} key={index}>
                    {item.schemename}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Divider orientation="left" style={{ borderTopColor: '#99bbe8', color: '#0079c1' }}>
              <strong>范围编辑</strong>
            </Divider>
            <Form.Item label="地区选择" name="areaName" style={{ marginBottom: '19px' }}>
              <Cascader
                fieldNames={{
                  label: 'name',
                  value: 'name',
                  children: 'districtList',
                }}
                showSearch
                options={options}
                placeholder="请选择行政区"
                changeOnSelect
                allowClear={false}
              />
            </Form.Item>
            <Form.Item label="范围类型" name="customFlag" style={{ marginBottom: '19px' }}>
              <Radio.Group onChange={onChange1} value={radio1}>
                <Radio value={0}>地区选择</Radio>
                <Radio value={1}>手绘区域</Radio>
              </Radio.Group>
            </Form.Item>
            {radio1 === 1 && (
              <>
                <Form.Item label="手绘区域" name="customPointExtent">
                  {butState && (
                    <Tag
                      style={{
                        width: '100px',
                        height: '27px',
                        paddingLeft: '28px',
                        paddingTop: '0px',
                        marginTop: '4px',
                        display: 'flex',
                        alignItems: 'center',
                      }}
                      color="warning"
                    >
                      绘制中
                    </Tag>
                  )}
                  {!butState && draw == 0 && (
                    <Tag
                      style={{
                        width: '100px',
                        height: '27px',
                        paddingLeft: '25px',
                        paddingTop: '0px',
                        marginTop: '4px',
                        display: 'flex',
                        alignItems: 'center',
                      }}
                      color="processing"
                      onClick={() => {
                        setButState(true);
                      }}
                    >
                      开始绘制
                    </Tag>
                  )}
                  {!butState && draw == 1 && (
                    <Tooltip title="点击按钮开始绘制">
                      <Tag
                        icon={<CheckCircleOutlined style={{ marginTop: '3px' }} />}
                        color="success"
                        style={{
                          width: '100px',
                          height: '27px',
                          paddingLeft: '21px',
                          paddingTop: '0px',
                          marginTop: '4px',
                          display: 'flex',
                          alignItems: 'center',
                        }}
                        onClick={() => {
                          setNewDraw(0);
                          setButState(true);
                        }}
                      >
                        已绘制
                      </Tag>
                    </Tooltip>
                  )}
                </Form.Item>
              </>
            )}

            <Form.Item label="遮罩颜色" name="backgroundColor" style={{ marginBottom: '19px' }}>
              <div className={styles.colorContent}>
                {colorArr.map(item => (
                  <div
                    className={classnames(styles.colorBox, {
                      [styles.currentColor]: item.color === color,
                    })}
                    key={item.color}
                    style={{ background: item.color }}
                    onClick={() => checkColor(item.color)}
                  />
                ))}
              </div>
            </Form.Item>
            <Form.Item label="透明度(%)" name="backgroundOpacity" style={{ marginBottom: '19px' }}>
              <Slider min={0} max={100} />
            </Form.Item>
            <Form.Item label="边界颜色" name="boundColor" style={{ marginBottom: '19px' }}>
              <Popconfirm
                overlayClassName={styles.Popconfirmtitle}
                placement="topLeft"
                icon={false}
                title={
                  <SketchPicker width="217px" color={colorList} onChange={e => colorChange(e)} />
                }
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  setKeepColor(colorList);
                }}
                onCancel={() => {
                  form.setFieldsValue({ boundColor: keepColor });
                  mapRef.current.changeBoundColor(keepColor);
                  setColorList(keepColor);
                }}
              >
                <div className={styles.borderColor}>
                  <div
                    style={{
                      background: colorList,
                      width: '18px',
                      height: '10px',
                      marginLeft: '1px',
                      marginTop: '4px',
                    }}
                  />
                </div>
              </Popconfirm>
            </Form.Item>
            <Form.Item label="边界宽度" name="boundWidth" style={{ marginBottom: '19px' }}>
              <InputNumber min={1} max={10} />
            </Form.Item>
            <Divider orientation="left" style={{ borderTopColor: '#99bbe8', color: '#0079c1' }}>
              <strong>高级设置</strong>
            </Divider>
            {name ? (
              <Form.Item label="管网方案" name="exportScheme" style={{ marginBottom: '19px' }}>
                <Radio.Group onChange={onChange} value={radio}>
                  <Radio value="pandagis">整图绘制</Radio>
                  <Radio value="arcgis">实时绘制</Radio>
                </Radio.Group>
              </Form.Item>
            ) : (
              <></>
            )}

            <Form.Item label="复位视野" style={{ marginBottom: '19px' }}>
              <div style={{ display: 'flex' }}>
                <Form.Item name="extent" style={{ marginBottom: '0', width: '100%' }}>
                  {!load && !area && (
                    <Tooltip title="点击按钮开始绘制">
                      <Tag
                        color="processing"
                        icon={<EnvironmentOutlined style={{ marginTop: '2px' }} />}
                        style={{
                          width: '100px',
                          height: '27px',
                          paddingLeft: '13px',
                          paddingTop: '0px',
                          marginTop: '4px',
                          display: 'flex',
                          alignItems: 'center',
                        }}
                        onClick={() => {
                          onTangleClick();
                          setLoad(true);
                        }}
                      >
                        开始绘制
                      </Tag>
                    </Tooltip>
                  )}

                  {load && (
                    <Tooltip title="点击按钮开始绘制">
                      <Tag
                        icon={<EnvironmentOutlined style={{ marginTop: '2px' }} />}
                        color="warning"
                        style={{
                          width: '100px',
                          height: '27px',
                          paddingLeft: '20px',
                          paddingTop: '0px',
                          marginTop: '4px',
                          display: 'flex',
                          alignItems: 'center',
                        }}
                        onClick={() => {
                          onTangleClick();
                        }}
                      >
                        绘制中
                      </Tag>
                    </Tooltip>
                  )}
                  {area && !load && (
                    <Tooltip title="点击按钮开始绘制">
                      <Tag
                        icon={<EnvironmentOutlined style={{ marginTop: '2px' }} />}
                        color="success"
                        style={{
                          width: '100px',
                          height: '27px',
                          paddingLeft: '20px',
                          paddingTop: '0px',
                          marginTop: '4px',
                          display: 'flex',
                          alignItems: 'center',
                        }}
                        onClick={() => {
                          onTangleClick();
                          setLoad(true);
                        }}
                      >
                        已绘制
                      </Tag>
                    </Tooltip>
                  )}
                </Form.Item>
                {/* <Tooltip title="复位视野框选">
                    <Button
                      style={{ height: '76px', borderLeft: 'none' }}
                      icon={<EnvironmentOutlined style={{ marginTop: '5px' }} />}
                      onClick={e => onTangleClick(e)}
                    />
                  </Tooltip> */}
              </div>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        )}

        <div className={styles.switcher}>
          {toolVisible && (
            <Tooltip title="隐藏配置栏">
              <DoubleLeftOutlined onClick={() => setToolVisible(false)} />
            </Tooltip>
          )}
          {!toolVisible && (
            <Tooltip title="显示配置栏">
              <DoubleRightOutlined onClick={() => setToolVisible(true)} />
            </Tooltip>
          )}
        </div>
      </div>
      <div className={styles.mapBox}>
        {canLoadMap && (
          <ArcGISSceneMap
            ref={mapRef}
            filterMap={true}
            getMapInfo={e => getMapInfo(e)}
            widgets={widgets}
            config={firstList}
            client="sandbox"
          />
        )}
        {radio == 'arcgis' ? (
          <PipenetStylesCenter
            schemeName={Schemename.schemename}
            mapServerName={name}
            view={map}
            savaCallback={onSave}
            ref={styleRef}
            pipenetLayer={Schemename}
          />
        ) : (
          <></>
        )}
        {radio1 == 1 && butState ? (
          <>
            <span>{console.log(form.getFieldsValue().areaName)}</span>
            <EditAndDrawPanel
              view={mapInfo.current}
              editType={['POLYGON', 'EXTENT', 'CIRCLE']}
              defaultGraphic={resultData}
              areaName={
                form.getFieldsValue().areaName &&
                form.getFieldsValue().areaName[form.getFieldsValue().areaName.length - 1]
              }
              useActivePanel
              colorConfigBtnShow
              handleBtnShow
              callback={saveCallBack}
            />
          </>
        ) : (
          <></>
        )}
      </div>
    </div>
  );
};

export default Map;