import * as React from 'react';
import { Props, State } from './type';
import styled from 'styled-components'
import {setOrUpdate} from 'nw-share';
import {isSnail} from 'snail-helpers';
import {callHandler} from 'nejsbridge/dist/bridge.snail.es';
import {getLogInstance} from 'snail-log';

import { removeImgQuery } from '../utils/imgResize'

const isSnailOnline = location.host === 'du.163.com'

const ShareContainer = styled.div`
  ${
  props => !props.isEdit && 'position: absolute!important;left: -9999px!important;top: -9999px!important;'
  }
`

let shareData = null;
export const getShareData = () => {
  return shareData;
};

export class Share extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  componentDidMount(){
    let {
      title = '',
      description = '',
      activityId = new Date().getTime().toString(),
      picurl = {url: 'https://wx2.sinaimg.cn/square/7d25d640ly1g79i81d2x7j202s02sa9y.jpg'},
      lofterPic,
      text,
      link = location.href,
      isEdit,
      notSetTitle,
      notSetShare,
    } = this.props;
    if(!isEdit){
      //增加蜗牛打点组件的初始化
      if(isSnailOnline){
        getLogInstance();
      }
      let docTitle = this.props.docTitle || title;
      if (!notSetTitle) {
        document.title = docTitle;
      }
      if (notSetShare) return; 
      if(isSnail()){
        callHandler('setTitle', {
          title: docTitle
        })
      }
      // 未设置分享标题时默认使用页面标题
      if (!title) {
        title = document.title;
      }
      if (!text) {
        text = title;
      }
      let shareValue: any = {
        title,
        description,
        activityId,
        picurl: removeImgQuery(picurl?.url) + '?imageView&thumbnail=200y200',
        text,
        link
      };
      if (lofterPic && lofterPic.url) {
        shareValue.lofter = {
          img: lofterPic.url,
          title,
          desc: description
        }
      }
      shareData = shareValue;
      console.log('分享模块配置保存', shareData);
      setOrUpdate(shareValue)
    }
  }

  render() {
    const {style, isEdit} = this.props;
    return (
      <ShareContainer style={style} isEdit={isEdit}>{
        isEdit && '分享配置，只在编辑器中展示，实际页面中不显示'
      }</ShareContainer>
    )
  }
}
