var qs = parseQueryString(window.location.href);
// var hostUrl = '../..';
var hostUrl = BASEURL;
var returnUrl = qs.returnUrl;
var token = qs.token;

checkToken();

if (qs.name) {
    $('.current-city span').text(qs.name).attr('data-code', qs.code);
}

$('#back').click(function() {
   window.history.go(-1)
});

$('.current-city').click(function() {
    var cityName = qs.name || $('.current-city span').text();
    var cityCode = qs.code || $('.current-city span').attr('data-code');
    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;
    }
})

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 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 searchCity () {
	window.location.href = "choice_city.html?token=" + token;
}