import React, { FC, useState, useEffect } from 'react';
import { MAP_STYLES } from '../../../config/map';
import IconFont from '@sensoro/library/lib/components/icon-font';
import classNames from '@pansy/classnames';
import markImg from '@/assets/map/mark.png';
import styles from './index.less';

const MapTheme: FC<any> = props => {
  const {
    __map__,
    small,
    noStyle,
    defaultStatus,
    onStatusChange,
    style,
  } = props;

  const map = __map__;
  const [gridStatus, setGridStatus] = useState<boolean>(!!defaultStatus);
  const [sateLite, setSateLite] = useState<any>(null);
  const [markerLayer, setMarkLayer] = useState<any>(null);

  useEffect(() => {
    try {
      map.plugin(['AMap.TileLayer'], () => {
        const sate = new window.AMap.TileLayer.Satellite();
        const layer = new window.AMap.TileLayer.Flexible({
          cacheSize: 30,
          opacity: 0.9,
          //@ts-ignore
          createTile: function(x, y, z, success, fail) {
            let img = document.createElement('img');
            img.onload = function() {
              success(img);
            };
            img.crossOrigin = 'anonymous';
            img.onerror = function() {
              fail();
            };
            img.src = markImg;
          },
        });
        setMarkLayer(layer);
        setSateLite(sate);
      });
    } catch (e) {
      console.log(e);
    }
  }, []);

  const handleThemeChange = (e: any) => {
    e.stopPropagation();
    e.preventDefault();
    if (gridStatus) {
      map.setMapStyle(MAP_STYLES.whiteSmoke);
      markerLayer && map?.remove([sateLite, markerLayer]);
      setGridStatus(false);
      onStatusChange?.(false);
    } else {
      map.setMapStyle(MAP_STYLES.grid);
      markerLayer && map?.add([sateLite, markerLayer]);
      setGridStatus(true);
      onStatusChange?.(true);
    }
  };

  return noStyle ? (
    <span
      onClick={handleThemeChange}
      className={classNames(styles.operator, {
        [styles.active]: gridStatus,
      })}
    >
      <IconFont type="icon-map-theme-grid" />
      实景
    </span>
  ) : (
    <div
      className={classNames(styles.tool, {
        [styles.small]: true,
        'map-grid-theme': true,
      })}
      style={{ ...style }}
    >
      <span
        onClick={handleThemeChange}
        className={classNames(styles.operator, {
          [styles.active]: gridStatus,
        })}
      >
        <IconFont type="icon-map-theme-grid" />
        实景
      </span>
    </div>
  );
};

export default MapTheme;
