import { getUrlParameter, formatUrl } from '@common/js/utils';
import { get } from '@service/http';
import { getShortLink } from '@apis/common';
import Promise from 'promise-polyfill';

require('./tmjssdk');
const jsBridge = window.TMJSBridge;

const bridge = Object.assign({}, jsBridge, {
  /**
   * 端内h5分享
   * @param params {
   * shareType：0：// 弹窗不带预
   * 览 1：弹窗带预览 2：直接分享
   * needDraw：0：不画 1：画
   * channel：参考下文channel 分享渠道
   * toastText:分享成功提示文本
   * bigImgUrl: 大图url // 区分卡片分享
   * imgUrl: 分享的图片
   * desc: 描述
   * shareUrl:分享链接
   * title:标题
   * qRCodePoint: 二维码坐标 
   * {
  *   "height": 10,
      "leftTopX": 10,
      "leftTopY": 10,
      "width": 10
   * }
   * HOOK:{    钩子函数
   * beforeCallBridge（shareData） //  bridge调用前触发，参数为分享数据,有异步操作时，必须返回Promise
   * }
   */

  h5Share: async function({
    shareType = 1,
    needDraw = 0,
    channel = 2,
    toastText = '',
    bigImgUrl,
    imgUrl,
    desc,
    shareUrl,
    title,
    qRCodePoint,
    id,
    host, // share接口的hostname
    type, // contentType
    urlParams = {},
    callback = () => {},
    HOOK = {
      // beforeGetInfo() {},
      // insert() {},
      beforeCallBridge() {},
    },
  }) {
    console.log('h5Share');
    // 获取后台配置的分享信息,获取成功后再调起app分享
    let shareData = await getAppShareInfo({ id , type, host});
    console.log('start share');
    let params = { shareType, needDraw, channel, toastText };
    // shareContentType 0: 链接 1:图片
    if (shareData.shareContentType === 1) {
      if (bigImgUrl) {
        params.imgUrl = bigImgUrl;
      } else {
        console.log('使用默认大图');
      }
      if (qRCodePoint) {
        params.qRCodePoint = qRCodePoint;
      }
    } else {
      if (imgUrl) {
        params.imgUrl = imgUrl;
      }
      if (desc) {
        params.desc = desc;
      }
      if (shareUrl) {
        params.shareUrl = shareUrl;
      }
      if (title) {
        params.title = title;
      }
    }

    // 在分享出去的URL上拼接业务参数
    console.log(urlParams, "urlParams");
    shareData.shareUrl = formatUrl(shareData.shareUrl, urlParams);

    let _params = Object.assign({}, shareData, params);
    console.log('do share');

    // 8.31 app 端移除needDraw判断，不需要客户端绘制二维码时需要设置qRCodePoint为null
    if (_params.needDraw === 0) {
      _params.qRCodePoint = null;
    }

    await HOOK.beforeCallBridge(_params);

    console.log(shareData.shareUrl, "shareData.shareUrl");

    _params = { sharedata: JSON.stringify(_params) };
    
    console.log(_params);
    jsBridge.share(_params, callback);
  },

  /**
   *  端内埋点
   */
  track: function(type, data, callback = () => {}) {
    let _params = Object.assign({}, { type: type }, data);
    jsBridge.maidian({ params: _params }, callback);
  },

  testShare: function(params, callback = () => {}) {
    console.log('testshare');
    jsBridge.share({ sharedata: JSON.stringify({}) }, callback);
  },
});

function transformShareData(origin) {
  let newData = {
    desc: origin.wxShareInfo || '',
    imgUrl: origin.wxShareImg || '',
    qRCodePoint: origin.qRCodePoint || {
      height: 10,
      leftTopX: 10,
      leftTopY: 10,
      width: 10,
    },
    shareContentType: origin.shareContentType === 0 || origin.shareContentType === 1 ? origin.shareContentType : '',
    shareUrl: origin.shareUrl || '',
    title: origin.wxShareTitle || '',
    contentId: origin.id || getUrlParameter('id'),
    contentType: origin.type || getUrlParameter('type'),
    shareContentIndex: origin.shareContentIndex,
  };
  return newData;
}

/**
 * 获取app分享信息
 */
function getAppShareInfo(params) {
  return new Promise((resolve, reject) => {
    get(`${params.host ? params.host  : ''}/youtui/content/share`, {
      contentId: params.id || getUrlParameter('id'),
      contentType: params.type || getUrlParameter('type'),
      shareFrom: 1, // 固定为1 点击分享来源（0：app卡片；1：预览页）
    })
      .then(result => {
        let shareData = transformShareData(result);
        params.id && (shareData.id = params.id);
        params.type && (shareData.type = params.type);
        resolve(shareData);
      })
      .catch(err => {
        reject();
        console.error(err);
      });
  });
}

export default bridge;

