import { Map } from '@tarojs/components';
import Taro from '@tarojs/taro';

import { useCallback } from 'react';

import BaseMessage, { IUserMessageProps } from '@/components/message-chat/base';
import { ILocationMessage } from '@/types/message';
import { safeJsonParse } from '@/utils/common';
import Toast from '@/utils/toast';

import './index.less';

interface IProps extends IUserMessageProps {}

const PREFIX = 'location-message';

function LocationMessage(props: IProps) {
  const { message } = props;
  const data = safeJsonParse<ILocationMessage>(message.actionObject, null);

  const handleClickMap = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation();
      Taro.openLocation({
        name: data.name,
        address: data.address,
        longitude: Number(data.longitude),
        latitude: Number(data.latitude),
        scale: 18,
      });
    },
    [data]
  );

  if (!data) {
    return null;
  }

  return (
    <BaseMessage {...props}>
      <div className={`${PREFIX}__map-container`} onClick={handleClickMap}>
        <div className={`${PREFIX}__name`}>{data.name}</div>
        <div className={`${PREFIX}__address`}>{data.address}</div>
        <Map
          scale={15}
          enableZoom={false}
          enableScroll={false}
          className={`${PREFIX}__map`}
          latitude={Number(data.latitude)}
          longitude={Number(data.longitude)}
          markers={[
            {
              id: 0,
              latitude: Number(data.latitude),
              longitude: Number(data.longitude),
              iconPath: '',
              width: 20,
              height: 28,
            },
          ]}
          onError={() => Toast.error('地图加载错误')}
        />
        <div className={`${PREFIX}__mask`} onClick={handleClickMap} />
      </div>
    </BaseMessage>
  );
}

export default LocationMessage;
