<?php
if (!defined('BASEPATH')) 
	exit('No direct script access allowed');

class pages extends CI_Controller{
	
	public function __construct(){
        parent::__construct();
		//$this->load->library("permissiontrain");
		$this->load->library('session');
		$this->load->model("train_system_model");
		$this->load->model("BIZ_train_model");
		$this->load->helper('train');
		$this->load->helper('cookie');
		$this->order_status_msg = $this->config->item('train_order_status_msg');

		$this->isadmin();
    }

	function isadmin(){
		$OPI_SN = get_cookie("OPI_SN"); //获取对应的cookies
		if ($OPI_SN>0){
			//已登录
		}else{
			//$this->permissiontrain->is_admin();
			redirect(site_url('login/indextrain'));
		}
	}
	
	//首页
	public function index($coli_id = null){
		// if(get_cookie('dingname') == '' && get_cookie('dingunionid') == ''){
		// 	redirect('/apps/dinglogin/login/?returnurl=/apps/trainsystem/pages/');
		// }
		
		if($coli_id == null){
			$cols_id = $this->input->post("ht_order");
		}else{
			$cols_id = $coli_id;
		}
        
        $list=new StdClass;
        if(!empty($cols_id)){
            $cold_sn = $this->BIZ_train_model->get_biz_cold($cols_id);
            $list->wl = $this->BIZ_train_model->get_operatorInfo($cols_id);
            $i=0;
            $list->info=array();
            foreach ($cold_sn as $v) {
                $list->info[$i] = new StdClass;
                $list->info[$i]->people = $this->BIZ_train_model->biz_people($v->COLD_SN);
                $list->info[$i]->train = $this->BIZ_train_model->biz_order_detail($v->COLD_SN);
                $list->info[$i]->status = $this->train_system_model->get_submitStatus($v->COLD_SN); //判断是否提交过
                $i++;
            }
            $list->cols_id=$cols_id;
        }

		// //查询聚合余额
        // $back_data = GetPost_http("http://op.juhe.cn/trainTickets/balance.php?key=79f03107b921ef31310bd40a1415c1cb");
        // $back_data = json_decode($back_data);
        // if(!empty($back_data->result)){
        //     $list->balance = $back_data->result;
        // }else{
        //     $list->balance = "NULL";
        // }
		$list->balance = "NULL";
		// print_r(json_encode($list));
        $this->load->view('common/header');
        $this->load->view('homepage',$list);
        $this->load->view('common/footer'); 
	}
	
	//系统列表页面
	public function order_list(){
		// if(get_cookie('dingname') == '' && get_cookie('dingunionid') == ''){
		// 	redirect('/apps/dinglogin/login/?returnurl=/apps/trainsystem/pages/');
		// }

		$page_size = 10;
        $page = $this->input->get("page");
        $order = $this->input->get("order");
		$web_code = $this->input->get("web_code");
		$channel = $this->input->get("channel");
        $where = "1=1";//搜索条件
        $page_parameter = "";//返回的分页条件参数
        if(empty($page) or !is_numeric($page)){
            $page=0;
        }
        if(!empty($order)){
            $where = "BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR InfoManager.dbo.trainsystem.ts_ordernumber='{$order}' OR InfoManager.dbo.trainsystem.ts_elecnumber='{$order}'";
			//$where2 = "where BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR JOL_JuheOrder='{$order}'";
            $list["order"] = $order;
            $page_parameter = "order=".$order;
        }
		if(!empty($web_code)){
			$where = "BIZ_ConfirmLineInfo.COLI_WebCode='{$web_code}'";
			$page_parameter = "web_code=".$web_code;
		}

		if (!empty($channel)){
			$where = " InfoManager.dbo.trainsystem.ts_channel='{$channel}' ";
			$page_parameter = " channel=".$channel;
		}
		
		//获取订单数据
        $data = $this->train_system_model->get_order($page_size,$page,$where);
		// print_r(json_encode($data));die();
        $list["data"]=$data->list;
        
        $this->load->library('pagination');

        $config['base_url'] = site_url("/apps/trainsystem/pages/order_list?{$page_parameter}");
        $config['total_rows'] = $data->count;
        $config['per_page'] = $page_size;
        $config['page_query_string']=TRUE;
        $config['query_string_segment']="page";
        $config['cur_tag_open'] = '<li class="active"><a href="#">';        
        $config['cur_tag_close'] = '</a></li>';
        $config['first_tag_open']=$config['last_tag_open']=$config['next_tag_open']=$config['prev_tag_open']=$config['num_tag_open']="<li>";
        $config['first_tag_close']=$config['lasbt_tag_close']=$config['next_tag_close']=$config['prev_tag_close']=$config['num_tag_close']="</li>";

        $this->pagination->initialize($config);

        $list["page_link"]=$this->pagination->create_links();


        foreach ($list["data"] as $key => $value) {
			$status = trim($value->ts_status);
            $value->info = $this->order_status_msg[$status];//自定义说明信息;
        }  
                   
        
        $this->load->view('header');
        $this->load->view('order_list',$list);
        $this->load->view('footer');
	}
	
