
import Taro from '@tarojs/taro'
import * as taroRuntime from '@tarojs/runtime';
import gdp from 'gio-miniprogram-sdk-cdp/gio-taro';
import { APPID, _GIO_CONFIG } from '../constants/app';
import { getOrCreateLocalId, getCurrentUrl } from '../utils/tools';
import { _UID } from '../constants/api';

let sessionId: string;
const appNames = {
  weapp: 'wx_mini_program',
}
// @ts-ignore
// eslint-disable-next-line no-undef
const _DOMIAN_VALUE = DOMIAN_VALUE;

const init = () => {
  // gio 埋点初始化
  gdp('init', _GIO_CONFIG.accountId, _GIO_CONFIG.dataSourceId, APPID, {
    version: '2.0.0',
    host: _GIO_CONFIG.host,
    taro: taroRuntime,
    debug: false,
    compress: false,
    hashtag: false,
    enableIdMapping: true,
    autotrack: false, // 开启埋点功能需先集成 babel-plugin-setname 插件，具体请看 babel.config.js
    followShare: false,
  });
};

const getSessionId = () => {
  if (sessionId) {
    return sessionId
  } else {
    sessionId = Math.random().toString(16).substr(2, 8) + Math.random().toString(36).substr(2, 4) + Math.random().toString(36).substr(2, 8);
    return sessionId
  }
};

const getEventId = (data) => {
  if (data.eventId) {
    return data.eventId;
  }
  if (data.pageId && data.buttonId) {
    return `XCX_${data.pageId}_${data.buttonId}`;
  }
  return 'XCX_default_eventId';
}

const send = async (option) => {
  const $app: any = Taro.getApp().$app;
  const { openId, unionId } = await $app.getIdData() || {};
  const uid = Taro.getStorageSync(_UID) || '-1';
  const ENV = process.env.TARO_ENV;
  // 获取本地的设备码，无则随机生成一个
  const di = await getOrCreateLocalId();
  // 组装计算XP-Client
  let si:any = {}
  if(ENV === 'xhs') {
    // @ts-ignore
    si = xhs.getSystemInfoSync() || {}
  } else {
    si = Taro.getSystemInfoSync() || {}; // 此处如果断网情况下会返回 undifined
  }
  const accountInfo: any = ENV === 'weapp' ? Taro.getAccountInfoSync() || {} : {};

  const properties = {
    ...option.para,
    pageId: option.pageId,
    buttonId: option.buttonId,
  };
  const eventId = getEventId(option);
  delete properties.eventId;

  const commonParams = {
    'device': openId || '', //设备唯一ID 兴爷说改成openid
    'brand': si.model, //手机品牌
    'model': si.model, //手机机型
    'sys_ver': si.system, //系统版本号
    'app_ver': accountInfo.miniProgram ? accountInfo.miniProgram.version : '',  // 应用版本号
    'platform': si.platform.includes('ios') ? 2 : 1, //平台
    'app_phase': _DOMIAN_VALUE,
    't': +new Date(),
    'app_name': appNames[ENV],
    'package_name': appNames[ENV],
    'position': `${Taro.getStorageSync('longitude')},${Taro.getStorageSync('latitude')}`, //  之前位置都是拿了直接用的，没有缓存到内存里，待收集
    'service_name': 'mini_program',
  }

  // 事件参数
  const eventParams = {
    'user_id': uid,
    'session_id': getSessionId(),
    'page_id': properties.pageId,
    'button_id': properties.buttonId,
    openid: openId,
    nls: di,
    unionID: unionId,
    scene: await $app.getScene(),
    url_all: getCurrentUrl(),
  };

  gdp('track', eventId, { ...commonParams, ...eventParams, ...properties });
};

const timpObj: any = {}

const show = () => {
  const pages = Taro.getCurrentPages();
  const page = pages[pages.length - 1]
  timpObj[page ? page.route : 'null'] = +new Date();
  send({ pageId: 'P10040', buttonId: 'B001', para: { url: page && page.route, ref: pages.length > 1 ? pages[pages.length - 2] ? pages[pages.length - 2].route : pages : '' } })
}

const hide = () => {
  const pages = Taro.getCurrentPages();
  const page = pages[pages.length - 1]
  send({ pageId: 'P10040', buttonId: 'B002', para: { url: page.route, duration: +new Date() - timpObj[page.route] } })
}

/**
 * 为了配合数据中台统计数据，每次登录时使用gdp('setUserId', id)来上报用户id
 */
const loginReport = (id) => {
  if (id) {
    gdp('setUserId', id)
  }
}

const logoutClearReport = () => {
  gdp('clearUserId');
}

export default {
  init,
  send,
  show,
  hide,
  getSessionId,
  loginReport,
  logoutClearReport
}
