/*
 * 规定页面上的 #stock_code 是6位股票代码  #stock_id 是8位股票代码 !!
 */


/**
 * 由六位数字的股票代码 得到8位股票代码 不会返回指数和权证，只返回正股或基金
 * 规则 (注意，交易所规则可能变化。目前先这样规定):
 * 6{\d5} 上海正股 sh
 * 5{\d5} 上海基金 sh 但需要排除 58{\d4} 它是 权证
 * 0{\d5} 深圳正股 sz 但需要排除 03{\d4} 它是 权证
 * 1{\d5} 深圳基金 sz
 * 3{\d5} 深圳创业板 sz
 *
 * sh000{\d5} 沪市指数
 * sh6{\d5} 沪市正股 sh
 * sh7{\d5} 沪市配股 投票 申购新股 回购登记 撤销
 * sh8{\d5} 沪市配股 投票 申购新股 回购登记 撤销
 * sh50{\d4} sh51{\d4} sh52{\d4}上海基金 sh 
 * sh58{\d4} 沪市权证
 * sh9{\d6}  沪市B股
 *
 * sz39{\d4} 深市指数
 * sz30{\d4} 深市创业板
 * sz36{\d4} 深市投票
 * sz07{\d4} 配股增发
 * sz08{\d4} 配股增发
 * sz03{\d4} 深市权证;
 * sz15{\d4} 深市封闭式基金
 * sz16{\d4} 深市封闭式基金
 * sz18{\d4} 深市封闭式基金
 * sz00{\d4} 深市正股 (其中sz002是中小板)
 * sz2{\d5} 深市B股
 *
 * @param string $code 6位股票代码
 * @return string 8位股票代码
 */
function stock_6to8(code){
	code=code+'';
	
	if(/\d{6}/.test(code)){
	}else{
		return code;
	}
	
	var prefix='';	
	var first_char=code.charAt(0);	
	var second_char=code.charAt(1);	
	if((first_char==0&&second_char!=3)||(first_char==1)|| (first_char==3 && second_char==0)){
		prefix='sz';
	}else if((first_char==5&&second_char!=8)||first_char==6){
		prefix='sh';
	}	
	return prefix+code;
}

/**
 * A股 由8位数字的股票代码 得到6位股票代码
 *
 * @param string code8 8位股票代码
 * @return string 6位股票代码
 */
function stock_8to6(code8){
	if(code8.length == 8){
		return code8.substring(2);
	}
	return code8;
}

/**
 * 根据股票名 判断 是否为ST股票
 * 
 * @param {String} stock_name
 */
function stock_is_st(stock_name){
	stock_name = stock_name.toUpperCase();
	if( stock_name.charAt( 0 ) == 'S' 
		&& stock_name.charAt( 1 ) == 'T' 
	){
		return true;
	}
	if( stock_name.length > 3){
		if( stock_name.charAt( 0 ) == '*' 
			&& stock_name.charAt( 1 ) == 'S' 
			&& stock_name.charAt( 2 ) == 'T' 
		){
			return true;
		}else if( stock_name.charAt( 0 ) == 'S' 
			&& stock_name.charAt( 1 ) == '*' 
			&& stock_name.charAt( 2 ) == 'S' 
			&& stock_name.charAt( 3 ) == 'T' 
		){
			return true;
		}else if( stock_name.charAt( 0 ) == 'S' 
			&& stock_name.charAt( 1 ) == 'S' 
			&& stock_name.charAt( 2 ) == 'T' 
		){
			return true;
		}
	}
	if( (stock_name.length > 3) 
		&& stock_name.charAt( 0 ) == 'S' 
		&& stock_name.charAt( 1 ) == ' ' 
		&& stock_name.charAt( 2 ) == 'S' 
		&& stock_name.charAt( 3 ) == 'T' 
	){
		return true;
	}
	return false;
}

/**
 * 根据8位证券代码判断股票是否基金，基金等需要显示3位小数
 */
