/* eslint-disable no-case-declarations */
/* eslint-disable import/no-duplicates */
/* eslint-disable no-new */
import React, { useEffect, useState, useRef } from 'react';
import {
  ArcGISMap,
  ArcGISSceneMap,
  Drawtool,
  geomUtils,
  PipenetStylesCenter,
  MapImageLayer,
  watchUtils,
} from '@wisdom-map/arcgismap';
import { getPipenetLayer } from '@wisdom-map/basemap';
import {
  Form,
  Input,
  Slider,
  InputNumber,
  Select,
  Button,
  Cascader,
  notification,
  Tooltip,
  Radio,
  message,
} from 'antd';
import { EnvironmentOutlined } from '@ant-design/icons';
import classnames from 'classnames';
import { GetWebSiteConfig } from '@/services/gis/gis';
import { SetServiceConfig } from '@/services/webConfig/api';
import styles from './index.less';
import { ContinuousLegend } from '@antv/g2/lib/dependents';
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',
};
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 [setttingsSave, setSetttingsSave] = useState({});
  const [name, setName] = useState('');
  const [Schemename, setSchemename] = useState('');
  const [radio, setRadio] = useState();
  const mapRef = useRef();
  const mapInfo = useRef(null);
  const [keep, setKeep] = useState('');
  const [keepSave, setKeepSave] = useState('');
  const [map, setMap] = useState(null);
  const [color, setColor] = 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;
        }
      });
      setTimeout(() => {
        form.setFieldsValue({
          areaName: [setttings.areaName],
          backgroundColor: setttings.backgroundColor,
          backgroundOpacity: setttings.backgroundOpacity * 100,
          boundColor: setttings.boundColor,
          boundWidth: parseInt(setttings.boundWidth),
          extent: setttings.extent,
          schemename: setttings.schemename,
          exportScheme: setttings.exportScheme || 'pandagis',
        });
        setColor(setttings.backgroundColor);
        setRadio(setttings.exportScheme || 'pandagis');
        if (setttings.id) {
          setKeep(setttings);
          setName(setttings.id);
          setSchemename(setttings.schemename);
        } 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 => {
    setMap(viewObject);
    const { layer } = getPipenetLayer(viewObject?.map);
    if (layer) {
      layer.visible = false;
    }
    watchUtils.watch(viewObject, ['zoom'], newzoom => {
      // 鼠标滚动隐藏前端绘制的管网图
      viewObject.map.layers.find(layer => {
        if (layer.layerType == 'PipenetLayer') {
          layer.visible = false;
        }
      });
    });
    if (radio == 'pandagis') {
      // 用户自定义创建的管网图
      viewObject.map.add(pandagis);
    }
    mapInfo.current = viewObject;
  };
  // 选择颜色
  const checkColor = color => {
    form.setFieldsValue({ backgroundColor: color });
    setColor(color);
    mapRef.current.updateAreaColor(color);
  };
  // 表单修改后对地图进行配置
  const changeValue = 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':
        Drawtool.deactivate(false);
        obj[index].areaName = changedFields[0].value[changedFields[0].value.length - 1];
        mapRef.current.changeAreaName(obj[index].areaName);
        break;
      case 'schemename':
        GetWebSiteConfig({ client: 'sandbox' }).then(res => {
          setSchemeList(res.data);
          setMapsettings(res.data);
          setSetttingsSave(res.data);
        });
        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;
            setSchemename(item.schemename);
            setName(item.id);
            setKeep(item);
          } else {
            item.layerType = 'dynamic';
          }
        });
        form.setFieldsValue({
          areaName: setttings.areaName,
          backgroundColor: setttings.backgroundColor,
          backgroundOpacity: setttings.backgroundOpacity * 100,
          boundColor: setttings.boundColor,
          boundWidth: parseInt(setttings.boundWidth),
          extent: setttings.extent,
          exportScheme: setttings.exportScheme || 'pandagis',
        });
        setColor(setttings.backgroundColor);
        setRadio(setttings.exportScheme || 'pandagis');
        mapRef.current.mapchange(obj);
        // 清除原有接口返回后端绘制的管网图
        const { layer } = getPipenetLayer(mapRef.current?.map);
        if (layer) {
          layer.visible = false;
        }
        // 若方案是后端绘制每次切换首先创建用户自定义的后端绘制管网
        if (setttings.exportScheme != 'arcgis') {
          const pandagisaa = new MapImageLayer({
            id: setttings.id,
            url: `/PandaGIS/MapServer/${setttings.id}`,
            layerType: 'PipenetLayertest',
            title: setttings.id,
          });
          // 用户自定义创建的管网图
          mapInfo.current.map.add(pandagisaa);
        }
        setMapsettings(obj);
        break;

      default:
        break;
    }
  };
  // 选择范围
  const onTangleClick = e => {
    Drawtool.activate({
      view: mapInfo.current,
      action: 'extent',
      drawEnd: data => {
        const geom = geomUtils.toGeometry({
          type: 'extent',
          xmin: data.rings[0][0][0],
          xmax: data.rings[0][2][0],
          ymin: data.rings[0][0][1],
          ymax: data.rings[0][1][1],
        });
        form.setFieldsValue({
          extent: `${data.rings[0][0][0]},${data.rings[0][0][1]},${data.rings[0][2][0]},${
            data.rings[0][1][1]
          }`,
        });
        mapRef.current.gotoGeometry(geom);
      },
    });
  };
  // 提交
  const onFinish = () => {
    if (!Drawtool.graphic) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '请选择复位范围再保存',
      });
      return;
    }
    if (radio == 'arcgis' && keepSave != 'success') {
      message.error('请先保存管网前端绘制方案');
      return;
    }
    const obj = form.getFieldsValue();
    let aa = '';
    if (Array.isArray(obj.areaName)) {
      aa = obj.areaName[obj.areaName.length - 1];
    } else {
      aa = obj.areaName;
    }
    const jsConfig = {
      extent: form.getFieldValue('extent'),
      areaName: aa,
      boundColor: '#86c8f8',
      boundWidth: `${obj.boundWidth}px`,
      backgroundColor: obj.backgroundColor,
      backgroundOpacity: obj.backgroundOpacity / 100,
      exportScheme: obj.exportScheme == '' ? 'pandagis' : obj.exportScheme,
    };
    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') }),
        }).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].exportScheme = obj.exportScheme;
        setSetttingsSave(mapObj);
        Drawtool.deactivate(false);
        setKeepSave('');
      } 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 => {
    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 onSave = e => {
    setKeepSave(e);
  };

  return (
    <div>
      <div className={styles.mapContent}>
        <div className={styles.mapTool}>
          <Form
            form={form}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            onFieldsChange={changeValue}
            onFinish={onFinish}
          >
            <Form.Item label="切换方案" name="schemename">
              <Select placeholder="请选择方案">
                {schemeList.map((item, index) => (
                  <Option value={item.schemename} key={index}>
                    {item.schemename}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="地区选择" name="areaName">
              <Cascader
                fieldNames={{
                  label: 'name',
                  value: 'name',
                  children: 'districtList',
                }}
                showSearch
                options={options}
                placeholder="请选择行政区"
                changeOnSelect
                allowClear={false}
              />
            </Form.Item>

            <Form.Item label="遮罩颜色" name="backgroundColor">
              <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">
              <Slider min={0} max={100} />
            </Form.Item>
            <Form.Item label="边界宽度" name="boundWidth">
              <InputNumber min={1} max={10} />
            </Form.Item>
            {name ? (
              <Form.Item label="管网方案" name="exportScheme">
                <Radio.Group onChange={onChange} value={radio}>
                  <Radio value="pandagis">后端绘制</Radio>
                  <Radio value="arcgis">前端绘制</Radio>
                </Radio.Group>
              </Form.Item>
            ) : (
              <></>
            )}

            <Form.Item label="复位范围">
              <div style={{ display: 'flex' }}>
                <Form.Item name="extent" style={{ marginBottom: '0', width: '100%' }}>
                  <Input.TextArea style={{ resize: 'none', height: '76px' }} disabled />
                </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>
        <div className={styles.mapBox}>
          {canLoadMap && (
            // <ArcGISMap
            //   ref={mapRef}
            //   getMapInfo={e => getMapInfo(e)}
            //   config={mapsettings}
            //   widgets={widgets}
            // />
            <ArcGISSceneMap
              ref={mapRef}
              getMapInfo={e => getMapInfo(e)}
              widgets={widgets}
              client="sandbox"
            />
          )}
          {radio == 'arcgis' ? (
            <PipenetStylesCenter
              schemeName={Schemename}
              mapServerName={name}
              view={map}
              savaCallback={onSave}
            />
          ) : (
            <></>
          )}
        </div>
      </div>
    </div>
  );
};

export default Map;
