import React, { useState, useEffect, useRef, useMemo, useCallback } 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;
  maxscale: number;
  transXInit: number;
};

const Map: React.FC<MapProps> = ({
  type,
  selFloorId,
  render,
  mapList,
  changeMapList,
  mapSize,
  maxscale,
  transXInit,
}) => {
  //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>(120);

  //const [mscale, setMscale] = useState<number>(1);
  const mscale = useRef<number>(1);
  //最大的缩放比例

  const [minscale, setMinscale] = useState<number>(0.6);
  const [canMove, setCanMove] = useState<boolean>(false);

  const [moveTop, setMoveTop] = useState<number>(0); //地图的块的top的改变
  const [moveLeft, setMoveLeft] = useState<number>(0);
  const [mapHeight, setMapHeight] = useState(500);
  const [mapWidth, setMapWidth] = useState(1340);
  const [marginLeft, setMarginLeft] = useState(0);

  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 = useCallback(
    (event: React.MouseEvent) => {
      //debugger;
      if (canMove) {
        let nowPageX = event.pageX;
        let nowPageY = event.pageY;

        // moveTop
        //moveLeft
        var mapwidth = mapSize.width * mscale.current;
        var mapheight = mapSize.height * mscale.current;
        var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
        var mapWrapHeight = (mapRef.current || {}).clientHeight || 0;

        //console.log('-translateY + moveTop', moveTop, translateY, -translateY + moveTop, mapheight);
        if (-translateX + moveLeft > mapwidth - 220) {
          //不能再往左 translateX  < -mapwidth + 220+moveLeft
          //console.log('zuozuozuo');
        }
        if (-translateY + moveTop > mapheight - 220) {
          //不能再往上   translateY  < -mapheight + 220+moveTop
          //console.log('shangshang');
        }

        if (translateX - moveLeft > mapWrapWidth - 220) {
          //不能再往右  translateX > mapWrapWidth - 220+moveLeft
          //console.log('youyou');
        }

        if (translateY - moveTop > mapWrapHeight - 220) {
          //不能再往下  translateY   > mapWrapHeight - 220+moveTop
          //console.log('xiaxia');
        }
        var nowTranslateX = translateX + nowPageX - startPageX;
        var nowTranslateY = translateY + nowPageY - startPageY;
        //不能让地图太靠左边 看不到
        nowTranslateX =
          nowTranslateX < -mapwidth + 250 + moveLeft ? -mapwidth + 250 + moveLeft : nowTranslateX;
        //不能让地图太靠右边 看不到
        nowTranslateX =
          nowTranslateX > mapWrapWidth - 250 + moveLeft
            ? mapWrapWidth - 250 + moveLeft
            : nowTranslateX;
        nowTranslateY =
          nowTranslateY < -mapheight + 250 + moveTop ? -mapheight + 250 + moveTop : nowTranslateY;

        nowTranslateY =
          nowTranslateY > mapWrapHeight - 220 + moveTop
            ? mapWrapHeight - 220 + moveTop
            : nowTranslateY;

        setTranslateX(nowTranslateX);
        setTranslateY(nowTranslateY);

        //console.log('mouseMoveEvent-xx', translateX, nowPageX, startPageX);
        // console.log('mouseMoveEvent-yy', translateY, nowPageY, startPageY);

        setStartPageX(event.pageX);
        setStartPageY(event.pageY);
      }
    },
    [mapSize, translateX, translateY, moveLeft, moveTop, canMove, startPageX, startPageY],
  );

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

    var mscaleTemp: number = Number((mscale.current + 0.1).toFixed(4));
    mscale.current = Math.min(mscaleTemp, maxscale);
    console.log('mscale.current', mscale.current, maxscale, minscale);
    var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
    var mapWrapHeight = (mapRef.current || {}).clientHeight || 0;
    var moveWidth = (mapWrapWidth * (mscale.current - 1)) / 2;
    var moveHeight = (mapWrapHeight * (mscale.current - 1)) / 2;
    setMoveTop(moveHeight);
    setMoveLeft(moveWidth);
    changeMap(mscale.current, moveWidth, moveHeight);
    //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);

    var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
    var mapWrapHeight = (mapRef.current || {}).clientHeight || 0;
    var moveWidth = (mapWrapWidth * (mscale.current - 1)) / 2;
    var moveHeight = (mapWrapHeight * (mscale.current - 1)) / 2;
    setMoveTop(moveHeight);
    setMoveLeft(moveWidth);
    changeMap(mscale.current, moveWidth, moveHeight);
    // }
  };
  function changeMap(scale, moveWidth, moveHeight) {
    changeMapList(scale, moveWidth, moveHeight);
  }
  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 + mapWrapWidth / 2);
      setTranslateY(top + mapWrapHeight / 2);
      mscale.current = 1;
      //搜索完成
      changeSearchBuildId(''); //清空搜索记录  以防两次搜索一样的建筑的 没反应
      changeSearchFloorId(''); //清空搜索记录 以防两次搜索一样的楼层时 没反应 要不要换位置
      changeSearchText({}); //清空搜索记录 好进行一些操作
    } else if (currentFloorId.current && currentFloorId.current != selFloorId) {
      //如果两次的selFloorId 不一样 才会更改地图的位置为0 0
      setTranslateX(transXInit);
      setTranslateY(120);
      mscale.current = 1;
    }
    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 + mapWrapWidth / 2);
      setTranslateY(top + mapWrapHeight / 2);

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

  const mapWheel = useCallback(
    (event) => {
      event.preventDefault();
      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) {
        //ctrlKey为true 双指的方向不一致
        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, minscale, maxscale);
        mscale.current = Math.min(Math.max(minscale, mscaleTemp), maxscale); //缩放倍率赋值
      } 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);
      }

      var mapWrapWidth = (mapRef.current || {}).clientWidth || 0;
      var mapWrapHeight = (mapRef.current || {}).clientHeight || 0;
      //为了让地图在 屏幕中间缩放
      var moveWidth = (mapWrapWidth * (mscale.current - 1)) / 2;
      var moveHeight = (mapWrapHeight * (mscale.current - 1)) / 2;
      setMoveTop(moveHeight);
      setMoveLeft(moveWidth);

      changeMap(mscale.current, moveWidth, moveHeight);
    },
    [maxscale],
  );

  useEffect(() => {
    // todo 要不要用呢
    document.querySelector('#root').addEventListener(
      'mouseup',
      function () {
        //console.log('mouseUpEvent');
        setCanMove(false);
      },
      true,
    );
  }, []);
  useEffect(() => {
      //赋值传过来的初始 translateX 为了横向局中
    setTranslateX(transXInit);
  }, [transXInit]);

  useEffect(
    function () {
      var mapDom = document.querySelector('#map');
      //console.log('document.querySelector("#map")', mapDom);
      console.log('maxscalemaxscalemaxscale', maxscale);
      //控制板的事件
      // if (maxscale > 1) {
      mapDom.addEventListener('wheel', mapWheel);
      // }
      return () => {
        //console.log('maxscalemaxscalemaxscale------', maxscale);
        mapDom.removeEventListener('wheel', mapWheel);
      };
    },
    [maxscale],
  );
  //展示比例尺
  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 - 190);
    var bodyWidth = document.body.offsetWidth;
    setMapWidth(bodyWidth);
    setMarginLeft(-(bodyWidth - 1340) / 2); //1340 是固定宽度值
  }, []);

  return (
    <div
      className={mapstyles.mapwrap}
      ref={mapRef}
      onMouseDown={(event) => {
        mouseDownEvent(event);
      }}
      onMouseUp={(event) => {
        mouseUpEvent(event);
      }}
      onMouseMove={mouseMoveEvent}
      style={{
        height: mapHeight + 'px',
        width: mapWidth + 'px',
        marginLeft: marginLeft + '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,
        }}
        // onWheel={(event) => {
        //   //event.stopPropagation();
        //   //event.preventDefault();
        //   mapWheel(event);
        // }}
      >
        {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={mapReduce}
        >
          <Icon className="" type="reduce" style={{ fontSize: 22 }}></Icon>
        </div>
      </div>
    </div>
  );
};
export default Map;