function stock_is_fund(stock_id){	
	if (!stock_id){
		return false;
	}
	if (stock_id && stock_id.length == 6 )	{
		stock_id = stock_6to8(stock_id);
	}
	var code_4 = stock_id.substr(0,4);
	if(code_4 == 'sh50' || code_4 == 'sh51' || code_4 == 'sh52'){
		return true;
	}
	if(code_4 == 'sz15' || code_4 == 'sz16' || code_4 == 'sz18'){
		return true;
	}
	return false;
}

/**
 * 刷新股票实时行情,总是每隔6秒取一次
 * 在买入股票页、卖出股票页、股票行业页等都会使用
 * 只要这个页面存在 input id="stock_id" 的控件
 */
function stock_must_refresh_lastquote(){
	var stock_id=$('#stock_id').val();
	if(stock_id && stock_id.length==8){
		stock_refresh_lastquote(stock_id);
	}
}

$(document).ready(
	function(){		
		if("undefined" == typeof( $('#stock_id').get(0) )){
		}else{
			setInterval( "stock_must_refresh_lastquote()" , 6.01*1000);
		}
	}
);


/*
 * 刷新页面上的实时行情 买入页 卖出页 个股行情页 弹出式的个股行情页，都共用
 */
function stock_refresh_lastquote(stock_id){
	var obj = new syb.stock.LastQuote();
	//尝试cache 中加载数据 并显示
	var cache_data = obj.load_cache(stock_id);
	if(cache_data){
		stock_fill_quote_on_html(cache_data);
	}
	//无论如何，还要通过js获取最新的实时行情
	obj.load(stock_id, function(data) {
		stock_fill_quote_on_html(data);
	});
	obj.load_data_by_sina();
}

/**
 * 清空页面显示的行情数据  买入页 卖出页 个股行情页 弹出式的个股行情页，都共用
 *
 */
function stock_clear_quote_on_html(){
	$('#stock_name').text('');
	$('#buy_price').val('');
	$('#sell_price').val('');
	for(i=1;i<=5;i++){
		$('#sale' + i +'_count').text('0.00');
		$('#buy' + i +'_count').text('0.00');	
		$('#sale'  + i ).text('0.00');
		$('#buy'  + i ).text('0.00');
	}
	$('#now_price').text('0.00');
	$('#today_buy').text('0.00');
	$('#today_sale').text('0.00');
	$('#last_close').text('0.00');
	$('#today_open').text('0.00');
	$('#limit_down').text('0.00');
	$('#limit_up').text('0.00');
	$('#diff_amount').text('0.00')
	$('#today_amount').text('0.00');
	$('#diff_percent').text('0')
	$('#today_volume').text('0');
}


/**
 * 填充股票数据   买入页 卖出页 个股行情页 弹出式的个股行情页，都共用
 * 规定页面上的 #stock_code 是6位股票代码  #stock_id 是8位股票代码 
  * @param {Object} data 是一个结构体，参见  syb.stock.LastQuote
 */
