import * as React from 'react';
import classNames from '../../utils/classnames';
import './index.css';
import * as PropTypes from 'prop-types';

// 所有绝对地址直接交由浏览器，新开窗口交由浏览器
// 当前窗口相对地址交给平台
export default function Link({
  content = '这是一个链接',
  url = '',
  events = {},
  style,
  className,
  contentSlot,
  params = [], // TODO 格式定义
}) {
  url = url.trim();
  const cls = classNames({
    'weda-link': true,
    'weda-ui': true,
    [className]: className,
  });

  // URL 构造函数不支持 '//xxx.com' 的格式
  if (url.indexOf('//') === 0) {
    url = location.protocol + url;
  }

  // "proto:" 或 "//" 起头的是绝对路径
  let isAbosolutePath = /^(?:[a-z]+:)/i.test(url);

  let base,
    path,
    href,
    paramObj = {},
    urlObj;
  if (!isAbosolutePath) {
    // 相对地址使用站位域名，不实际使用
    base =
      location.origin && location.origin !== 'null'
        ? location.origin
        : 'https://we.da';
  }

  try {
    urlObj = new URL(url, base);
    params.forEach((x) => {
      urlObj.searchParams.append(x.key, x.value);
    });

    href = urlObj.href;
    path = urlObj.pathname;

    for (const [key, value] of urlObj.searchParams) {
      paramObj[key] = value;
    }

    // 相对地址去掉站位域名
    if (!isAbosolutePath) {
      href = urlObj.pathname + urlObj.search + urlObj.hash;
      href = href.replace(/^\//, '');
    }
  } catch (e) {
    // 非法 url
    isAbosolutePath = true;
    href = url;
    path = '';
    paramObj = params.reduce((p, x) => {
      p[x.key] = x.value;
      return p;
    }, {});
  }

  return (
    <a
      style={{ ...style }}
      className={cls}
      href={href}
      onClick={(e) => {
        events.tap && events.tap({}, { originEvent: e });

        if (!e.defaultPrevented) {
          if (!isAbosolutePath) {
            e.preventDefault();
            app.navigateTo({
              pageId: path,
              packageName: '',
              mode: 'weDa',
              params: paramObj,
            });
          }
        }
      }}
      rel="noreferrer"
    >
      {contentSlot && <div className="weda-link-slot">{contentSlot}</div>}
      {content}
    </a>
  );
}
