/* @charset "UTF-8" */
/**
 * 区间统计对象
 * 
 * @param {Object} params
 * 
 */
var IntervalStatData	= function ()
{
	var self	= this;
	
	/**
	 * 同花顺客户端Quote对象
	 */
	var _thsQuote;
	
	/**
	 * 同花顺客户端Util对象
	 */
	var _util;
	
	/**
	 * 客户端数据项对象
	 */
	var _clientDataItem;
	
	/**
	 * 区间开始时间
	 */
	var _beginTime;
	
	/**
	 * 区间结束时间
	 */
	var _endTime;
	
	/**
	 * 当前代码
	 */
	var _code;
	
	/**
	 * 股票市场类别
	 */
	var _stockType;
	
	/**
	 * 当前包含市场的股票代码
	 */
	var _marketCode;
	
	/**
	 * 当前周期
	 */
	var _period;
	
	/**
	 * 小数位数
	 */
	var _codeDecimal;
	/**
	 * 获取开始时间
	 */
	self.getBeginTime	= function ()
	{
		return formatTime(_beginTime);
	};
	
	/**
	 * 获取原始开始时间
	 */
	self.getOriginalBeginTime	= function ()
	{
		return _beginTime;
	};
	
	/**
	 * 设置开始时间
	 */
	self.setBeginTime	= function (beginTime)
	{
		_beginTime = beginTime;
	};
	
	/**
	 * 获取结束时间
	 */
	self.getEndTime	= function ()
	{
		return formatTime(_endTime);
	};
	
	/**
	 * 获取原始结束时间
	 */
	self.getOriginalEndTime	= function ()
	{
		return _endTime;
	};
	
	/**
	 * 设置结束时间
	 */
	self.setEndTime	= function (endTime)
	{
		_endTime = endTime;
	};
	
	/**
	 * 获取周期个数
	 */
	self.getPeriodNum = function()
	{
		var params = {
				begintime	: _beginTime,
				endtime		: _endTime
		};
		return _thsQuote.getPeriodNum(params);
	};
	
	var formatTime	= function (time)
	{
		if (_period < 16384) {
			var year	= Math.floor(time / Math.pow(2, 20));
			var month	= Math.floor((time - year * Math.pow(2, 20)) /  Math.pow(2, 16));
			month		= month < 10 ? '0' + month : month;
			var day		= Math.floor((time - year * Math.pow(2, 20) - month * Math.pow(2, 16)) /  Math.pow(2, 11));
			day			= day < 10 ? '0' + day : day;
			var hour	= Math.floor((time - year * Math.pow(2, 20) - month * Math.pow(2, 16) - day * Math.pow(2, 11)) / Math.pow(2, 6));
			hour		= hour < 10 ? '0' + hour : hour;
			var minute	= time % Math.pow(2, 20) % Math.pow(2, 16) % Math.pow(2, 11) % Math.pow(2, 6);
			minute		= minute < 10 ? '0' + minute : minute;
			if (_period == 8192) {
				return month + '-' + day + ' ' + hour + ':' + minute;
			} else {
				return (year - 100) + '-' + month + '-' + day + ' ' + hour + ':' + minute;
			}
		} else {
			time	+= '';
			return time.substr(0, 4) + '-' + time.substr(4, 2) + '-' + time.substr(6, 2);
		}
	};
	
	/**
	 * 获取区间统计的数据（区间统计内可以直接获取的数据）
	 * @param {Object} dataItems 要获取的数据项
	 */
	self.getData		= function (dataItems)
	{
		var data	= {};
		for (var i in dataItems) {
			var item	= dataItems[i];
			var v	= getData(item);
			if (v != undefined) {
				data[item]	= v;
			}
		}
		
		return data;
	};
	
	/**
	 * 获取区间统计大盘行业涨跌幅
	 * @param {function} callback 回调函数
	 */
	self.getDpHyZdf	= function (callback)
	{
		var getDpHy = _thsQuote.getIndexAndIndustry(_marketCode);
		var dpHyArr = getDpHy.split('|');
		dpHyArr[1] = dpHyArr[1].substring(1);
		dpHyStr = dpHyArr.toString();
		
		if (_period == 8192) {
			var reqObj = {
				code		: dpHyStr,
				type		: 'new',
				period		: _period,
				time		: _endTime,
				begin		: _beginTime,
				end			: _endTime,
				onready		: function(){
					// 获取大盘行业区间起始价
					var param = {
						code		: dpHyStr,
						period		: _period,
						time		: _beginTime,
						mode		: 'beforecalclast',
						type		: 'new'
					};
					var retStrBegin = _thsQuote.getData(param);
					var retObjBegin = eval('(' + retStrBegin + ')');
					
					// 获取大盘行业区间终止价
					var param = {
						code		: dpHyStr,
						period		: _period,
						time		: _endTime,
						mode		: 'beforecalclast',
						type		: 'new'
					};
					var retStrEnd = _thsQuote.getData(param);
					var retObjEnd = eval('(' + retStrEnd + ')');
					
					var backObj = {};
					var dpCode	= dpHyArr[0];
					var hyCode	= dpHyArr[1];
					
					if (retObjEnd[dpCode] && retObjBegin[dpCode]) {
						if (retObjBegin[dpCode]['new']) {
							var dp = (retObjEnd[dpCode]['new'] - retObjBegin[dpCode]['new']) / retObjBegin[dpCode]['new'] * 100;
							backObj['dp']	= dp.toFixed(3);
						}
					}
					
					if (retObjEnd[hyCode] && retObjBegin[hyCode]) {
						if (retObjBegin[hyCode]['new']) {
							var hy = (retObjEnd[hyCode]['new'] - retObjBegin[hyCode]['new']) / retObjBegin[hyCode]['new'] * 100;
							backObj['hy']	= hy.toFixed(3);
						}
					}
					
					callback(backObj);
				}
			};
		} else {
			var zdfDataItemId	= '1116617';
			var reqObj = {
				code		: dpHyStr,
				type		: '7,11',
				period		: _period,
				time		: _endTime,
				begin		: _beginTime,
				end			: _endTime,
				onready		: function(){
					var param = {
						code		: dpHyStr,
						period		: _period,
						time		: _endTime,
						validbegin	: _beginTime,
						validend	: _endTime,
						mode		: 'beforecalclast',
						type		: zdfDataItemId
					};
					var retStr = _thsQuote.getStatData(param);
					var retObj = eval('(' + retStr + ')');
					var backObj = {};
					var flag = 0;
					for (var i in retObj) {
						if (flag == 0) {
							backObj['dp'] = retObj[i][zdfDataItemId];
						} else {
							backObj['hy'] = retObj[i][zdfDataItemId];
						}
						flag++;
					}
					callback(backObj);
				}
			};
		}
		var flag = _thsQuote.request(reqObj);
	};
	
	/**
	 * 注册拖动
	 * @param {function} callback 回调函数
	 * 回调时会传入一个对象包括以下几个键名
	 * begin	拖动开始时间
	 * end		拖动结束时间
	 */
	self.registerDrag		= function (callback)
	{
		var params	= {
			onready	: function (periodNum, period, code, end, begin)
			{
				var data	= {
					periodNum	: periodNum,
					begin		: formatTime(begin),
					end			: formatTime(end)
				};
				callback(data);
			}
		};
		_util.registerAreaStatTimeChange(params);
	};
	
	/**
	 * 获取对应数据项的数据项id
	 * @param {Object} dataItem
	 * @return {String}
	 */
	var getDataItemId	= function (dataItem)
	{
		initClientDataItem();
		return _clientDataItem.getDataItemId(dataItem);
	};
	
	/**
	 * 获取某个数据项的值
	 * @param {Object} dataItem
	 */
	var getData			= function (dataItem)
	{
		if ((dataItem == '起始价' || dataItem == '终止价') && _period == '8192') {
			return getFsQsZzPrice(dataItem);
		} else if (dataItem == '振幅' && _period == '8192') {
			return getFsZhenfu();
		} else {
			
			var param, retStr, retObj;
			
			dataItem	= getDataItemId(dataItem);
			if (dataItem == undefined) {
				return undefined;
			}
			
			param = {
				code		: _code,
				period		: _period,
				time		: _endTime,
				validbegin	: _beginTime,
				validend	: _endTime,
				mode		: 'beforecalclast',
				type		: dataItem
			};
			retStr = _thsQuote.getStatData(param);
			if (retStr != '({})') {
				retObj = eval('(' + retStr + ')');
				if (retObj[_code] && typeof retObj[_code][dataItem] != 'undefined') {
					return retObj[_code][dataItem];
				} else {
					return undefined;
				}
			} else {
				retObj = undefined;
			}
		}
	};
	
	/**
	 * 获取内盘或者外盘
	 * @param {Object} dataItem 内盘或外盘
	 * @return {Object} | {undefined} 
	 * 返回的数据包含以下两个数据项
	 * 内盘、外盘
	 */
	self.getNpWp		= function (callback)
	{
		var npDataItemId	= getDataItemId('内盘');
		var wpDataItemId	= getDataItemId('外盘');
		
		var dataItems	= [npDataItemId, wpDataItemId];
		
		var reqObj = {
			code		: _code,
			type		: dataItems,
			period		: _period,
			time		: _endTime,
			begin		: _beginTime,
			end			: _endTime,
			onready		: function() {
				var result	= {};
				for (var i in dataItems) {
					var item	=  i == 0 ? 'np' : 'wp';
					
					// 获取内盘开始点的量
					var param = {
						code		: _code,
						period		: _period,
						time		: _beginTime,
						mode		: 'beforecalclast',
						type		: dataItems[i]
					};
					var retStrBegin = _thsQuote.getStatData(param);
					var retObjBegin = eval('(' + retStrBegin + ')');
					
					// 获取外盘结束点的量
					var param = {
						code		: _code,
						period		: _period,
						time		: _endTime,
						mode		: 'beforecalclast',
						type		: dataItems[i]
					};
					var retStrEnd = _thsQuote.getData(param);
					var retObjEnd = eval('(' + retStrEnd + ')');
					
					if (retObjEnd[_code] && retObjBegin[_code]) {
						var data = parseFloat(retObjEnd[_code][dataItems[i]] - retObjBegin[_code][dataItems[i]]);
						if (!isNaN(data)) {
							result[item]	= data;
						}
					}
				}
				
				if (typeof callback == 'function') {
					callback(result);
				}
			}
		};
		_thsQuote.request(reqObj);
	};
	
	/**
	 * 获取个股贡献度
	 */
	self.getContribution = function (callback)
	{
		var param = {
			code		: _marketCode,
			datatype	: 2708,
			period		: _period,
			begintime	: _beginTime,
			endtime		: _endTime,
			onready		: function (data) {
				if (typeof callback == 'function') {
					callback(data);
				}
			}
		};
		_thsQuote.AreaStatConRequest(param);
	};
	
	/**
	 * 获取分时起始或终止价
	 */
	var getFsQsZzPrice		= function (dataItem)
	{
		var param, retStr, retObj;
		var time	= dataItem == '起始价' ? _beginTime : _endTime;
		param = {
			code		: _code,
			period		: _period,
			time		: time,
			mode		: 'beforecalclast',
			type		: 'new'
		};
		var retStr = _thsQuote.getStatData(param);
		if (retStr != '({})') {
			retObj = eval('(' + retStr + ')');
			if (retObj[_code] && typeof retObj[_code]['new'] != 'undefined') {
				return retObj[_code]['new'];
			} else {
				return undefined;
			}
		} else {
			return undefined;
		}
	};
	
	/**
	 * 获取分时振幅数据
	 * @return {Float} 3位小数
	 */
	var getFsZhenfu	= function ()
	{
		var paramHigh, paramLow, highStr, lowStr, highObj, lowObj, retObj;
		// 获取最高最低数据项id
		var zgDataItemId	= getDataItemId('最高');
		var zdDataItemId	= getDataItemId('最低');
		//获取最高
		paramHigh = {
			code		: _code,
			period		: _period,
			time		: _endTime,
			validbegin	: _beginTime,
			validend	: _endTime,
			mode		: 'beforecalclast',
			type		: zgDataItemId
		};
		var highStr = _thsQuote.getStatData(paramHigh);
		//获取最低
		paramLow = {
				code		: _code,
				period		: _period,
				time		: _endTime,
				validbegin	: _beginTime,
				validend	: _endTime,
				mode		: 'beforecalclast',
				type		: zdDataItemId
		};
		var lowStr = _thsQuote.getStatData(paramLow);
		if (highStr != '({})' && lowStr != '({})') {
			highObj	= eval('(' + highStr + ')');
			lowObj	= eval('(' + lowStr + ')');
			
			high = highObj[_code][zgDataItemId];
			low = lowObj[_code][zdDataItemId];
			
			if (low) {
				var zhenfu = (high - low) / low;
				if (isNaN(zhenfu)) {
					return undefined;
				}
				return (zhenfu * 100).toFixed(3);
			} else {
				return undefined;
			}
		} else {
			return undefined;
		}
	};
	
	/**
	 * 获取当前股票代码
	 * @return String
	 */
	self.getCurrentStockCode = function ()
	{
		return _code;
	};
	
	/**
	 * 获取当前包含市场的股票代码
	 * @return String
	 */
	self.getCurrentMarketStockCode = function ()
	{
		return _marketCode;
	};
	
	/**
	 * 获取股票类型
	 * @return Integer
	 */
	self.getStockType = function ()
	{
		return _stockType;
	};
	
	/**
	 * 获取股票小数位数
	 * @return Integer
	 */
	self.getCodeDecimal = function ()
	{
		return _codeDecimal;
	};
	
	/**
	 * 获取当前周期
	 * @return Integer
	 */
	self.getPeriod = function ()
	{
		return _period;
	};
	
	/**
	 * 设置统计区间(起始结束时间)
	 * @param {Object} params 
	 * {
	 * 	begintime	:20120301,
	 * 	endtime		:20120306
	 * }
	 * @return {object} 有效的起始结束时间
	 * {
	 * 	begintime	:20120301,
	 * 	endtime		:20120306
	 * }
	 */
	self.setAreaStatTime = function (params)
	{
		var retStr = _thsQuote.setAreaStatTime(params);
		return retStr;
	};
	
	/**
	 * 释放变量，防止内存泄露
	 */
	self.release	= function ()
	{
		delete(_thsQuote);
		delete(_util);
		delete(_code);
		delete(_period);
		delete(_beginTime);
		delete(_endTime);
		delete(_marketCode);
		delete(_stockType);
		delete(_clientDataItem);
		delete(_codeDecimal);
	};
	
	/**
	 * 区间统计对象初始化
	 */
	var init	= function ()
	{
		_thsQuote	= external.createObject("Quote");
		_util		= external.createObject("Util");
		var qjtjStr = _thsQuote.StartGetAreaStatData();
		var qjtjObj = eval('('+ qjtjStr +')');
		_code		= _thsQuote.getStockCode(qjtjObj.code);
		_period		= qjtjObj.period;
		_beginTime	= qjtjObj.begintime;
		_endTime	= qjtjObj.endtime;
		_marketCode	= qjtjObj.code;
		_stockType	= _thsQuote.getStockType(_marketCode);
		_codeDecimal = _thsQuote.GetCodeDecimal(_marketCode);
	};
	
	/**
	 * 初始化客户端数据项对象
	 */
	var initClientDataItem	= function ()
	{
		if (!_clientDataItem) {
			_clientDataItem	= new ClientDataItem({
				period	: _period,
				code	: _marketCode,
				stockType:_stockType
			})
		}
	}
	
	/**
	 * 注册实时行情推送
	 */
	self.registerPush	= function (dataItems, callback)
	{
		if ($.isArray(dataItems) && typeof callback == 'function' && _period != '8192') {
			_thsQuote.registerPush(getRealQuotationParam(dataItems, callback));
		}
	}
	
	/**
	 * 获取实时行情推送参数
	 */
	var getRealQuotationParam	= function (dataItems, callback)
	{
		return {
			code		: _code,
			period		: _period,
			time		: _endTime,
			begin		: _beginTime,
			end			: _endTime,
			type		: dataItems,
			onready	: function (data) {
				if ($.isArray(dataItems)) {
					var result	= {};
					for (var i in dataItems) {
						var data	= getData(dataItems[i])
						if (typeof data != 'undefined') {
							result[dataItems[i]]	= data;
						}
					}
					
					if (typeof callback == 'function') {
						callback(result);
					}
				}
			}
		}
	}
	
	init();
	
	return self;
};
window.IntervalStatData	= new IntervalStatData();