/**
 * Created by rockyl on 2018-12-26.
 *
 * 埋点按钮
 */
import InteractComponent from "components/base/InteractComponent";
import {callApi} from "../net/webService";
import {engine} from "scilla";

export default class BuriedPoint extends InteractComponent {
	dpm: string;
	dcm: string;

	private _buriedPointName: string;
	private _exposured: boolean;

	onCreate() {
		super.onCreate();

		if (this.dpm && this.dcm && !this._exposured) {
			this.setConfig(this.dpm, this.dcm, true);
		}
	}

	onTouchTap(e) {
		super.onTouchTap(e);

		if (this._buriedPointName) {
			logClick(this._buriedPointName);
		}
	}

	setConfig(dpm, dcm, needLogExposure = false) {
		this._buriedPointName = 'buried-point-' + Date.now() + Math.floor(Math.random() * 999999);
		addBuriedPointConfig(
			this._buriedPointName,
			{dpm, dcm}
		);

		if (needLogExposure) {
			logExposure(this._buriedPointName);
			this._exposured = true;
		}
	}
}

let _buriedPoints: any = {};
let env: any;

export function initEnv() {
	const cfg = engine.dataCenter.get('CFG');
	env = {
		app_id: cfg.appId,
		oaid: cfg.opActivityId,
		page_id: 3,
		comp_id: 4,
	}
}

export function addBuriedPoints(buriedPoints) {
	for (let name in buriedPoints) {
		_buriedPoints[name] = buriedPoints[name];
	}
}

export function addBuriedPointConfig(name, config) {
	const {dpm, dcm} = config;
	_buriedPoints[name] = new BuriedPointData(dpm, dcm);
}

export function addBuriedPointConfigs(configs) {
	for (let name in configs) {
		addBuriedPointConfig(name, configs[name]);
	}
}

export function logExposure(name) {
	return log(name, 'exposure');
}

export function logClick(name) {
	return log(name, 'click');
}

function log(name, type) {
	if (DEBUG) {
		//return;
	}

	let logPoint = _buriedPoints[name];

	let appId = engine.dataCenter.get('CFG', 'appId');
	let {dpm, dcm} = logPoint;

	return callApi(   //todo 埋点
		type == 'exposure' ? '//embedlog.duiba.com.cn/exposure/standard' : '/log/click',
		{
			dpm, dcm, appId
		},
		'get', type == 'exposure' ? 'jsonp' : 'json'
	).catch(e => {
		//console.log(e);
	});
}

function fillData(src) {
	let result = src;
	for (let key in env) {
		result = result.replace(key, env[key]);
	}
	return result;
}

class BuriedPointData {
	dpm: string;
	dcm: string;

	constructor(dpm, dcm) {

		this.dpm = fillData(dpm);
		this.dcm = fillData(dcm);
	}
}
