var cfg = window.chartConfig;
// ajax with adj set 1
$(function () {
    jQuery.support.cors = true;
    if($("#adj").val()=='1') {
        console.log("Got adj set 1");
        var pyurl= "https://py.doorcome.cn/ts/adj?";
        pyurl += "ts_code="+$("#ts_code").val();
        pyurl += "&s="+$("#s").val();
        pyurl += "&e="+$("#e").val();
        console.log(pyurl);
        //var formData = new FormData($('#form1')[0]);
        $.ajax({
            crossDomain:true,
            //type: 'post',
            url: pyurl, //上传文件的请求路径必须是绝对路劲
            //data: formData,
            cache: false,
            processData: false,
            contentType: false,
            success:function (data) {
                console.log("Get data sucessfully");
                var adj = getAdj(data);
                //console.log(adj);
                console.log(cfg.data[0]['value'][0]);
                console.log(cfg.data[0]['value'][1]);
                cfg.data = adjData(adj,cfg.data,'price');
                cfg.data2 = adjData(adj,cfg.data2,'price');
                cfg.data3 = adjData(adj,cfg.data3,'price');
                cfg.data4 = adjData(adj,cfg.data4,'volum');
                cfg.data5 = adjData(adj,cfg.data5,'volum');
                console.log(cfg.data[0]['value'][0]);
                console.log(cfg.data[0]['value'][1]);
                //重新执行画图
                if (option && typeof option === "object") {
                    myChart.setOption(option, true);
                }
            },
            error: function () {
                alert("获取数据失败！");
            }
        });
    };
});

function getAdj(data){
    var arr = $.parseJSON(data);
    var rtArr = {};
    var key = '';
    //console.log(arr);
    var lastAdj= arr[0]['adj_factor'] //last adj number
    for(var i = 0; i <arr.length;i++){
        key=arr[i]['trade_date'];
        rtArr[key] = arr[i]['adj_factor']/lastAdj;
    }
     return rtArr;
}

function adjData(adj,data,tp){
    var k = '';
    if(data == null) return 0;
    for(var i=0; i<data.length; i++){
        k = data[i]['value'][0];    //get date as key
        k = k.replace(/-/g,'');  //formate key formate from yyyy-mm-dd to yyyymmdd
        if(tp=='price')data[i]['value'][1]=Math.round(data[i]['value'][1]*adj[k]*100)/100;  //价格保留两位小数
        if(tp=='volum')data[i]['value'][1]=Math.round(data[i]['value'][1]/adj[k]);  //数量取整数
    }
    return data;
}