import getWeather from '@/components/AMap/weather';
// import GeoMap from '@/components/GeoMap';
import ScreenHeader from '@/components/ScreenBox/ScreenHeader';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { getDeviceMachineryList } from '@/services/monitoringScreen';
import { regeo } from '@/components/AMap/service';
import { useParticlesJs } from './hook';
import Map from './components/map';
import Banner from './components/Banner';
import DeviceList from './components/DeviceList';
import DeviceType from './components/DeviceType';
import makeMachinery from './components/machinery';
import MachineryInfo from './components/MachineryInfo';
import Styles from './style.less';

export default (props) => {
  const screenRef = useRef();
  const mapRef = useRef();
  const aMapRef = useRef();
  const [mapReady, setMapReady] = useState(false);
  const [weather, setWeather] = useState('暂无天气信息');
  const [machines, setMachines] = useState([]);
  const machineMarkers = useRef([]);
  const [deviceType, setDeviceType] = useState();
  const [curMachine, setCurMachine] = useState();
  const curPos = useRef();
  const infoWinRef = useRef();

  const onMapReady = (map, AMap) => {
    mapRef.current = map;
    aMapRef.current = AMap;
    setMapReady(true);
  };

  useEffect(() => {
    if (mapReady) {
      makeMachinery(
        machines,
        machineMarkers.current,
        mapRef.current,
        aMapRef.current,
        (machine, position) => {
          // 创建信息窗体
          setCurMachine({ ...machine });
          curPos.current = position;
        },
      );
    }
  }, [mapReady, machines]);

  useEffect(() => {
    if (mapReady) {
      const map = mapRef.current;
      const AMap = aMapRef.current;

      if (curMachine) {
        const infoWindow = new AMap.InfoWindow({
          isCustom: true, //使用自定义窗体
          content: infoWinRef.current,
          offset: new AMap.Pixel(0, -45),
        });

        infoWindow.on('close', () => {
          map.clearInfoWindow();
        });

        infoWindow.open(map, curPos.current);
      } else {
        map.clearInfoWindow();
      }
    }
  }, [curMachine, mapReady]);

  useEffect(() => {
    const params = deviceType ? { deviceType } : undefined;
    getDeviceMachineryList(params).then((res) => {
      const locIds = [];
      const locList = [];
      const list = res || [];

      for (let item of list) {
        if (item.location && item.location.indexOf('0.0') === -1) {
          locIds.push(item.machineryId);
          locList.push(item.location);
        }
      }

      if (locList.length > 0) {
        // 高德接口, 请求地址的描述
        regeo({ location: locList.join('|') })
          .then((regs) => {
            if (regs.status === '1') {
              regs.regeocodes.forEach((addrs, inx) => {
                const addr = addrs['formatted_address'];
                const addressComponent = addrs.addressComponent;
                const machine = list.filter((x) => x.machineryId === locIds[inx])[0];
                machine.loc = addr.replace(addressComponent.province, ''); // 去掉省
              });
            }

            setMachines(list);
          })
          .catch((er) => {
            console.error(er);

            setMachines(list);
          });
      }
    });
  }, [deviceType]);

  useEffect(() => {
    getWeather()
      .then((res) => {
        if (res && res.length) {
          const { casts, city } = res[0];
          const { dayweather, nighttemp, daytemp } = casts[0];
          const [min, max] =
            parseInt(nighttemp) > parseInt(daytemp) ? [daytemp, nighttemp] : [nighttemp, daytemp];
          setWeather(`${city} ${dayweather} ${min}-${max} °C`);
        } else {
          setWeather('暂无天气信息');
        }
      })
      .catch((err) => {
        console.log(err.message);
      });
  }, []);

  useParticlesJs(Styles['particles-js']);

  return (
    <div className={classNames(Styles['screen-page'], Styles['pd-lr-40'])} ref={screenRef}>
      <div id={Styles['particles-js']} />
      <div className={Styles['grail-layout']}>
        <div className={Styles['grail-header']}>
          <ScreenHeader weather={weather} />
        </div>
        <div className={classNames(Styles['grail-container'], Styles['mg-tp-30'])}>
          <div className={classNames(Styles['grail-content'], Styles['pd-lr-40'])}>
            <div className={Styles['statis-container']}>
              <Banner />
            </div>
            <Map onReady={onMapReady}>
              <div
                className={Styles['map-addon']}
                style={{
                  top: '60px',
                  left: '60px',
                  width: '120px',
                }}
              >
                <DeviceType onChange={setDeviceType} />
              </div>
            </Map>
          </div>
        </div>
      </div>
      <div style={{ position: 'absolute', zIndex: -1 }}>
        <MachineryInfo
          data={curMachine}
          ref={infoWinRef}
          onClose={() => {
            mapRef.current.clearInfoWindow();
          }}
        />
      </div>
    </div>
  );
};