function stock_fill_quote_on_html(data){
	//结构体有效才继续
	if(data && typeof(data.sell5_count)=='string'){}else{
		return false;
	};
	//必须和页面上期待的一致，才继续
	var value = $('#stock_id').val();
	if(data.stock_id==value){}else{
		common_log('没有找到 #stock_id 或不匹配 value #stock_id 的值');
		return false;
	}
	$('#stock_name').text(data.name);
	//$('#buy_price').val(data.buy1);
	//$('#sell_price').val(data.sell1);
	//买5卖5价
	$('#sale5').text(data.sell5);
	$('#sale4').text(data.sell4);
	$('#sale3').text(data.sell3);
	$('#sale2').text(data.sell2);
	$('#sale1').text(data.sell1);
	$('#buy5').text(data.buy5);
	$('#buy4').text(data.buy4);
	$('#buy3').text(data.buy3);
	$('#buy2').text(data.buy2);
	$('#buy1').text(data.buy1);
	//买5卖5价着色
	for(i=1;i<=5;i++){
		if(  parseFloat($('#sale' + i ).text()) >= data.last_close ){
			$('#sale' + i ).addClass("up_color");
		}else{
			$('#sale' + i ).addClass("down_color");
		}
		if(  parseFloat($('#buy' + i ).text()) >= data.last_close ){
			$('#buy' + i ).addClass("up_color");
		}else{
			$('#buy' + i ).addClass("down_color");
		}
	}
	//买5卖5量
	var now_price = parseFloat(data.sell1);	
	$('#sale5_count').text(data.sell5_count);
	$('#sale4_count').text(data.sell4_count);
	$('#sale3_count').text(data.sell3_count);
	$('#sale2_count').text(data.sell2_count);
	$('#sale1_count').text(data.sell1_count);
	$('#buy5_count').text(data.buy5_count);
	$('#buy4_count').text(data.buy4_count);
	$('#buy3_count').text(data.buy3_count);
	$('#buy2_count').text(data.buy2_count);
	$('#buy1_count').text(data.buy1_count);

	//当前价
	$('#now_price').text(data.today_now);
	if(data.last_close>0 && data.today_now > data.last_close){
		$('#now_price').addClass("up_color");
	}else{
		$('#now_price').addClass("down_color");
	}
	//当前买价，当前卖价 
	$('#today_buy').text(data.buy1);
	$('#today_sale').text(data.sell1);
	//昨收
	$('#last_close').text(data.last_close);
	//今开
	$('#today_open').text(data.today_open);	
	if(data.last_close>0 && data.today_open > data.last_close){
		$('#today_open').addClass("up_color");
	}else{
		$('#today_open').addClass("down_color");
	}
	
	//涨跌停
	//判断是否是ST股
	var stock_name = $('#stock_name').text();
	if(stock_is_st(stock_name)){
		$('#limit_down').text((data.last_close*0.95).toFixed(2)).addClass("down_color").removeClass("up_color");
		$('#limit_up').text((data.last_close*1.05).toFixed(2)).addClass("up_color").removeClass("down_color");
		
	}else{
		$('#limit_down').text((data.last_close*0.9).toFixed(2)).addClass("down_color").removeClass("up_color");		
		$('#limit_up').text((data.last_close*1.1).toFixed(2)).addClass("up_color").removeClass("down_color");
	}
	//涨跌幅
	var diff_amount = (data.updown + "").substring(0,(data.updown + "").indexOf('.') + 3);			
	var diff_percent = (data.updown_rate + "").substring(0,(data.updown_rate + "").indexOf('.') + 3);			

	if(diff_amount > 0){
		$('#diff_amount').text(diff_amount).addClass("up_color").removeClass('down_color');
	} else {
		$('#diff_amount').text(diff_amount).addClass("down_color").removeClass('up_color');
	}	
	if(diff_percent >= 0){
		$('#diff_percent').text(diff_percent + '%').addClass("up_color").removeClass('down_color');				
	} else {
		$('#diff_percent').text(diff_percent + '%').addClass("down_color").removeClass("up_color");
	}
	//成交量 成交额
	var fVolume = new Number(data.turnover_count);
	var fAmount = new Number(data.turnover_money/10000);
	if(fVolume <= 10000){
		$('#today_volume').text(fVolume.toFixed(2) + '手');
	}else{
		fVolume = (fVolume) / 10000; // 万手
		$('#today_volume').text(fVolume.toFixed(2) + '万手');
	}
	if(fAmount <= 10000){
		$('#today_amount').text(fAmount.toFixed(2) + '万');
	}else{
		fAmount = (fAmount) / 10000; // 万元
		$('#today_amount').text(fAmount.toFixed(2) + '亿');
	}
	//行情时间
	$('#hq_time').text(data.time);
}

/**
 *
 * 计算列表中股票市值，前提条件：各个股票的实时价格已经取到
 * @param  jObjTable 一个jquery对象，对应表格id
 * @param calc_direct 
 *	calc_direct 参数不填(或者填入非0的值时)表示正向计算  	(当前价格-买入价格) 	来计算盈亏
 *	calc_direct = 1 表示 卖空时的计算  										(买入价格-当前价格) 	来计算盈亏
 */
