import React from 'react';
import Taro from '@tarojs/taro';
import { View, Map } from '@tarojs/components';
import { Icon, Loading } from '@antmjs/vantui';
import { getLocation } from '@/utils/authorize';
import iconPath from '@/assets/icons/marker.png';
import style from './style.module.less';

/**
 * 这里使用2个map, 每个 map 负责不同的场景
 * 如果使用 1 个map, 通过属性去控制, 微信暂时有 bug 比如 showLocation 就有bug
 */
export default (props) => {
  const { readOnly, location, onChange } = props;

  console.log('-----map---readOnly---', readOnly, location);

  const id = React.useMemo(() => `map-${Math.random().toString(36).substring(2, 10)}`, []);
  const idReadOnly = React.useMemo(() => `map-${Math.random().toString(36).substring(2, 10)}`, []);
  const mapCtxRef = React.useRef();

  const [
    markers,
    center,
  ] = React.useMemo(() => {
    // eslint-disable-next-line no-undef
    const loc = location || DEFAULT_POS;
    const [longitude, latitude] = loc.split(',');

    const mks = readOnly ? [{
      id: 1,
      longitude,
      latitude,
      iconPath,
      width: 17,
      height: 20
    }] : [];

    return [
      mks,
      { longitude, latitude }
    ]
  }, [location, readOnly]);

  console.log('------center-------', center, location)

  const moveTo = (ctx, point) => {
    ctx.moveToLocation({
      ...point,
      fail: console.error,
    })
  }

  const getContext = React.useCallback(() => {
    const query = Taro.createSelectorQuery();
    query.select(`#${id}`).context(res => {
      mapCtxRef.current = res.context;

      // 修改中心图标 - 暂时不起作用, wx bug
      mapCtxRef.current.setLocMarkerIcon({
        iconPath,
        fail: console.error,
      })
    }).exec();
  }, [id]);

  const fixedLocation = () => {
    return new Promise((resolve) => {
      Taro.showLoading({
        title: '加载中',
      })
      getLocation({ type: 'gcj02' }).then((res) => {
        Taro.hideLoading()
        resolve(res);
      }).catch((err) => {
        console.error(err);
        Taro.hideLoading();
        Taro.showToast({
          title: '定位失败',
          icon: 'none',
        })
      });
    });
  }

  const onRefresh = () => {
    if (mapCtxRef.current) {
      fixedLocation().then((res) => {
        const { longitude, latitude } = res;
        // console.log('longitude', longitude);
        // console.log('latitude', latitude);
        onChange([res.longitude, res.latitude].join(','));
        moveTo(mapCtxRef.current, { longitude, latitude });
      })

    }
  }

  React.useEffect(() => {
    if (!readOnly) {
      getContext();

      // 获取定位
      fixedLocation().then((res) => {
        const { longitude, latitude } = res;
        onChange([longitude, latitude].join(','));
      })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [readOnly, getContext]);

  return (
    <View className={style['map-wrapper']}>
      {
        !readOnly && (
          <Map
            id={id}
            showLocation
            longitude={center.longitude}
            latitude={center.latitude}
          >
            <Icon name="aim" size="24px" onClick={onRefresh} color="#1A7565" className={style['icon']} />
          </Map>
        )
      }
      {
        readOnly && (
          <Map
            id={idReadOnly}
            longitude={center.longitude}
            latitude={center.latitude}
            markers={markers}
          />
        )
      }
    </View >
  )
}