	//订单详情页面
	public function order(){
		// if(get_cookie('dingname') == '' && get_cookie('dingunionid') == ''){
		// 	redirect('/apps/dinglogin/login/?returnurl=/apps/trainsystem/pages/');
		// }
		$ordernumber = $order=$this->input->get("order");
		
		if(empty($ordernumber)){
			exit('参数错误');
		}	
		
		//根据订单号查询订单信息
		$data = array();
		$train_infos = $this->train_system_model->get_order_info($ordernumber);
		$passpager_detail = $this->train_system_model->get_passager_details($ordernumber);
		
		//构造详情数组
		$data['status'] = $train_infos->ts_status;
		$data['ordernumber'] = $train_infos->ts_ordernumber;
		$data['train_date'] = $train_infos->ts_startdate;
		$data['checi'] = $train_infos->ts_checi;
		$data['elecnumber'] = $train_infos->ts_elecnumber;
		$data['from_station_name'] = $train_infos->ts_fromstationame;
		$data['from_station_code'] = $train_infos->ts_fromstationcode;
		$data['to_station_name'] = $train_infos->ts_tostationame;
		$data['to_station_code'] = $train_infos->ts_tostationcode;
		$data['start_time'] = $train_infos->ts_startime;
		$data['arrive_time'] = $train_infos->ts_endtime;
		$data['channel'] = $train_infos->ts_channel;
		$data['msg'] = $train_infos->ts_errormsg;
		$data['passengers'] = $passpager_detail;
		
		// //聚合订单可以查询实时数据
		// if($train_infos->ts_channel == 'juhe'){
		// 	$post_data=array(
        //                 "key"=>"79f03107b921ef31310bd40a1415c1cb",
        //                 "orderid"=>$train_infos->ts_ordernumber
        //                     ); 		
		// 	$back_data = GetPost_http("http://op.juhe.cn/trainTickets/orderStatus",$post_data);
		// 	$data['train_date'] = '';
		// 	$data['start_time'] = json_decode($back_data)->result->start_time;
		// 	$data['arrive_time'] = json_decode($back_data)->result->arrive_time;
		// }
		
	    $this->load->view('bootstrap3/header');
	    $this->load->view('order',$data);
	    $this->load->view('bootstrap3/footer'); 
	}

	//退票页面
    public function refund(){
		// if(get_cookie('dingname') == '' && get_cookie('dingunionid') == ''){
		// 	redirect('/apps/dinglogin/login/?returnurl=/apps/trainsystem/pages/');
		// }
		$ordernumber = $order=$this->input->get("order");
		
		if(empty($ordernumber)){
			exit('参数错误');
		}	
		
		//根据订单号查询订单信息
		$data = array();
		$train_infos = $this->train_system_model->get_order_info($ordernumber);
		$passpager_detail = $this->train_system_model->get_passager_details($ordernumber);
		
		//构造详情数组
		$data['ordernumber'] = $train_infos->ts_ordernumber;
		$data['cold_sn'] = $train_infos->ts_cold_sn;
		$data['train_date'] = $train_infos->ts_startdate;
		$data['checi'] = $train_infos->ts_checi;
		$data['elecnumber'] = $train_infos->ts_elecnumber;
		$data['from_station_name'] = $train_infos->ts_fromstationame;
		$data['from_station_code'] = $train_infos->ts_fromstationcode;
		$data['to_station_name'] = $train_infos->ts_tostationame;
		$data['to_station_code'] = $train_infos->ts_tostationcode;
		$data['start_time'] = $train_infos->ts_startime;
		$data['arrive_time'] = $train_infos->ts_endtime;
		$data['channel'] = $train_infos->ts_channel;
		$data['msg'] = $train_infos->ts_errormsg;
		$data['return_json'] = $train_infos->ts_returncallback;
		$data['passengers'] = $passpager_detail;
		
		//print_r($data);
	    $this->load->view('header');
	    $this->load->view('refund',$data);
	    $this->load->view('footer'); 
        
    }
	
