import React, { useState, useEffect, useRef, useMemo } from 'react';
import mapstyles from './index.less';
import { useModel } from 'umi';

import cx from 'classnames';
import Icon from '@/tenants-ui/SgIcon';

type MapProps = {
  type: string;
  // searchText: any;
  selFloorId?: string;
  render: (item: API.MapInfo, index: number) => React.ReactNode;
  mapList: API.MapInfo[];
  mapSize: any;
  changeMapList: any;
};

const Map: React.FC<MapProps> = ({ type, selFloorId, render, mapList, changeMapList, mapSize }) => {
  //useModel 注释掉 不用啦 晚会删

  //   useEffect(() => {
  //     getMapListData(selFloorId);
  //   }, [selFloorId]);
  const {
    searchText,
    changeSearchSpace,
    changeSearchText,
    changeSearchFloorId,
    changeSearchBuildId,
  } = useModel('sagacare_searchInfo');
  //const [mapList, setCurMapList] = useState<any>(mapList);
  const [startPageX, setStartPageX] = useState<number>(0);
  const [startPageY, setStartPageY] = useState<number>(0);

  const [translateX, setTranslateX] = useState<number>(0);
  const [translateY, setTranslateY] = useState<number>(0);

  //const [mscale, setMscale] = useState<number>(1);
  const mscale = useRef<number>(1);
  //最大的缩放比例
  const [maxscale, setMaxscale] = useState<number>(1.5);
  const [minscale, setMinscale] = useState<number>(0.5);
  const [canMove, setCanMove] = useState<boolean>(false);

  const [mapHeight, setMapHeight] = useState(500);

  const currentFloorId = useRef<any>(null);
  const mapRef = useRef();
  //   let mapWidth: number = 3000,
  //     mapHeight: number = 1200;

  const mouseDownEvent = (event: React.MouseEvent) => {
    setStartPageX(event.pageX);
    setStartPageY(event.pageY);
    //console.log('mouseDownEvent', startPageX, event.pageY);
    setCanMove(true);
  };
  const mouseUpEvent = (event: React.MouseEvent) => {
    //console.log('mouseUpEvent', event);
    setCanMove(false);
  };
  const mouseMoveEvent = (event: React.MouseEvent) => {
    if (canMove) {
      let nowPageX = event.pageX;
      let nowPageY = event.pageY;
      setTranslateX(translateX + nowPageX - startPageX);
      setTranslateY(translateY + nowPageY - startPageY);
      //console.log('mouseMoveEvent-xx', translateX, nowPageX, startPageX);
      // console.log('mouseMoveEvent-yy', translateY, nowPageY, startPageY);

      setStartPageX(event.pageX);
      setStartPageY(event.pageY);
    }
  };

  const mapZoom = (event: React.MouseEvent) => {
    event.stopPropagation();

    var mscaleTemp: number = Number((mscale.current + 0.1).toFixed(4));
    //setMscale(mscaleTemp);
    mscale.current = Math.min(mscaleTemp, maxscale);
    changeMap(mscale.current);
    var changeWidth = (mapSize.width * (mscaleTemp - 1)) / 2;
    var changeHeight = (mapSize.height * (mscaleTemp - 1)) / 2;
    //   setTranslateX(translateX - changeWidth);
    //   setTranslateY(translateY - changeHeight);

    //console.log('mscale', mscaleTemp);
  };

  const mapReduce = (event: React.MouseEvent) => {
    event.stopPropagation();
    //console.log('mapReduce', mscale);
    // if (mscale.current > minscale) {
    var mscaleTemp = Number((mscale.current - 0.1).toFixed(4));
    mscale.current = Math.max(mscaleTemp, minscale);
    changeMap(mscale.current);
    var changeWidth = (mapSize.width * (mscaleTemp - 1)) / 2;
    var changeHeight = (mapSize.height * (mscaleTemp - 1)) / 2;
    //   setTranslateX(translateX - changeWidth);
    //   setTranslateY(translateY - changeHeight);
    // }
  };
  function changeMap(scale) {
    changeMapList(scale);
  }
  //const fixWidth = 1300;
  //   useEffect(() => {
  //     var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
  //     var scale = Number((mapWrapWidth / mapSize.width).toFixed(4));
  //     setMscale(scale);
  //     changeMap(scale);
  //     //if (scale < 0.3) {
  //     setMinscale(scale);
  //     //}
  //   }, [mapSize]);

  //当地图发生改变时 的搜索
  useEffect(() => {
    //searchText使用对象 防止修改了 不再重新定位
    //根据searchText进行搜索 如果mapList 更改了

    if (searchText && searchText.text && mapList.length > 0) {
      let left: any, top: any;

      var filterItem = mapList.filter((item) => {
        return item.localName == (searchText && searchText.text);
      });
      if (filterItem.length == 0) return;
      //找到搜索的空间
      changeSearchSpace(filterItem[0]);
      //console.log('selectSpace2', filterItem[0]);
      left = -((filterItem[0] || {}).left || 0);
      top = -((filterItem[0] || {}).top || 0);
      var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
      var mapWrapHeight = (mapRef.current || {}).clientHeight || 0;
      //   setTranslateX(left * mscale + mapWrapWidth / 2);
      //   setTranslateY(top * mscale + mapWrapHeight / 2);
      //搜索完成
      changeSearchBuildId(''); //清空搜索记录  以防两次搜索一样的建筑的 没反应
      changeSearchFloorId(''); //清空搜索记录 以防两次搜索一样的楼层时 没反应 要不要换位置
      changeSearchText({}); //清空搜索记录 好进行一些操作
    } else if (currentFloorId.current != selFloorId) {
      //如果两次的selFloorId 不一样 才会更改地图的位置为0 0
      setTranslateX(0);
      setTranslateY(0);
    }
    currentFloorId.current = selFloorId;
    //console.log('selectSpace2');
  }, [mapList]);

  //搜索信息改变时的搜索
  useEffect(() => {
    if (searchText && searchText.text && mapList.length > 0) {
      let left: any, top: any;

      var filterItem = mapList.filter((item) => {
        return item.localName == (searchText && searchText.text);
      });
      if (filterItem.length == 0) return;
      //找到搜索的空间
      changeSearchSpace(filterItem[0]);

      //console.log('selectSpace2', filterItem[0]);
      left = -((filterItem[0] || {}).left || 0);
      top = -((filterItem[0] || {}).top || 0);
      var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
      var mapWrapHeight = (mapRef.current || {}).clientHeight || 0;

      //   setTranslateX(left * mscale + mapWrapWidth / 2);
      //   setTranslateY(top * mscale + mapWrapHeight / 2);
      changeSearchBuildId(''); //清空搜索记录  以防两次搜索一样的建筑的 没反应
      changeSearchFloorId(''); //清空搜索记录 以防两次搜索一样的楼层时 没反应 要不要换位置
      changeSearchText({});
    }
  }, [searchText]);

  useEffect(() => {
    // todo 要不要用呢
    document.querySelector('#root').addEventListener(
      'mouseup',
      function () {
        //console.log('mouseUpEvent');
        setCanMove(false);
      },
      true,
    );

    var mapDom = document.querySelector('#map');
    //console.log('document.querySelector("#map")', mapDom);
    let tscale = 1;
    mapDom.addEventListener('wheel', function (event) {
      //debugger;
      event.preventDefault();
      console.log('wheel', event);
      if (Math.abs(event.deltaX) !== 0 && Math.abs(event.deltaY) !== 0)
        return console.log('没有固定方向');
      if (event.deltaX < 0) return console.log('向右');
      if (event.deltaX > 0) return console.log('向左');
      if (event.ctrlKey) {
        if (event.deltaY > 0) console.log('向内');
        if (event.deltaY < 0) console.log('向外');
        var base = -0.009;
        if (event.deltaY > 100 || event.deltaY < -100) {
          base = -0.0006;
        }
        var mscaleTemp = mscale.current + event.deltaY * base;
        console.log('mscaleTemp', mscale.current, mscaleTemp);
        mscale.current = Math.min(Math.max(minscale, mscaleTemp), maxscale);
        changeMap(mscale.current);
      } else {
        if (event.deltaY > 0) console.log('向上');
        if (event.deltaY < 0) console.log('向下');
        // var base = -0.009;
        // if (event.deltaY > 100 || event.deltaY < -100) {
        //   base = -0.0006;
        // }
        // var mscaleTemp = mscale.current + event.deltaY * base;
        // console.log('mscaleTemp', mscale.current, mscaleTemp);
        // mscale.current = Math.min(Math.max(minscale, mscaleTemp), maxscale);
        // changeMap(mscale.current);
      }
    });
  }, []);

  //展示比例尺
  var showscale = useMemo(() => {
    return (mscale.current * 100).toFixed(0);
  }, [mscale.current]);

  useEffect(() => {
    console.log('document', document.body.offsetHeight);
    var bodyHeight = document.body.offsetHeight;
    setMapHeight(bodyHeight - 293);
  }, []);
  return (
    <div
      className={mapstyles.mapwrap}
      ref={mapRef}
      onMouseDown={(event) => {
        mouseDownEvent(event);
      }}
      onMouseUp={(event) => {
        mouseUpEvent(event);
      }}
      onMouseMove={(event) => {
        mouseMoveEvent(event);
      }}
      style={{ height: mapHeight + 'px' }}
    >
      <div
        id="map"
        className={cx(mapstyles.map, { [mapstyles.equipmentMap]: type == 'equipment' })}
        style={{
          transform: `translate(${translateX}px,${translateY}px)`,
          width: mapSize.width,
          height: mapSize.height,
        }}
      >
        {mapList.map(function (item, index) {
          return render(item, index);
        })}
      </div>
      <div className={mapstyles.mapControl}>
        <div className={cx(mapstyles.controlBar)}>
          <div>缩放比例：</div>
          <div>{showscale}/100</div>
        </div>
        <div
          className={cx(mapstyles.zoom, { [mapstyles.disable]: mscale.current >= maxscale })}
          onClick={(event) => {
            mapZoom(event);
          }}
        >
          <Icon className="" type="zoom" style={{ fontSize: 22 }}></Icon>
        </div>
        <div
          className={cx(mapstyles.zoom, { [mapstyles.disable]: mscale.current <= minscale })}
          onClick={(event) => {
            mapReduce(event);
          }}
        >
          <Icon className="" type="reduce" style={{ fontSize: 22 }}></Icon>
        </div>
      </div>
    </div>
  );
};
export default Map;
