Light12306/Mobile12306New/js/run_query.js
SilenceLeo 9907c57d50 增加
2014-08-21 17:20:34 +08:00

450 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var RunQuery = {
init: function() {
if($('#runquery_page').length == 0){
return false;
}
var maxDay = (new Date()).addDays(19);
Public.formatString = 'M月d日';
Public.setDate(maxDay);
Public.calendar.checkCallback = RunQuery.dateChangeCallback;
RunQuery.getQueryData();
if(!RunQuery.curData){
window.location.href = 'query.html';
return false;
}
$('#filter_ok').on('click', function() {
Public.hideInnerPage('filter');
$('#query_form [name=filters]').val($('#filter_form').serialize());
RunQuery.hisUpdata();
});
$('#check_left,#check_right').on('click', function() {
RunQuery.hisUpdata();
});
$('#filter_cancel').on('click', function() {
Public.hideInnerPage('filter');
var bak = $('#query_form [name=filters]').val(),
querys = bak.split('&');
Query.setFilter(querys);
});
RunQuery.checkLogin();
RunQuery.setFilter();
$('#filter_btn').on('click',function(){
Public.showInnerPage('filter');
});
$('#filter_cancel').on('click',function(){
Public.hideInnerPage();
});
RunQuery.queryTicket();
},
curData:null,
getQueryData:function(){
if(!!Public.his.queryObjs[Public.his.querys[0][0]]){
RunQuery.curData = Public.his.queryObjs[Public.his.querys[0][0]];
}
},
setFilter:function(){
Query.setFilter(RunQuery.curData['filters'].split('&'));
$('.station_title strong').html(RunQuery.curData['startname'] +'→'+RunQuery.curData['endname']);
$('#query_form [name=startname]').val(RunQuery.curData['startname']);
$('#query_form [name=startcode]').val(RunQuery.curData['startcode']);
$('#query_form [name=endname]').val(RunQuery.curData['endname']);
$('#query_form [name=endcode]').val(RunQuery.curData['endcode']);
$('#query_form [name=type]').val(RunQuery.curData['type']);
$('#query_form [name=filters]').val(RunQuery.curData['filters']);
var date = new Date(RunQuery.curData['start_date'].replace(/\-/g,'/'));
$('#start_date').html(date.format('M月d日') + ' ' + date.day(3));
Public.calendar.setCurDate(date);
},
isLogin:false,
checkNum: 0,
checkLogin: function() {
RunQuery.checkNum++;
cn12306.isUserLogined(RunQuery.hasLogin, RunQuery.noLogin, function() {
RunQuery.noLogin();
// Public.toast("登录时网络错误");
if (RunQuery.checkNum < 2) {
RunQuery.checkLogin();
}
});
},
hasLogin: function() {
RunQuery.isLogin = true;
$('body').removeClass('nologin');
$('#login_tip').hide();
},
noLogin: function() {
RunQuery.isLogin = false;
$('body').addClass('nologin');
$('#login_tip').show();
},
queryTicket : function(){
// cn12306.get("leftTicket/query", setting, "json", function (text) {
// var trains = htmlParser.analyzeTicketQueryData(text);
// if (showDlg) {
// if (!trains.length) {
// dlg.setState("block", "未能查询到任何车次,请修改条件或稍后重试。");
// dlg.autoCloseDialog();
// } else {
// dlg.closeDialog();
// }
// }
// callback.call(this, trains);
// }, function (text) {
// if (showDlg)
// dlg.delayExecute(3, runquery, "操作出现网络错误");
// }, "", "leftTicket/init");
var loading = Public.showLoading('正在查票');
cn12306.ajax({
type:"GET",
url: "leftTicket/query",
data: {
"leftTicketDTO.train_date": RunQuery.curData.start_date,
"leftTicketDTO.from_station": RunQuery.curData.startcode,
"leftTicketDTO.to_station": RunQuery.curData.endcode,
"purpose_codes": RunQuery.curData.type == "2" ? "0X00" : "ADULT"
},
refer: "leftTicket/init",
success: function(json) {
// console.log(JSON.stringify(json));
if(json["status"] == true && json["httpstatus"] == 200){
if(json['data'].length > 0){
RunQuery.formatJson(json);
RunQuery.formatList();
}
}
Public.hideLoading(loading);
},
error: function(xhr, type) {
console.log(xhr,type);
Public.hideLoading(loading);
}
});
},
formatList:function(){
var lists = RunQuery.trainData.trainMap,
html = '',
obj={};
for (var k in lists) {
if(!lists[k]['available']){
continue;
}
obj = lists[k];
html += '<li>';
/*第1行*/
html += '<div class="line no_border">';
html += '<strong class="pull_right text_underline text_lg" data-id="'+obj["id"]+'">'+obj["code"]+'</strong>';
html += '<strong class="text_warning text_lg link_label">'+obj["from"]["time"]+'</strong>';
html += '<span class="text_lg">';
if(obj["from"]["code"] == obj["start"]["code"]){
html+='<i class="text_label">始</i>';
}
html += obj["from"]["name"]+'</span>';
html += '</div>';
/*第2行*/
html += '<div class="line">';
ls = obj["elapsedTime"]['total'].split(':');
html += '<span class="pull_right text_gray">'+ (!!ls[0]?ls[0]+'小时':'')+(!!ls[1]?ls[1]+'分':'0分')+'</span>';
html += '<span class="text_lg link_label">';
html += obj["to"]["time"]+'</span>';
html += '<span class="text_lg">'
if(obj["to"]["code"] == obj["end"]["code"]){
html+='<i class="text_label">终</i>';
}
html += obj["to"]["name"]+'</span>';
html += '</div>';
/*输出席别*/
/*商务坐*/
for (var i = 0; i < obj['ticketMapSort'].length; i++) {
obj['ticketMapSort'][i];
if(obj['ticketMapSort'][i]["count"] == 0){
continue;
}
html += '<div class="line"><span class="pull_right">';
if(obj['ticketMapSort'][i]["count"]=='有'){
html+='<span class="text_warning">有</span>';
}else{
html+='<span class="text_warning">'+obj['ticketMapSort'][i]["count"]+'</span>';
html+='<span class="text_gray">张</span>';
}
html+='<a href="javascript:;" class="btn btn_success" data-traincode="'+obj["id"]+'" data-seatcode="'+obj['ticketMapSort'][i]["code"]+'">抢票</a>';
html+='</span>';
html+='<span class="link_label">'+obj['ticketMapSort'][i]['name']+'</span>';
html+='<span class="text_gray">'+(obj['ticketMapSort'][i]['price']/10)+'元</span>';
html+='</div>';
};
html+='</li>';
};
$('#train_list').html(html);
$('.station_title span').html('共&nbsp;'+ $('#train_list li').length +'&nbsp;趟列车');
},
getTicketInfo:function (v) {
var data = [], info = v.indexOf("#") === -1 ? v : /getSelected\(['"](.*?)['"]\)/i.exec(v)[1].split('#')[11],
match = info.match(/([A-Z\d])0*?([\*\d]{5})0*?(\d{4})/gi);
for (var j in match) {
var m = /([A-Z\d])0*?([\*\d]{5})0*?(\d{4})/i.exec(match[j]);
var sc = m[1];
var sp = m[2][0] == '*' ? null : parseInt(m[2], 10);
var st = parseInt(m[3], 10);
var seat = { code: sc, name: Util.toSeatTypeName(sc), price: sp };
if (st < 3000) {
seat.count = st;
//TODO 二等软座提交是否和二等座一样都用的MO
//一等软座 7 二等软座 8
if (sc === "7") {
data.push({ code: 'M', name: Util.toSeatTypeName('M'), price: sp, count: st });
}
else if (sc === "8") {
data.push({ code: 'O', name: Util.toSeatTypeName('O'), price: sp, count: st });
} else {
data.push(seat);
}
} else {
seat.count = st - 3000;
seat.code = '0';
seat.name = "无座";
data.push(seat);
}
};
return data;
},
trainData:null,
formatJson : function(data){
if(!Array.isArray(data['data']) && !data['data'].length){
return null;
}
var lists = data['data'],train,kp,selltimem,trainData={ raw: data, rawTrainMap: {}, trainMap: {}, auto: null, nextTime: null };
for (var i = 0; i < lists.length; i++) {
t = lists[i];
train = {
"id": t["queryLeftNewDTO"]["train_no"],
"code": t["queryLeftNewDTO"]["station_train_code"],
"available": t["queryLeftNewDTO"]["canWebBuy"] === 'Y' ? 1 : 0,
"start": {
"code": t["queryLeftNewDTO"]['start_station_telecode'],
"name": t["queryLeftNewDTO"]["start_station_name"]
},
"from": {
"code": t["queryLeftNewDTO"]['from_station_telecode'],
"fromStationNo": t["queryLeftNewDTO"]['from_station_no'],
"name": t["queryLeftNewDTO"]['from_station_name'],
"endpoint": t["queryLeftNewDTO"]['from_station_telecode'] == t["queryLeftNewDTO"]['start_station_telecode'],
"time": t["queryLeftNewDTO"]['start_time']
},
"to": {
"code": t["queryLeftNewDTO"]['to_station_telecode'],
"toStationNo": t["queryLeftNewDTO"]['to_station_no'],
"name": t["queryLeftNewDTO"]['to_station_name'],
"endpoint": t["queryLeftNewDTO"]['end_station_telecode'] == t["queryLeftNewDTO"]['to_station_telecode'],
"time": t["queryLeftNewDTO"]['arrive_time']
},
"elapsedTime": {
"days": t["queryLeftNewDTO"]['day_difference'],
"total": t["queryLeftNewDTO"]['lishi']
},
"end": {
"code": t["queryLeftNewDTO"]['end_station_telecode'],
"name": t["queryLeftNewDTO"]['end_station_name']
},
"ypinfo": t["queryLeftNewDTO"]['yp_info'],
"ypinfo_ex": t["queryLeftNewDTO"]['yp_ex'],
"locationCode": t["queryLeftNewDTO"]['location_code'],
"controlDay": t["queryLeftNewDTO"]['control_day'],
"supportCard": t["queryLeftNewDTO"]['is_support_card'],
"saleTime": t["queryLeftNewDTO"]['sale_time'],
"secureStr": t['secretStr'],
"selltime": null,
"date": t["queryLeftNewDTO"]['start_train_date'].replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3"),
"limitSellInfo": t['buttonTextInfo'] && t['buttonTextInfo'].indexOf("暂售") != -1 ? t['buttonTextInfo'].replace(/<[^>]+>/i, "") : null
};
kp = RunQuery.getTicketInfo(t["queryLeftNewDTO"]['yp_info']);
train.tickets = kp;
train.ticketMap = Util.mapObject(kp, function (e) { return e.code; });
train.ticketMapSort = Util.sortType(train.ticketMap);
console.log(train.ticketMapSort);
// for (var i = 0; i < train.ticketMapSort.length; i++) {
// if(train.ticketMapSort[i]['count'] == 0){
// train.ticketMapSort.splice(i,1);
// i--;
// }
// };
// //起售时间
selltimem = /(0*(\d+)月0*(\d+)日)?(\d+)\s*点\s*((\d+)分)?\s*起售/i.exec(t.buttonTextInfo.replace(/<.*?>/g, ''));
if (selltimem) {
train.available = -1;
train.selltime = new Date();
train.selltime.setHours(parseInt(selltimem[4]));
train.selltime.setMinutes(parseInt(selltimem[6] || "0", 10));
train.selltime.setSeconds(0);
if (selltimem[1]) {
//带日期
train.selltime.setMonth(parseInt(selltimem[2]) - 1);
train.selltime.setDate(parseInt(selltimem[3]));
if (train.selltime.getMonth() < new Date().getMonth()) {
train.selltime.setFullYear(train.selltime.getFullYear() + 1);
}
}
}
trainData.rawTrainMap[train.id] = t;
trainData.trainMap[train.id] = train;
};
RunQuery.trainData = trainData;
},
dateChangeCallback: function(date) {
var time = date.date.getTime();
if (time >= Public.calendar.minDate.date.getTime() && time <= Public.calendar.maxDate.date.getTime()) {
$('#date_tip').hide();
Public.hideInnerPage('date_box');
$('#start_date').html(Public.calendar.curDate.format(Public.formatString) + ' ' + Public.calendar.curDate.day(3));
$('#start_date_val').val(Public.calendar.curDate.format('yyyy-MM-dd'));
RunQuery.hisUpdata();
console.log(date);
} else {
var offset = $('a.cur', Public.calendar.wrap).offset();
$('#date_tip').css({
'left': offset.left,
'top': offset.top,
'display': 'block'
}).html('<p>' + date.format('M月d日') + '不在预售期</p><a href="#" class="btn btn_m btn_success">预约提醒</a>');
if (offset.left / window.innerWidth > 0.75) {
$('#date_tip').attr('class', 'tip_small tip_right');
} else if (offset.left / window.innerWidth < 0.15) {
$('#date_tip').attr('class', 'tip_small tip_left');
} else {
$('#date_tip').attr('class', 'tip_small');
}
}
},
hisUpdata:function(){
Public.setHisQuery($('#startStationCode').val() + '-' + $('#endStationCode').val(), $('#query_form').serialize());
Public.setHis();
RunQuery.getQueryData();
RunQuery.queryTicket();
}
}
// var transferData = function (data, noProcess) {
// var result = data;
// if (!Array.isArray(result.data) || !result.data.length || !result.data[0].queryLeftNewDTO) {
// exports.events.fireEvent("requestFailed");
// };
// var trainData = { raw: result, rawTrainMap: {}, trainMap: {}, auto: null, nextTime: null };
// _.each(result.data, function (t) {
// var train = {
// id: t.queryLeftNewDTO.train_no,
// code: t.queryLeftNewDTO.station_train_code,
// available: t.queryLeftNewDTO.canWebBuy === 'Y' ? 1 : 0,
// start: {
// code: t.queryLeftNewDTO.start_station_telecode,
// name: t.queryLeftNewDTO.start_station_name,
// },
// from: {
// code: t.queryLeftNewDTO.from_station_telecode,
// fromStationNo: t.queryLeftNewDTO.from_station_no,
// name: t.queryLeftNewDTO.from_station_name,
// endpoint: t.queryLeftNewDTO.from_station_telecode == t.queryLeftNewDTO.start_station_telecode,
// time: t.queryLeftNewDTO.start_time
// },
// to: {
// code: t.queryLeftNewDTO.to_station_telecode,
// toStationNo: t.queryLeftNewDTO.to_station_no,
// name: t.queryLeftNewDTO.to_station_name,
// endpoint: t.queryLeftNewDTO.end_station_telecode == t.queryLeftNewDTO.to_station_telecode,
// time: t.queryLeftNewDTO.arrive_time
// },
// elapsedTime: {
// days: t.queryLeftNewDTO.day_difference,
// total: t.queryLeftNewDTO.lishi
// },
// end: {
// code: t.queryLeftNewDTO.end_station_telecode,
// name: t.queryLeftNewDTO.end_station_name,
// },
// ypinfo: t.queryLeftNewDTO.yp_info,
// ypinfo_ex: t.queryLeftNewDTO.yp_ex,
// locationCode: t.queryLeftNewDTO.location_code,
// controlDay: t.queryLeftNewDTO.control_day,
// supportCard: t.queryLeftNewDTO.is_support_card,
// saleTime: t.queryLeftNewDTO.sale_time,
// secureStr: t.secretStr,
// selltime: null,
// date: t.queryLeftNewDTO.start_train_date.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3"),
// limitSellInfo: t.buttonTextInfo && t.buttonTextInfo.indexOf("暂售") != -1 ? t.buttonTextInfo.replace(/<[^>]+>/i, "") : null
// };
// var kp = getTicketInfo(t.queryLeftNewDTO.yp_info);
// train.tickets = kp;
// train.ticketMap = _.mapObject(kp, function (e) { return e.code; });
// //起售时间
// var selltimem = /(0*(\d+)月0*(\d+)日)?(\d+)\s*点\s*((\d+)分)?\s*起售/i.exec(t.buttonTextInfo.replace(/<.*?>/g, ''));
// if (selltimem) {
// train.available = -1;
// train.selltime = new Date();
// train.selltime.setHours(parseInt(selltimem[4]));
// train.selltime.setMinutes(parseInt(selltimem[6] || "0", 10));
// train.selltime.setSeconds(0);
// if (selltimem[1]) {
// //带日期
// train.selltime.setMonth(parseInt(selltimem[2]) - 1);
// train.selltime.setDate(parseInt(selltimem[3]));
// if (train.selltime.getMonth() < new Date().getMonth()) {
// train.selltime.setFullYear(train.selltime.getFullYear() + 1);
// }
// }
// }
// trainData.rawTrainMap[train.id] = t;
// trainData.trainMap[train.id] = train;
// });
// trainData.original = _.values(trainData.trainMap);
// trainData.available = trainData.original;
// trainData.trainCodes = _.pluck(trainData.original, "code");
// trainData.filtered = [];
// trainData.include = trainData.available;
// // if (!noProcess) {
// // //执行车次预过滤。过滤内容:出发地,目标地,时间
// // exports.events.fireEvent("filterTrains", trainData);
// // //处理车次
// // exports.events.fireEvent("processTrains", trainData);
// // //过滤数据
// // if (trainData.filtered && trainData.filtered.length) {
// // //从原始数据中删除
// // var orgMap = _.mapObject(result.data, function (e) {
// // return e.queryLeftNewDTO.train_no;
// // });
// // var filtered = _.map(trainData.filtered, function (t) {
// // return orgMap[t.id];
// // });
// // trainData.rawDataFiltered = _.without.apply(null, [result.data].concat(filtered));
// // result.data = trainData.rawDataFiltered;
// // }
// // }
// return trainData;
// };