import React, { useEffect, useState, useRef } from 'react';
import SiteModal from '@/components/Modal/SiteModa';
import { Input, Cascader, Button } from 'antd';
import {
  gcj_decrypt,
  exetent2AmapPoint,
  lngLat2WebMercator,
} from '@/utils/transformUtil';
import { GetAllConfig, GetMetaData } from '@/services/platform/gis';
const { Search } = Input;
import styles from './index.less';
const MapScope = props => {
  const [options, setOptions] = useState([]);

  // const [mouseTool,setMouseTool] = useState(null)
  const { confirmModal, extent, mapId, title, schemename } = props;
  const [currentExtent, setCurrentExtent] = useState();
  const [isDistrict, setIsDistrict] = useState(false);
  const [currentAreaName, setCurrentAreaName] = useState(null);
  const [areaName, setAreaName] = useState([]); // 选择的地区
  const [area, setArea] = useState([]);
  const [flag, setFlag] = useState(0);
  const mapID = useRef();
  const mouseToolID = useRef();
  useEffect(() => {
    console.log(document.getElementById(mapId), '进入组件');
    setAreaName([]);
    if (document.getElementById(mapId)) {
      console.log(mapID, '底图参数');
      if (!mapID.current) {
        // 1.加载底图
        console.log(mapId, '底图33333');
        let m = new window.AMap.Map(mapId);
        console.log(m, '底图');
        mapID.current = m;
        // 2.加载管网配置
        if (!extent) {
          GetAllConfig().then(res => {
            if (res.IsSuccess == true) {
              res.Result.forEach(item => {
                if (item.schemename === schemename) {
                  mapID.current.setCenter(exetent2AmapPoint(item.extent));
                }
              });
              let pipenetCofig;
              res.Result.map(item => {
                if (item.type == 'pipenet') {
                  pipenetCofig = item;
                }
              });
              if (pipenetCofig) {
                GetMetaData(pipenetCofig.servicename).then(res2 => {
                  if (res2 && res2.units) {
                    const layers = res2.layers || [];
                    const workspace = res2.mapName.split('_')[0];
                    const subLayers = layers
                      .filter(
                        layer =>
                          layer.subLayerIds && layer.subLayerIds.length === 0,
                      )
                      .map(layer => layer.name);
                    const paramLayers = `${workspace}:${subLayers.join(',')}`;
                    const params = {
                      LAYERS: paramLayers,
                      VERSION: '1.1.1',
                      _site: '',
                    };
                    console.log('params', params);
                    const wmsOption = {
                      tileSize: 512,
                      url: `${
                        location.origin
                      }/Cityinterface/rest/services/MapServer.svc/${
                        pipenetCofig.servicename
                      }/GeoServerProxy/wms`,
                      blend: false,
                      params: params,
                      zooms: [2, 20],
                    };
                    let wms = new window.AMap.TileLayer.WMS(wmsOption);
                    m.add(wms);
                    console.log(m);
                  }
                });
              }
            }
          });
        }

        // 3.组装高德支持的数据
      }
      if (!mouseToolID.current) {
        let tool = new AMap.MouseTool(mapID.current);
        mouseToolID.current = tool;
      }
      console.log(extent, 'extent');
      extent && mapID.current.setCenter(exetent2AmapPoint(extent));
      //   distinct && onCascderChange([distinct]);
      window.AMap.plugin('AMap.DistrictSearch', function() {
        let districtSearch = new AMap.DistrictSearch({
          // 关键字对应的行政区级别，country表示国家
          level: 'country',
          //  显示下级行政区级数，1表示返回下一级行政区
          subdistrict: 3,
        });

        // 搜索所有省/直辖市信息
        districtSearch.search('中国', function(status, result) {
          // 查询成功时，result即为对应的行政区信息
          console.log(result, '行政区划信息');
          setOptions(result.districtList[0].districtList);
        });
      });
    }
  }, [props]);
  const resetmap = () => {};

  const getInitConfig = () => {};
  const onSubmit = () => {
    console.log(currentExtent);
    console.log(currentAreaName);
    confirmModal && confirmModal(currentExtent, currentAreaName, flag);
    let mouseTool = mouseToolID.current;
    mouseTool.close(true);
    let map = mapID.current;
    map.clearMap();
  };
  const handleSearch = () => {};
  const onTangleClick = () => {
    // if(!mouseTool){
    //     let tool = new AMap.MouseTool(map)
    //     setMouseTool(tool)
    // }
    let mouseTool = mouseToolID.current;
    mouseTool.close(true);

    mouseTool.rectangle({
      fillColor: '#00b0ff',
      strokeColor: '#80d8ff',
      // 同Polygon的Option设置
    });
    console.log(mouseTool, '进入选择范围');
    mouseTool.on('draw', function(event) {
      mouseTool.close(false);
      // console.log(event.obj.getBounds(),"矩形对象")
      let bounds = event.obj.getBounds();
      let ne = bounds.northEast.pos;
      let sw = bounds.southWest.pos;
      let str = sw.concat(ne).toString();
      setFlag(flag + 1);
      console.log(str, 'strstr');
      setCurrentExtent(str);
    });
  };
  const onCascderChange = value => {
    let map = mapID.current;
    map.clearMap();
    console.log(value, '选中的行政区');
    let dic = {
      '1': 'province',
      '2': 'city',
      '3': 'district',
    };
    let level = dic[value.length.toString];
    AMap.plugin('AMap.DistrictSearch', function() {
      // 创建行政区查询对象
      let district = new AMap.DistrictSearch({
        // 返回行政区边界坐标等具体信息
        extensions: 'all',
        // 设置查询行政区级别为 区
        level: level,
      });

      district.search(`${value[value.length - 1]}`, function(status, result) {
        // 获取朝阳区的边界信息

        let bounds = result.districtList[0].boundaries;

        let polygons = [];
        if (bounds) {
          for (let i = 0, l = bounds.length; i < l; i++) {
            // 生成行政区划polygon
            let polygon = new AMap.Polygon({
              map: map,
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.7,
              fillColor: '#CCF3FF',
              strokeColor: '#CC66CC',
            });
            polygons.push(polygon);
          }
          // 地图自适应
          map.setFitView();
          setAreaName(value);
          setCurrentAreaName(value[value.length - 1]);
          setIsDistrict(true);
        }
      });
    });
  };
  const filter = (inputValue, path) => {
    return path.some(
      option =>
        option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  };
  return (
    <SiteModal
      {...props}
      title={
        <span>
          <span style={{ marginRight: '20px' }}>{title}的范围选择</span>
          <span style={{ color: 'red' }}>提示：必须框选范围</span>
        </span>
      }
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: 200, borderRadius: '20px' }}
      afterClose={() => {
        setFlag(0);
      }}
      width="800px"
      cancelText="取消"
      okText="确认"
      onOk={() => onSubmit()}
    >
      <div
        style={{ width: '750px', height: '500px' }}
        className={styles.indexContainer}
      >
        <div style={{ width: '750px', height: '500px', position: 'absolute' }}>
          <div id={mapId} style={{ width: '750px', height: '500px' }} />

          <div style={{ top: '10px', left: '10px', position: 'absolute' }}>
            <Cascader
              fieldNames={{
                label: 'name',
                value: 'name',
                children: 'districtList',
              }}
              options={options}
              onChange={onCascderChange}
              placeholder="请选择行政区"
              showSearch={{ filter }}
              changeOnSelect
              value={areaName}
              style={{ width: '200px' }}
            />
          </div>
          <div style={{ top: '10px', right: '10px', position: 'absolute' }}>
            <Button type="primary" onClick={onTangleClick}>
              框选范围
            </Button>
          </div>
          <div
            style={{
              display: `${isDistrict ? 'inline' : 'none'}`,
              top: '10px',
              left: '220px',
              position: 'absolute',
            }}
          >
            <Button type="primary" onClick={onTangleClick}>
              样式调整
            </Button>
          </div>
        </div>
      </div>
    </SiteModal>
  );
};

export default MapScope;