function stock_calc_asset_in_table(jObjTable,calc_direct){
  if ( arguments.length > 0 ) {
  }else{
  	calc_direct = 0;
  }
	common_log('freshStocks 用户持股总市值 calc_direct = '  + calc_direct  );
	if ("undefined" == typeof(jObjTable) || "string" == typeof(jObjTable) || jObjTable==null) { return 0; };
	common_log(' typeof = ' + typeof(jObjTable) );
	
	if (jObjTable.length > 0){}else{return 0;}
	
	//持仓股各股的总市值	
	var stocks_asset = new Number( 0 );
	common_log('freshStocks 持仓股数量 =  ' + jObjTable.length );
	
	jObjTable.each(function(){
		var stock_id = $(this).attr('sid');
		common_log('freshStocks 持仓股 stock_id =  ' + stock_id );
		try{
			hq_str = eval("hq_str_" + stock_id);
		}catch(e){
		};
		
		if (typeof(hq_str) == "undefined" || hq_str.length == 0){			
			//伪装成为全0的，继续执行
			hq_str = '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0';
			common_log('freshStocks 持仓股 stock_id =  ' + stock_id + ' fake to zero ');
		}
		var hq_arr=hq_str.split(",");
		if (hq_arr.length < 32){
			return false;
		}
		
		//现价(最新价)，todo 交易时间内，应该判断当前时间与行情时间不超过1分钟	
		var fNowPrice = new Number(hq_arr[3]);
		var fLastClose = new Number(hq_arr[2]);	
		//存在上收价 可能是今日停牌	
		if (fNowPrice < 0.001 && fLastClose > 0.001){
			fNowPrice = fLastClose;
		}else{
			//没有最新价也没有上收价，暂时用上次的最新价
			if (fNowPrice < 0.001 && fLastClose < 0.001){
				fNowPrice = new Number( $(this).children('td[l="today_now"]').html() );
			}
		}
		if(stock_is_fund(stock_id)){
			$(this).children('td[l="today_now"]').html( fNowPrice.toFixed(3) );
		}else{
			$(this).children('td[l="today_now"]').html( fNowPrice.toFixed(2) );
		}
		common_log('freshStocks', 'each 持仓股 stock_id =  ' + stock_id  + ' 最新行情 = ' + fNowPrice);
		//取持股数量
		var stock_count = $(this).children('td[l="total"]').html();
		//最新市值 td(5)
		//var f_old_value_now = new Number( $(this).children('td[l="value_now"]').html() );		
		var fNowValue = fNowPrice * stock_count;		
		$(this).children('td[l="value_now"]').html( new Number(fNowValue).toFixed(2) );
		// 今涨跌幅
		var updown_rate = 0.0;
		if( fLastClose != 0 ){
			updown_rate = new Number( ( fNowPrice - fLastClose ) / fLastClose * 100 );
		}
		var tdspan_updown_rate = $(this).children('td[l="updown_rate"]').children('span');
		tdspan_updown_rate.siblings().remove();
		tdspan_updown_rate.html( new Number(updown_rate).toFixed(2) + '%' );
		
		//保本价
		var fRreakPrice = parseFloat( $.trim( $(this).children('td[l="break_price"]').html() ) );;
		if (isNaN(fRreakPrice)){fRreakPrice = 0;}; if (fRreakPrice < 0){fRreakPrice = 0;};
		
		//参考盈亏 td(l=profit) =(最新-保本)* stock_count
		var fProfit = (fNowPrice- fRreakPrice ) * stock_count;
		
		if( calc_direct=='1'){
				//会算出卖空是的保本价  fRreakPrice * (0.997/1.003);
				fRreakPrice = fRreakPrice * 0.994;
				 //$(this).children('td[l=3]').html(fRreakPrice);
				fProfit = (fRreakPrice - fNowPrice) * count;
		}
		//common_log('freshStocks 保本 = ' + fRreakPrice + '  参考盈亏=' + fProfit + ' 市值 =' + fNowValue);

		var tdspan_profit = $(this).children('td[l="profit"]').children('span');
		tdspan_profit.html( new Number(fProfit).toFixed(2) );

		//盈亏比例 td(7)
		var fProfit_rate = 0;
		if (fRreakPrice > 0){			
			if( typeof( calc_direct ) !='undefined' && calc_direct=='1'){
				fProfit_rate = (fRreakPrice - fNowPrice) / fRreakPrice  * 100;
			}else{
				fProfit_rate = (fNowPrice- fRreakPrice ) / fRreakPrice  * 100;
			}
		}else{
			fProfit_rate = 100;
		}
		//common_log('freshStocks', '计算得到盈亏比例 =  ' + fProfit_rate.toFixed(2) + '%');
		var tdspan_profit_rate = $(this).children('td[l="profit_rate"]').children('span');
		tdspan_profit_rate.html( new Number(fProfit_rate).toFixed(2) + '%' );
		
		//着色
		tdspan_profit.removeClass('upColor').removeClass('downColor');
		tdspan_profit_rate.removeClass('upColor').removeClass('downColor');		
		if (fProfit > 0){
			tdspan_profit.addClass('upColor');
			tdspan_profit_rate.addClass('upColor');
		}else if (fProfit < 0){
			tdspan_profit.addClass('downColor');
			tdspan_profit_rate.addClass('downColor');
		}
		tdspan_updown_rate.removeClass('upColor').removeClass('downColor');
		if (updown_rate > 0 ){
			tdspan_updown_rate.addClass('upColor');
		}else if (updown_rate < 0){
			tdspan_updown_rate.addClass('downColor');
		}
		
		//用户股票市值累加
		stocks_asset +=  new Number(fNowValue);		
		//common_log('freshStocks', '市值累加 =  ' + stocks_asset);
	});
	$('#stocks_maket_value').html( stocks_asset.toFixed(2) );
	return stocks_asset;
}

