import React, { useRef, useEffect, useState } from 'react';
import { MapBox, Marker } from '@zhst/map';
import { Button, Input, Space } from '@zhst/meta';
import { MarkerProps } from '../components/marker';
import { getDistancesByStringLine, lineToPoly } from '../utils';
// import { sluterData } from './.data/mock.ts'

const demo = () => {
  const [markerData, setMarkerData] = useState<MarkerProps[]>([])
  const [showMarker, setShowMarker] = useState(true)
  const [showCluster, setShowCluster] = useState(true)
  const [canDraw, setCanDraw] = useState(false)
  const [toolsBarOpen, setToolsBarOpen] = useState(false)
  const [popupInfo, setPopupInfo] = useState()
  const [sluterData, setSluterData] = useState({})
  const [showMouseTag, setShowMouseTag] = useState(false)
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 })
  const [rangingList, setRangingList] = useState([])
  const mapRef = useRef(null);
  const [token, setToken] = useState('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTczMDA4NTIsImp0aSI6IjExNTkiLCJpYXQiOjE3MTcwNDE2NTIsInVzZXJJZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImRhdGFSaWdodCI6MiwiY2FtZXJhUmlnaHQiOjEsImdwdVJpZ2h0IjoxLCJ1c2VybGVhZGVySWQiOjAsIm9yZ2FuaXphdGlvbklkIjoxLCJyb2xlSWQiOjF9.n9b_jcvzyehu2vmZF6ZrFM4Vz7h7Xr2GCf9p7muGTBE')

  // 初始化
  const handleMapLoad = (e: mapboxgl.MapboxEvent<undefined>) => {
    const map = e.target;

    if (!map) return

    map.flyTo({
      // center: [120,30],
      // zoom: map?.getMaxZoom(),
    });
  };

  const getData = async ({ url = 'http://10.0.0.120:30003/singer.DeviceService/ListCamera', token }: { url?: String, token: string }) => {
    let res = await fetch(
      url,
      {
      method: 'post',
      headers: {
        Authorization: token
      },
      data: {"labelData":[],"filter":{"realtimeProcessingFilter":0,"cameraFilter":[{"opt":"ORNOT","cameraOpt":"CAMERAOPT_TYPE","value":"100"}]},"maxResults":50}
    });
    const data = await res.json()
    if  (res.status === 200) {
      let markers = []
      let sluters = {
        features: []
      }
      data.cameras?.forEach(camera => {
        markers.push({
          key: camera.id,
          id: camera.id,
          title: camera.name,
          population: camera.id,
          checked: false,
          disabled: false,
          showCheckBox: true,
          status: ['blue', 'yellow', 'red'][Math.floor(Math.random() * 3)],
          latitude: camera.latitude,
          longitude: camera.longitude
        })
        sluters.features.push({
          "geometry": {
            "type": "Point",
            "coordinates": [
                camera.longitude,
                camera.latitude,
                50
            ]
          }
        })
      })
      setMarkerData(markers)
      setSluterData(sluters)
    }
  }

  return (
      <div>
        <Space style={{ marginBottom: '12px' }}>
          获取摄像头位置：
          <Input onChange={e => setToken(e.target.value)} value={token} />
          <Button onClick={() => getData({ token })} >请求</Button>
        </Space>
        <MapBox
          onLoad={handleMapLoad}
          ref={mapRef}
          draw={canDraw}
          toolsBarOpen={toolsBarOpen}
          onToolClick={e => {
            setCanDraw(pre => !pre)
            setToolsBarOpen(pre => !pre)
          }}
          onDrawCreate={e => {
            const geojson = e.features[0]
            const polygonJson = getDistancesByStringLine(geojson) || []
            setRangingList(polygonJson.distanceArr)
          }}
          onDrawDelete={e => console.log('Delete', e)}
          onDrawUpdate={e => {
            const geojson = e.features[0]
            const polygonJson = getDistancesByStringLine(geojson) || []
            setRangingList(polygonJson.distanceArr)
          }}
          width='100%'
          height='100vh'
          mapStyle={{
            sources: {
              'osm-tiles': {
                'type': 'raster',
                tiles: [`http://10.0.1.231:30003/map/api/tilesets/mapfile/{z}/{x}/{y}.png`], //在线地址，先写死120
              }
            },
          }}
          markerData={markerData || []}
          showMarker={showMarker}
          showPopUp
          sluterData={sluterData}
          showCluster={showCluster}
          // popUpInfo={popupInfo}
          onPopUpClose={e => setPopupInfo(null)}
          onMarkerCheck={(e, status, data) => {
            setMarkerData(pre => pre.map(item => {
              if (item.id === data.id) {
                item.checked = !data?.checked
              }
              return item
            }))
          }}
          onZoomEnd={map => {
            let zoom = map.target.getZoom()   // 画面层级，用来判断标签是否显示隐藏
            // 摄像头显示/隐藏
            setShowMarker(zoom > 5)
            // 范围统计显示/隐藏
            setShowCluster(zoom < 5)
          }}
          onClick={e => setShowMouseTag(true)}
          onDblClick={e => {
            setShowMouseTag(false)
            // setCanDraw(false)
          }}
          onMouseMove={e => {
            setMousePosition({ x: e.point.x, y: e.point.y })
          }}
          // customMarkerRender={(_data) => <div>自定义标记</div>}
        >
          {canDraw && (
            <div
              style={{
                position: 'absolute',
                fontSize: '16px',
                top: mousePosition.y,
                left: mousePosition.x,
                pointerEvents: 'none'
              }}
            >{showMouseTag ? '双击完成绘制' : '单击以确定起点'}</div>
          )}
          {rangingList?.map((item, index) => {
            return (
              <Marker
                key={item.to[0] || index}
                anchor="bottom"
                longitude={item.to[0]}
                latitude={item.to[1]}
                onClick={e => e.originalEvent.stopPropagation()}
              >
                <div style={{ padding: '3px 6px', background: '#fff', border: '1px solid #000' }} >{(item.totalLength)}km</div>
              </Marker>
            )
          })}
          <Marker
            anchor="bottom"
            longitude={120}
            latitude={31}
            onClick={e => {
              e.originalEvent.stopPropagation();
            }}
          >
            <div style={{ padding: '12px', background: 'red', color: '#fff', border: '1px solid #000' }} >我是自定义的DOM！</div>
          </Marker>
        </MapBox>
      </div>
  );
};

export default demo;