	//改签页面
	public function reschedule(){
		if(get_cookie('dingname') == '' && get_cookie('dingunionid') == ''){
			redirect('/apps/dinglogin/login/?returnurl=/apps/trainsystem/pages/');
		}
		$order = $this->input->get_post('order');
		$data = array();
		$data['order'] = $order;
		if(!empty($order)){
			$orderDetail = $this->train_system_model->ctripOrderDetail($order);
			$data['detail'] = $orderDetail;
		}
		//print_r($data);
		
		$this->load->view('header');
		$this->load->view('reschedule',$data);
		$this->load->view('footer'); 
	}
	
	//账单导出页面
	public function export(){
		// if(get_cookie('dingname') == '' && get_cookie('dingunionid') == ''){
		// 	redirect('/apps/dinglogin/login/?returnurl=/apps/trainsystem/pages/');
		// }
		$this->load->view('header');
		$this->load->view('export');
		$this->load->view('footer'); 
	}

    //澜海账单导出页面
	public function lanhaiExport(){
		$this->load->view('header');
		$this->load->view('export_lanhai');
		$this->load->view('footer'); 
	}

	//预售时间列表
	public function presale_list(){
		$page_size = 10;
        $page = $this->input->get("page");
        $stationcn = $this->input->get("stationcn");
		$web_code = $this->input->get("web_code");
        $where = "1=1";//搜索条件
        $page_parameter = "";//返回的分页条件参数
        if(empty($page) or !is_numeric($page)){
            $page=0;
        }
		if(!empty($stationcn)){
            $where = "  TST_station_cn like '%{$stationcn}%' ";
            $list["stationcn"] = $stationcn;
            $page_parameter = "stationcn=".$stationcn;
        }

		//获取订单数据
		$data = $this->BIZ_train_model->get_presale_list($page_size,$page,$where);
		// print_r(json_encode($data));die();
		$list["data"]=$data->list;
		
		$this->load->library('pagination');

		$config['base_url'] = site_url("/apps/trainsystem/pages/presale_list?{$page_parameter}");
		$config['total_rows'] = $data->count;
		$config['per_page'] = $page_size;
		$config['page_query_string']=TRUE;
		$config['query_string_segment']="page";
		$config['cur_tag_open'] = '<li class="active"><a href="#">';        
		$config['cur_tag_close'] = '</a></li>';
		$config['first_tag_open']=$config['last_tag_open']=$config['next_tag_open']=$config['prev_tag_open']=$config['num_tag_open']="<li>";
		$config['first_tag_close']=$config['lasbt_tag_close']=$config['next_tag_close']=$config['prev_tag_close']=$config['num_tag_close']="</li>";

		$this->pagination->initialize($config);

		$list["page_link"]=$this->pagination->create_links();	
		
		$this->load->view('header');
		$this->load->view('presale_list',$list);
		$this->load->view('footer');

	}

	//预售时间编辑
	public function presale_edit(){
		$ordernumber = $tstid=$this->input->get("tstid");
		
		if(empty($tstid)){
			exit('参数错误');
		}	

		//根据ID号查询信息
		$saletime_detail = $this->BIZ_train_model->get_saletime_detail($tstid);

		$data["info"] = $saletime_detail;
		$this->load->view('header');
		$this->load->view('presale_edit',$data);
		$this->load->view('footer');

	}

	//预售时间编辑保存
	public function presale_editsave(){
		$TST_id = $this->input->get_post("TST_id");
		$TST_station_cn = trim($this->input->get_post("TST_station_cn"));
		$TST_saletime = trim($this->input->get_post("TST_saletime"));
		$TST_station_code = trim($this->input->get_post("TST_station_code"));

		$data = new stdClass();
		$data->TST_id = $TST_id;
		$data->TST_station_cn = $TST_station_cn;
		$data->TST_saletime = $TST_saletime;
		$data->TST_station_code = $TST_station_code;

		$this->BIZ_train_model->update_saletime($data);

		$rUrl = '<script type="text/javascript">';
		$rUrl.= 'alert("修改完成，请查看修改后的信息！！"); window.location.href="/info.php/apps/trainsystem/pages/presale_list";'; // 弹出提示框
		//$rUrl.= 'window.location.href="/info.php/apps/trainsystem/pages/presale_edit?tstid='+$TST_id+'";'; // 跳转到目标页面
		$rUrl.= '</script>';
		echo $rUrl;
	}