//确保 stock_refresh_current_asset 函数第一次总是能被执行
var g_is_first_run_stock_refresh_current_asset = true;

/**
 * 重新计算 资产总值 【资金=可用资金和押单资金之和】+【股票市值】
 * 个人中心、卖出股票、持仓股池中 
 * 需要 列举现有全部股票，需要每隔一段时间就取实时行情刷新
 * 
 */
function stock_refresh_current_asset(){
	//总资产
	var obj_spn_a_asset = $('#spn_a_asset').html();
	//可用资金和押单资金之和
	var obj_spn_a_money_total = $('#spn_a_money_total').html();
	if(obj_spn_a_asset == null || obj_spn_a_money_total == null){
		return ;
	}
	//所有股票的市值
	var stocks_market_value = 0;

	var  jObjTable = $('#tb_stocks tbody tr');
	if( jObjTable ){
		if(typeof(g_current_js_stocks)!='undefined'){
			var clsDate = new Date();
			var hour = clsDate.getHours();
			var minute = clsDate.getMinutes();			
			//如果在开盘时间内，8秒重刷一次；如果不在开盘时间，不刷
			//星期日 星期六
			if ( clsDate.getDay()==0  || clsDate.getDay()==6 ){
				if(!g_is_first_run_stock_refresh_current_asset){				
					return;
				}				
			}
			if ( (hour > 15)  || (hour < 9)  || (hour == 9 && minute < 31 ) || (hour == 15 && minute < 5 ) ){
				if(!g_is_first_run_stock_refresh_current_asset){
					return;
				}
			}
			g_is_first_run_stock_refresh_current_asset = false;
			var len = global.site.hq_hosts2.length ;
			var index = Math.floor( Math.random() * len + 1)-1;
			var host = global.site.hq_hosts2[index];			
			var timestamp = clsDate.getTime();
			var url_request = 'http://' + host + '/r=' +timestamp.toString() + '&list=' + g_current_js_stocks;
			load_js('current_js_stocks', url_request, 'gbk', function(){				
					var calc_direct = 0;
					stocks_market_value = stock_calc_asset_in_table( jObjTable,calc_direct );		
					var new_asset = new Number(obj_spn_a_money_total) + new Number(stocks_market_value);
					$('#spn_a_asset').html(new_asset.toFixed(2));
					//调用自身
					setTimeout( "stock_refresh_current_asset();	" , 8 * 1000);
				}			
			);
		}
	}else{
		common_log('stock_refresh_current_js_stocks 没有找到 #tb_stocks');
	}
};



