var qs = parseQueryString(window.location.href);
// var hostUrl = '../..';
var hostUrl = BASEURL;
var returnUrl = qs.returnUrl;
var token = qs.token;
var addressName = '';
var local_city = localStorage.getItem("city");
if(local_city){
	//已经定位
}else{
	//还未定位
	getAddress();
}
checkToken();


$('#back').click(function() {
// 	window.webkit.messageHandlers.PopRootMessageHandler.postMessage({name:"1"});
	if (document.referrer.includes('fund_h5_api.html')) {
        window.location.href = document.referrer;
    } else {
        redirectToFailedReturnUrl('', 'failed', 1020, '退出公积金查询页');
    }
});


$('.current-city').click(function() {

	var flag = false;
    var cityName = $('.current-city span').text();
    var cityCode = $('.current-city span').attr('data-code');
    tips.find(function(item, index) {
		if(item.region == $('.current-city span').text()){
			flag = true;
			if (document.referrer.includes('&name=')) {
		        window.location.href = document.referrer.replace(/&name=[^&]+&code=[^&]+/, '&name=' + cityName + '&code=' + cityCode);
		    } else {
		        window.location.href = './fund_h5_api.html?token=' + token + '&name=' + cityName + '&code=' + cityCode;
		    }
//			window.location.href = './fund_h5_api.html?token=' + token + '&name=' + cityName + '&code=' + cityCode;
		}
	})
    if(!flag){
		window.location.href="no_open_city.html?cityName=" + $('.current-city span').text();
    }
//  if (document.referrer.includes('&name=')) {
//      window.location.href = document.referrer.replace(/&name=[^&]+&code=[^&]+/, '&name=' + cityName + '&code=' + cityCode);
//  }
})

//function redirectToFailedReturnUrl(tid, result, failCode, reason) {
//  var linkString = returnUrl.includes('?') ? '&' : '?';
//  returnUrl += linkString + "result=" + result + "&tid=" + tid + "&token=" + token + "&failCode=" + failCode + "&reason=" + reason;
//  window.location.href = returnUrl;
//}
function redirectToFailedReturnUrl(tid, result, failCode, reason) {
    if (returnUrl.indexOf('?') < 0) {
        returnUrl += "?result=" + result + "&tid=" + tid + "&token=" + token + "&failCode=" + failCode + "&reason=" + reason;
    } else {
        returnUrl += "&result=" + result + "&tid=" + tid + "&token=" + token + "&failCode=" + failCode + "&reason=" + reason;
    }

    window.sessionStorage.clear();
    window.location.href = returnUrl;
}

function showMsg(msg) {
    var msgBox = $('.alert-info');
    msgBox.children('p').text(msg);
    msgBox.show();
    setTimeout(function() {
        msgBox.hide();
    }, 30000);
}

function checkToken() {
    var getTokenInfo = $.ajax({
        type: 'GET',
        url: hostUrl + '/token?token=' + token + "&time=" + Math.round(Date.now() / 1000),
        timeout: 30000,
        contentType: 'application/json;charset=utf-8'
    });

    getTokenInfo.done(function(data) {
        if (data.returnUrl && !returnUrl) {
            returnUrl = data.returnUrl;
        }

        if (data.tid && data.region && data.loginLabel && data.inputData) {
            window.location.href = './fund_h5_api.html?token=' + token + "&time=" + Math.round(Date.now() / 1000);
            return;
        }
        $('body').show();
        getCityListAndRender();
    });

    getTokenInfo.fail(function(err) {
        $('body').show();
        showMsg('token校验失败:' + JSON.stringify(err.responseJSON.error));
    });
}

function getCityListAndRender() {
    $.ajax({
        type: "GET",
        url: hostUrl + '/city_list?type=fund&sort=true&token=' + token + '&time=' + Math.round(Date.now() / 1000),
        contentType: 'application/json;charset=utf-8',
        success: function(data) {
            return $(".city-list").CityPicker(data);
        },
        error: function(err) {
            return showMsg('获取城市列表失败:' + JSON.stringify(err.responseJSON.error));
        }
    });
}


//自动获取地址
function getAddress () {
	var code = '';
	var map = new BMap.Map("allmap");
	var point = new BMap.Point(116.331398,39.897445);
	map.centerAndZoom(point,12);
	
	var geolocation = new BMap.Geolocation();
	// 开启SDK辅助定位
	geolocation.enableSDKLocation();
	geolocation.getCurrentPosition(function(r){
		if(this.getStatus() == BMAP_STATUS_SUCCESS){
			var mk = new BMap.Marker(r.point);
			map.addOverlay(mk);
			map.panTo(r.point);
//			alert('您的位置：'+r.point.lng+','+r.point.lat);
//			alert(r.address.city)
			addressName = r.address.city;
			localStorage.setItem("city",addressName);
		}
		else {
//			alert('failed'+this.getStatus());
		}        
		//页面首次定位渲染
		if (addressName.indexOf("市") != -1) {
			addressName = addressName.replace('市', '');
			console.log(addressName)
			tips.find(function(item, index) {
				if(item.region == addressName){
					$('.current-city span').text(addressName).attr('data-code', item.regionCode);
				}
			})
		}
	});
	
}