	//澜海查询信息
	public function lanhaiMsg(){

		$order = $this->input->get_post("order"); //订单号
		$type =  $this->input->get_post("type"); //出票，退票，账单等类型

		$microtime = get_microtime();  //时间戳
		//生成接口请求头参数
		$timestamp = $microtime;
		$appId = LANHAI_appId;

		if ($type == "orderticket"){
			$url = LANHAI_URL."api/open/get/orderDetails";
		}else if ($type == "returnticket"){
			$url = LANHAI_URL."api/open/get/orderRefundDetails";	
		}

		//拼接发送的报文
		$PostData = new stdClass();
		$PostData->mainOrderId = $order;
		$PostData->timestamp = $timestamp;
		$PostData->appId = $appId;

		$ResponseJson = GetPost_http($url,json_encode($PostData),'json');		
		//log_message('error','澜海出票详细信息：'.$ResponseJson);
		$ResponseData = json_decode($ResponseJson);
		if (isset($ResponseData->data)){
			// //需要解密   
			$this->load->library("aesLanhai");
			$aesUnit = new Security();
			$data = json_decode($aesUnit->decryptData($ResponseData->data));

			$result = array();
			$this->handle_array($data,$type,$result);
			$formattedJson = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
			echo "<pre>$formattedJson</pre>";

		}else{
			$ResultNoticeResponse = new stdClass();
			$ResultNoticeResponse->returnCode = -1;
			$ResultNoticeResponse->success = false;
			$ResultNoticeResponse->returnMsg = "找不到订单数据!";
			$formattedJson = json_encode($ResultNoticeResponse, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
			echo $formattedJson;
		}
	}

	//循环展示JSON
	private function handle_array($arr,$type,&$array_to_fill){
		foreach($arr as $key => $value){
			if(is_array($value) || is_object($value)){
				$array_to_fill[$key] = array();
            	$this->handle_array($value,$type, $array_to_fill[$key]);
			}else{
				if ($type=="orderticket"){ //出票特殊显示
					if ($key == "passengerType"){
						if ($value==0){
							$value = "成人";
						}else if($value == 1){
							$value = "儿童";
						}
					}

					if ($key == "certificateType"){
						if ($value==1){
							$value = "身份证";
						}else if ($value == 2) {
							$value = "护照";
						}else if ($value == 7){
							$value = "回乡证";
						}else  if ($value == 8 ){
							$value = "台胞证";
						}
					}

					if ($key == "status"){
						switch ($value) {
							case 0:
								$value = "待出票";
								break;
							case 1:
								$value = "锁定订单";
								break;
							case 2:
								$value = "已出票";
								break;
							case 3:
								$value = "超时订单";
								break;
							case 4:
								$value = "已驳回";
								break;
							case 6:
								$value = "出票超时";
								break;
							case 12:
								$value = "锁单失败";
								break;
							default:
								# code...
								break;
						}
					}
				}
				$array_to_fill[$key] = $value;
			}
		}
	}


	public function presale_add(){
		$this->load->view('header');
		$this->load->view('presale_add');
		$this->load->view('footer');
	}

	public function presale_addsave(){
		$TST_station_cn = trim($this->input->get_post("TST_station_cn"));
		$TST_saletime = trim($this->input->get_post("TST_saletime"));
		$TST_station_code = trim($this->input->get_post("TST_station_code"));

		$data = new stdClass();
		$data->TST_station_cn = $TST_station_cn;
		$data->TST_saletime = $TST_saletime;
		$data->TST_station_code = $TST_station_code;

		$this->BIZ_train_model->add_saletime($data);

		$rUrl = '<script type="text/javascript">';
		$rUrl.= 'alert("添加完成！！"); window.location.href="/info.php/apps/trainsystem/pages/presale_list";'; // 弹出提示框
		$rUrl.= '</script>';
		echo $rUrl;

	}
}
