<?php

use League\CLImate\TerminalObject\Basic\Json;

defined('BASEPATH') or exit('No direct script access allowed');

class LanHaiTicket extends CI_Controller
{


    public function __construct()
    {
        parent::__construct();
        $this->load->model("BIZ_train_model");
        $this->load->model("train_system_model");
        $this->load->helper('train');
        $this->db_train_zw = $this->config->item('db_train_zw');
        $this->train_zw = $this->config->item('train_zw');
        $this->black_list = $this->config->item('black_list');
        $this->load->library("lanhaidata");

        $this->train_certificateType = $this->config->item('train_certificateType');
        $this->train_refundType = $this->config->item('train_refundType');
    }

    public function index()
    {
        //出票锁单接口: https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/pushorderdetail?mainOrderId=HN1720670129499
        //出票回调接口：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/pushorderresult/
        //退票锁单接口: https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/refundorderdetail?dataId=82033
        //退票回调接口: https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/refundorderresult/
        //退款回调接口：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/refundpriceresult/

        //http://ct.tms.lhticket.com   账号：  GLhaina    密码：123456
    }

    /**
     * @description: 澜海获取锁单接口，通过get方式获取参数mainOrderId（订单号）
     * @return {*}
     * @Date Changed: 
     * 网前地址：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/pushorderdetail?mainOrderId=HN1720670129499
     */
    public function pushOrderDetail()
    {
        //获取订单号
        $mainOrderId = $this->input->get_post("mainOrderId");
        $aes = $this->input->get_post("aes");
        if (strpos($mainOrderId, 'HN') !== false) { //由于我们的订单号是HN开头的，所以这里做下判断

            //根据mainOrderId获取火车票的信息
            $ticketfrom = $this->train_system_model->ticketfrom($mainOrderId);
            if (!empty($ticketfrom)) {
                $cold_sn = $ticketfrom->ts_cold_sn;
                $lanhaiRecord = json_decode($ticketfrom->ts_lanhaiData); //澜海特殊数据字段，保存了选择的出票人员Id

                $data['train'] = $this->BIZ_train_model->biz_order_detail($cold_sn);
                $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($cold_sn)['0']->COLI_ID;
                if (empty($this->BIZ_train_model->get_operatorInfo($coli_id))) {
                    $data['email'] = 'vivi@hainatravel.com';
                } else {
                    $data['email'] = $this->BIZ_train_model->get_operatorInfo($coli_id)['0']->OPI_Email;
                }

                //乘客信息
                $bpe_sn = '';
                if (!empty($lanhaiRecord)) {
                    $bpe_sn = $lanhaiRecord->bpe_sn;
                }

                if (!empty($bpe_sn)) {
                    $data['people_list'] = $this->BIZ_train_model->in_bpesn_people_info($bpe_sn);
                } else {
                    //没有找到选择的人员列表，就查询整个订单的人员列表
                    $people_arr = $this->BIZ_train_model->biz_people($cold_sn);
                    //护照号如果在黑名单的就不自动出票
                    foreach ($people_arr as $people_info) {
                        $bpe_sn .= $people_info->BPE_SN . ',';
                    }
                    $bpe_sn = substr($bpe_sn, 0, strlen($bpe_sn) - 1);
                    $data['people_list'] = $this->BIZ_train_model->in_bpesn_people_info($bpe_sn);
                }

                $AdultNum = 0;
                $ChildNum = 0;
                $i = 0;
                $lanhaiData = new  lanhaiData();
                $lanhaiCountryData = json_decode($lanhaiData->CountryData); //国家三字码基础信息
                $passagersdata = array();
                foreach ($data['people_list'] as $PassagerInfo) {
                    //乘客类型
                    switch ($PassagerInfo->BPE_GuestType) {
                        case 1:
                            $PiaoType = 1;
                            $PiaoTypeName = "成人票";
                            $AdultNum++;
                            break;
                        case 2:
                            $PiaoType = 2;
                            $PiaoTypeName = "儿童票";
                            $ChildNum++;
                            break;
                        default: //外国人应该就两种票吧
                            $PiaoType = 1;
                            $PiaoTypeName = "成人票";
                            break;
                    }

                    //证件类型
                    switch ($PassagerInfo->BPE_PassportType) {
                        case 'Chinese ID':
                            $PassportTypeseId = 1;
                            $PassportTypeseidName = "二代身份证";
                            break;
                        case 'MainlandTravel Permit from Hong Kong and Macau':
                            $PassportTypeseId = 7;
                            $PassportTypeseidName = "回乡证";
                            break;
                        case 'Travel Permit from Hong Kong / Macau':
                            $PassportTypeseId = 7;
                            $PassportTypeseidName = "回乡证";
                            break;
                        case 'Travel Permit from Taiwan':
                            $PassportTypeseId = 8;
                            $PassportTypeseidName = "台胞证";
                            break;
                        default:
                            $PassportTypeseId = 2;
                            $PassportTypeseidName = "护照";
                            break;
                    }

                    $passagersdata[$i] = new stdClass();
                    $passagersdata[$i]->passengerName = chk_sp_name($PassagerInfo->BPE_FirstName . $PassagerInfo->BPE_MiddleName . $PassagerInfo->BPE_LastName);
                    $passagersdata[$i]->passengerType = $PiaoType; //乘客类型，1 成人票，2 儿童票
                    $passagersdata[$i]->passportType = $PassportTypeseId; //证件类型，身份证 1，护照 2，回乡证 7，台胞证 8，外国人永久居留身份证 9，港澳通行证 10，台湾通行证 22，港澳台居民居住证 23
                    $passagersdata[$i]->passportNumber = $PassagerInfo->BPE_Passport; //护照号
                    $passagersdata[$i]->passengerId = $PassagerInfo->BPE_SN;  //乘客ID

                    $regionCode = "";
                    $countryName = "";
                    if (!empty($PassagerInfo->BPE_Nationality)) {
                        $htCode =  $PassagerInfo->BPE_Nationality;
                        if ($htCode == "TW" || $htCode == "HK" || $htCode == "MO") {
                            $regionCode = "CHN";
                            $countryName = "中国";
                        } else {
                            foreach ($lanhaiCountryData as $cItem) {
                                if ($cItem->code == $htCode) {
                                    $regionCode = $cItem->standCode;
                                    $countryName = $cItem->name;
                                    break;
                                }
                            }
                        }
                    }
                    $passagersdata[$i]->regionCode = $regionCode;  //国家简码 美国USA ,中国CHN
                    $passagersdata[$i]->countryName = $countryName; //国家名称 中文名称
                    $passagersdata[$i]->passportExpireDate = date('Y-m-d', strtotime($PassagerInfo->BPE_PassExpdate)); //证件到期
                    $passagersdata[$i]->birthday = date('Y-m-d', strtotime($PassagerInfo->BPE_BirthDate)); //出生日期

                    $i++;
                }


                //拼接发送的报文
                $PostData = new stdClass();
                $PostData->mainOrderId = $mainOrderId;
                $currentTime = date("Y-m-d H:i:s");
                $PostData->expireTime = date("Y-m-d H:i:s", strtotime($currentTime . ' +30 minutes'));
                $PostData->currentTime = $currentTime;
                $PostData->agentCode = LANHAI_appId;
                $PostData->contactMobile = "18877331805";
                $PostData->extendParams = "";

                $PostData->ticketsItems = array();
                $PostData->ticketsItems['0'] = new stdClass();
                $PostData->ticketsItems['0']->deliveryTicketId = $cold_sn; //行程id,cold_sn
                $PostData->ticketsItems['0']->fromStationName = $data['train']->DepartAirport_cn;
                $PostData->ticketsItems['0']->toStationName = $data['train']->ArrivalAirport_cn;
                $PostData->ticketsItems['0']->trainNumber = $data['train']->FlightsNo; //车次
                $PostData->ticketsItems['0']->departTime = date('Y-m-d H:i', strtotime($data['train']->DepartureTime));  //发车时间
                $PostData->ticketsItems['0']->arrivalTime =  date('Y-m-d H:i', strtotime($data['train']->ArrivalTime));  //到达时间
                $PostData->ticketsItems['0']->ticketCount = count($data["people_list"]);

                $PostData->ticketsItems['0']->ticketPrice = $data['train']->adultcost; //车票单价，单位（元）

                $seatName =  $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称,中文
                $PostData->ticketsItems['0']->seatName = $seatName;
                $PostData->ticketsItems['0']->acceptSeats = array(); //坐席选项
                $lanhaiSeatTypes = json_decode($lanhaiData->seatTypes); //座位选项
                foreach ($lanhaiSeatTypes as $seatItem) {
                    if ($seatItem->seatName == $seatName) {
                        $PostData->ticketsItems['0']->acceptSeats = $seatItem->seatItems;
                        break;
                    }
                }
                $acceptSeatRemark = "优先出【同排ABCDF座】，无法满足可出任意座位，不接受站票";
                if (($AdultNum + $ChildNum) > 1) {
                    //多人时
                    if (strstr($seatName, "卧")) {
                        $acceptSeatRemark = "客人想要2张下铺，最好在同一房间。下铺不足时，至少保证在同一房间，否则不要出票";
                    }
                } else {
                    //单人时
                }

                $PostData->ticketsItems['0']->acceptSeatRemark = $acceptSeatRemark; //行程坐席要求
                $PostData->ticketsItems['0']->ticketType = 1;
                $PostData->ticketsItems['0']->passengerInfos = $passagersdata;

                $total_price = $AdultNum * $data['train']->adultcost + $ChildNum * $data['train']->childcost; //总价
                $PostData->orderPrice = $total_price;  //订单总价，单位（元）

                //加密方式显示
                $this->load->library("aesLanhai");
                $aesUnit = new Security();
                $resultData = $aesUnit->encryptData(json_encode($PostData));

                //$resultData = $aesUnit->decryptData($resultData); //测试加解密是否正常。

                if ($aes == "false") {
                    //加个明文显示判断，用来检查数据
                    $resultData =  json_encode($PostData, JSON_UNESCAPED_UNICODE);
                }


                echo $resultData;
            } else {
                $ResultNoticeResponse = new stdClass();
                $ResultNoticeResponse->returnCode = -1;
                $ResultNoticeResponse->success = false;
                $ResultNoticeResponse->returnMsg = "mainOrderId错误！";
                echo json_encode($ResultNoticeResponse);
            }
        }
    }


    /**
     * 出票结果回调信息
     * 网前URL：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/pushorderresult/
     */
    public function pushOrderResult()
    {
        $back_json = file_get_contents('php://input');
        log_message('error', '澜海出票回调信息：' . $back_json);

        $lanhai_backdata = json_decode($back_json);


        if (!empty($lanhai_backdata)) {
            //判断回调信息是否正确，主要判断是否是本企业的回调信息
            $companyId = LANHAI_appId;
            $messageIdentity = $lanhai_backdata->authentication->appId; //传递的企业ID
            $ResultNoticeResponse = new stdClass();
            if ($companyId == $messageIdentity) {
                $ResultNoticeResponse->retCode = 0;
                $ResultNoticeResponse->success = true;
                $ResultNoticeResponse->message = "处理成功！";
            } else {
                $ResultNoticeResponse->returnCode = -1;
                $ResultNoticeResponse->success = false;
                $ResultNoticeResponse->returnMsg = "appId错误！";
            }
            echo json_encode($ResultNoticeResponse);

            //处理回调的内容，保存到本地及翰特
            $update_data = new stdClass();
            $update_data->ServiceName = "lanhai.ticketresult";
            $update_data->ordernumber = '';
            $update_data->seatsinfo = '';
            $update_data->TicketCheck = '';
            $update_data->bookcallback = '';
            $update_data->confirmcallback = '';
            $update_data->returncallback = '';
            $update_data->OrderTotleFee = 0;
            $update_data->ElectronicOrderNumber = '';
            $update_data->reschedulecallback = '';
            $update_data->OrderTicketTime = '';
            $update_data->operateTradeNo = "";

            if (!empty($lanhai_backdata->bodyInfo)) {

                // //需要解密   
                $this->load->library("aesLanhai");
                $aesUnit = new Security();
                $bodyINfo = json_decode($aesUnit->decryptData($lanhai_backdata->bodyInfo));

                if ($bodyINfo->failCode == 0) {
                    $update_data->OrderStatus = '4';
                    if (isset($bodyINfo->resultMsg)) {
                        $update_data->ErrorMsg =   $bodyINfo->resultMsg;
                    } else {
                        $update_data->ErrorMsg =  '出票成功';
                    }
                } else {
                    $update_data->OrderStatus = '5';
                    if (isset($bodyINfo->resultMsg)) {
                        $update_data->ErrorMsg = $bodyINfo->resultMsg;
                    } else {
                        $update_data->ErrorMsg = '出票失败';
                    }
                }
                $update_data->ordernumber = $lanhai_backdata->authentication->mainOrderId;
                if (isset($bodyINfo->orderPrice)) {
                    $update_data->OrderTotleFee = $bodyINfo->orderPrice;   //总价
                }
                if (isset($bodyINfo->payTradeNumber)) {
                    $update_data->operateTradeNo = $bodyINfo->payTradeNumber;  ////支付宝流水
                }

                $update_data->ticketresultcallback = json_encode($bodyINfo);
                //$update_data->OrderTicketTime = $lanhai_backdata->TrainOrderService->OrderInfo->TicketInfo->OrderTicketTime;

                //新接口数据,不一定保存到数据库里面，原订单已有，做个记录
                if (isset($bodyINfo->ticketSuccessTime)) {
                    $update_data->ticketSuccTime = $bodyINfo->ticketSuccessTime;  //出票成功时间
                }
                // $update_data->orderType = $lanhai_backdata->ticketResult->orderMasterInfo->orderType; //订单类型 0电子票 1配送票 2人工客票 3抢票订单
                // $update_data->contactName = $lanhai_backdata->ticketResult->orderMasterInfo->contactName; //联系人
                // $update_data->mobileNo = des_decrypt($lanhai_backdata->ticketResult->orderMasterInfo->mobileNo,$key); //联系电话 (DES加密）

                //人员及车票
                if (isset($bodyINfo->eOrderNumber)) {
                    $elecNo = $bodyINfo->eOrderNumber; //电子订单号，即12306取票号
                    $update_data->ElectronicOrderNumber = $elecNo;
                }

                if (isset($bodyINfo->ticketList)) { //如果订票成功，需要保存的数据                    
                    $data_passager = new stdClass();
                    foreach ($bodyINfo->ticketList as $tItems) {

                        if (isset($tItems->ticketCheck)) {
                            $checkWindow = $tItems->ticketCheck; //检票口
                            $update_data->TicketCheck = $checkWindow;
                        }

                        $update_data->trainNo = $tItems->trainNumber; //车次
                        $update_data->departTime = $tItems->departTime; //车次出发时间	

                        foreach ($tItems->passengerList as $pItems) {
                            $data_passager->ordernumber = $update_data->ordernumber;
                            //人员列表
                            $data_passager->status = '4';
                            $certificateType = $this->train_certificateType[$pItems->passportType]; //证件类型，身份证 1，护照 2，回乡证 7，台胞证 8，外国人永久居留身份证 9，港澳通行证 10，台湾通行证 22，港澳台居民居住证 23
                            $data_passager->identitytype = $certificateType;
                            $data_passager->realname = $pItems->passengerName;
                            $data_passager->numberid = $pItems->passportNumber;   //证件号码 
                            //$data_passager->birthday = $pItems->birthday;
                            if ($pItems->passengerType == 2) {
                                $passengerType = "儿童";
                            } else {
                                $passengerType = "成人";
                            }
                            $data_passager->ticketype = $passengerType;  //乘客类型  1成人 2儿童
                            $data_passager->seatype =  $pItems->seatName; //坐席类型
                            $data_passager->ticketprice = $pItems->realTicketPrice; //实际单价（元）
                            $SeatNo = "";
                            if (isset($pItems->carriageNo)) {
                                $SeatNo .= $pItems->carriageNo . "车厢";
                            }
                            if (isset($pItems->seatNo)) {
                                $SeatNo .= $pItems->seatNo; ////坐席号
                            }
                            $data_passager->seatdetail = $SeatNo;

                            $passengerId = $pItems->passengerId; // //乘客id
                            $data_passager->longtrainno =  $passengerId;

                            $jsonLanhaiData = new stdClass(); //澜海退票需要传递一些数据，尽量保存到这个里面。这样不用从翰特里面读取了。
                            $jsonLanhaiData->eOrderNumber = $update_data->ElectronicOrderNumber; //取票号
                            $data_passager->lanhaiData = json_encode($jsonLanhaiData);

                            //入库
                            $this->train_system_model->add_passagers($data_passager);
                        }

                        /****************************************************************************************/
                        //添加支付记录
                        $add_train_payment_data = new stdClass();
                        $add_train_payment_data->TOC_Memo = $update_data->ordernumber . '出票费';
                        $add_train_payment_data->TOC_VEI_SN = "33653";

                        //根据订单号获取cold_sn
                        $order_info = $this->train_system_model->get_order_info($update_data->ordernumber);
                        $cold_sn = $order_info->ts_cold_sn;
                        $add_train_payment_data->TOC_COLD_SN = $cold_sn;
                        $add_train_payment_data->TOC_TrainNumber = $update_data->trainNo;
                        $add_train_payment_data->TOC_DepartureDate = date('Y-m-d', strtotime($update_data->departTime));
                        $add_train_payment_data->TOC_TicketCost = $update_data->OrderTotleFee;
                        $passengerNum = $tItems->ticketCount; //车票数
                        if ($passengerNum>0){
                            $poundage = $passengerNum*10;
                        }else{
                            $poundage = 0;
                        }
                        $add_train_payment_data->poundage = $poundage;  //手续费 
                        $add_train_payment_data->FOI_TrainNetOrderNo = $update_data->ElectronicOrderNumber; //电子票号
                        //print_r($add_train_order_data);die();
                        $this->BIZ_train_model->add_train_payment($add_train_payment_data);
                        //记录供应商(瀚特)
                        $this->BIZ_train_model->update_cold_planvei_sn($cold_sn, '33653');
                    }
                }
            }

            //更新订单信息(出票系统)
            $this->train_system_model->update_orders($update_data);
        }
    }


    /**
     * 澜海退票锁单接口，通过get方式获取前参数dataId
     * 网前地址：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/refundorderdetail?dataId=82033
     */
    public function refundOrderDetail()
    {
        //获取客人ID
        $dataId = $this->input->get_post("dataId");
        $aes = $this->input->get_post("aes");

        //根据客人ID获取退票数据
        $passenger_data = $this->train_system_model->get_passenger_byId($dataId);
        if (!empty($passenger_data)) {
            //拼接发送的报文
            $PostData = new stdClass();
            $PostData->id = $passenger_data->tst_id; //dataId
            $PostData->mainOrderId = $passenger_data->tst_ordernumber; //出票订单id，如产生过线上改签成功，则使用改签的dataId
            $PostData->priority = 1; //0紧急退票，1非紧急退票  默认1

            //获取出票是保存的lanhaiData
            if (!empty($passenger_data->tst_lanhaiData)){
                $lanhaiData = json_decode($passenger_data->tst_lanhaiData);
            }

            $eOrderNumber = "";
            if (isset($lanhaiData->eOrderNumber)){
                $eOrderNumber = $lanhaiData->eOrderNumber; //取票号
            }

            $PostData->eOrderNumber = $eOrderNumber; //取票号
            $PostData->passengerType = $passenger_data->tst_ticketype."票"; //票种
            $PostData->passportType = $passenger_data->tst_identitytype; //"身份证"; //证件类型
            $PostData->passportName = $passenger_data->tst_realname; //姓名
            $PostData->passportNumber = $passenger_data->tst_numberid; //证件号
            $PostData->departStation = $passenger_data->ts_fromstationame; //发站
            $PostData->arriveStation = $passenger_data->ts_tostationame; //到站

            $rPrice = $passenger_data->tst_ticketprice;
            $PostData->ticketPrice = $rPrice; //票价（元）
            $PostData->preRefundPrice = $rPrice; //原票价（元）
            $PostData->percent = 100; //比例  默认100,我只取返回记录的价格。不管汉特的价格

            $PostData->trainNo = $passenger_data->ts_checi ; //车次

            //车厢及座位分解
            $tst_seatdetail = $passenger_data->tst_seatdetail;
            $carriageNo = "";
            $seatNo = "";
            if (strpos($tst_seatdetail,"车厢")!=false){
                $arrSeat = explode("车厢",$tst_seatdetail);
                $carriageNo = $arrSeat[0];
                $seatNo = $arrSeat[1];
            }
            $PostData->carriageNo = $carriageNo; //车厢
            $PostData->seatName = $passenger_data->tst_seatstype; //席别
            $PostData->seatNo = $seatNo; //席位号

            $strDt = $passenger_data->ts_startdate." ".$passenger_data->ts_startime;
            $DepartureTime = date('Y-m-d H:i', strtotime($strDt)); 

            // 出发时间前三十分钟的时间
            $thirtyMinutesAgo = strtotime('-30 minutes', strtotime($DepartureTime)); 
            $dealine =  date('Y-m-d H:i', $thirtyMinutesAgo);

            $PostData->ticketTime = $DepartureTime; //发车时间
            $PostData->createTime = ""; //可空
            $PostData->deadline = $dealine; //处理截止时间  建议最晚处理时间设置为发车前30分钟
            $PostData->refundTime = ""; //可空
            $PostData->getTicketTime = ""; //可空
            $PostData->refundPrice = 0; //可空
            $PostData->firstImage = null; //可空
            $PostData->secondImage = null; //可空
            $PostData->lockStatus = 0; //可空
            $PostData->lockUser = ""; //可空
            $PostData->status = 0; //可空
            $PostData->longEOrderNumber = ""; //可空
            $PostData->extendParams = ""; //拓展json对象

            //加密方式显示
            $this->load->library("aesLanhai");
            $aesUnit = new Security();
            $resultData = $aesUnit->encryptData(json_encode($PostData));
            //$resultData = $aesUnit->decryptData($resultData); //测试加解密是否正常。
            if ($aes == "false") {
                //加个明文显示判断，用来检查数据
                $resultData =  json_encode($PostData, JSON_UNESCAPED_UNICODE);
            }

            echo $resultData;

        } else {
            $ResultNoticeResponse = new stdClass();
            $ResultNoticeResponse->returnCode = -1;
            $ResultNoticeResponse->success = false;
            $ResultNoticeResponse->returnMsg = "dataId错误！";
            echo json_encode($ResultNoticeResponse);
        }
    }


    /**
     * 澜海退票返回信息
     * 网前URL：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/refundorderresult/
     */
    public function refundOrderResult()
    {
        $back_json = file_get_contents('php://input');
        log_message('error', '澜海退票回调信息：' . $back_json);

        $lanhai_backdata = json_decode($back_json);
        if (!empty($lanhai_backdata)) {
            $dataId = $lanhai_backdata->id;
            //根据客人ID获取退票数据
            $passenger_data = $this->train_system_model->get_passenger_byId($dataId);
            $ResultNoticeResponse = new stdClass();
            if (!empty($passenger_data)) {
                $ResultNoticeResponse->retCode = 0;
                $ResultNoticeResponse->success = true;
                $ResultNoticeResponse->message = "处理成功！";
                echo json_encode($ResultNoticeResponse);


                //处理回调的内容，保存到本地及翰特
                $update_data = new stdClass();
                $update_data->ServiceName = '';
                $update_data->ordernumber = '';
                $update_data->seatsinfo = '';
                $update_data->TicketCheck = '';
                $update_data->bookcallback = '';
                $update_data->confirmcallback = '';
                $update_data->returncallback = '';
                $update_data->OrderTotleFee = 0;
                $update_data->ElectronicOrderNumber = '';
                $update_data->reschedulecallback = '';
                $update_data->OrderTicketTime = '';
                //新字段
                $update_data->operateTradeNo ="";

                $update_data->ordernumber = $passenger_data->tst_ordernumber;
                $passpager_info = new stdClass();
				$passpager_info->returncallback = $back_json;
				$passpager_info->ordernumber = $passenger_data->tst_ordernumber;
				$passpager_info->tst_id = $dataId; //乘客ID，用来更新
                //回调的数据正确，开始判断成功还是失败。
                if (isset($lanhai_backdata->refundPrice)){ //如果有退款金额，说明退票成功
                    //退票成功
					$update_data->OrderStatus = '7';
					//退票时还需要单独对对每个乘客存储回调信息
					$passpager_info->status = '7';
                    $refundPrice = $lanhai_backdata->refundPrice; //退款金额
                    $update_data->ErrorMsg = "退票成功,"."退票金额:".$refundPrice;

                    //退票手续费保存到数据库
					//翰特添加退款记录
					$returnticket = new stdClass();
					$return_order = $update_data->ordernumber;				
					$returnticket->TOC_VEI_SN = "33653";
						
					//根据订单号获取cold_sn
					$cold_sn = $passenger_data->ts_cold_sn;
					$returnSuccTime = date("Y-m-d H:i:s");

					$memo = $return_order.'_退票成功_' . $dataId; //退票集合信息 ，用$dataId是为了标识唯一性
					$returnticket->TOC_Memo = $memo;
					$returnticket->TOC_COLD_SN = $cold_sn;
					$returnticket->TOC_TrainNumber = $passenger_data->ts_checi;
					$returnticket->TOC_DepartureDate = $passenger_data->ts_startdate;
					$returnticket->TOC_TicketCost = -15;
					//print_r($add_train_payment_data);die();
					$this->BIZ_train_model->returnticket_train($returnticket);

                }else{
                    //退票失败
					$update_data->OrderStatus = '8';
					//失败也保存下信息
					$passpager_info->status = '8';
                    $update_data->ErrorMsg = "退票失败:".$lanhai_backdata->failReason;
                }

                $this->train_system_model->return_update_passager_lanhai($passpager_info);
                $update_data->returncallback = $back_json;	

                //更新订单信息(出票系统)
			    $this->train_system_model->update_orders($update_data);

            } else {
                $ResultNoticeResponse->returnCode = -1;
                $ResultNoticeResponse->success = false;
                $ResultNoticeResponse->returnMsg = "退票订单数据没找到!";
                echo json_encode($ResultNoticeResponse);
            }
        }
    }

    /**
     * 澜海退款回调信息
     * 网前URL：https://www.mycht.cn/info.php/apps/trainsystem/lanhaiticket/refundpriceresult/
     */
    public function refundPriceResult(){
        $back_json = file_get_contents('php://input');
        log_message('error', '澜海退款回调信息：' . $back_json);

        $lanhai_backdata = json_decode($back_json);
        if (!empty($lanhai_backdata))
        {
            $id = $lanhai_backdata->id; //线上低改高后的订单为dataId，其他情况为出票的mainOrderId
            //先判断是否是低改高的订单，目前我们没有改签。
            if (1==2){
                //这里是改签的操作，目前没有
            }else{
                //这里的ID是mainOrderId ，出票订单ID
                $order_info = $this->train_system_model->get_order_info($id);
                if (!empty($order_info)){
                    $ResultNoticeResponse = new stdClass(); 
                    $ResultNoticeResponse->retCode = 0;
                    $ResultNoticeResponse->success = true;
                    $ResultNoticeResponse->message = "处理成功！";
                    echo json_encode($ResultNoticeResponse); //找到订单 对应数据就返回处理成功的结果，后面的错误不关澜海那边的事。
    
    
                    //处理回调的内容，保存到本地及翰特
                    $update_data = new stdClass();
                    $update_data->ServiceName = '';
                    $update_data->ordernumber = '';
                    $update_data->seatsinfo = '';
                    $update_data->TicketCheck = '';
                    $update_data->bookcallback = '';
                    $update_data->confirmcallback = '';
                    $update_data->returncallback = '';
                    $update_data->OrderTotleFee = 0;
                    $update_data->ElectronicOrderNumber = '';
                    $update_data->reschedulecallback = '';
                    $update_data->OrderTicketTime = '';
                    //新字段
                    $update_data->operateTradeNo ="";


                    $isOnline =  $lanhai_backdata->isOnline; //1：线上退款，0：线下退款
                    if ($isOnline==1){
                        $refundType = "线上退款";
                    }else{
                        $refundType = "线下退款";
                    }
                    $refundTime =  date("Y-m-d H:i:s"); //退款时间
                    $return_money = $lanhai_backdata->refundPrice; //退款金额，单位元
                    $refundId = $lanhai_backdata->refundId; //退款唯一id(幂等性）
        
                    $update_data->ordernumber = $order_info->ts_ordernumber;
                    $update_data->OrderStatus = '11'; //11是订单退款
                    
                    $update_data->ErrorMsg = '退款:'.$refundType." 金额:".$return_money."  time:". $refundTime;
                    $update_data->refundcallback = $back_json;
        
                    //翰特添加退款记录
                    $refund_train_payment = new stdClass();
                    $return_order = $order_info->ts_ordernumber;                
                    $refund_train_payment->TOC_VEI_SN = "33653";
                
                    $cold_sn = $order_info->ts_cold_sn;
                    //print_r($order_info);
        
                    $memo = $return_order.'_'.$refundType. '_' . $refundId; //退款集合信息
                    $refund_train_payment->TOC_Memo = $memo;
                    $refund_train_payment->TOC_COLD_SN = $cold_sn;
                    $refund_train_payment->TOC_TrainNumber = $order_info->ts_checi;
                    $refund_train_payment->TOC_DepartureDate = $order_info->ts_startdate;
                    $refund_train_payment->TOC_TicketCost = -$return_money;
                    //print_r($add_train_payment_data);die();
                    $this->BIZ_train_model->refund_train_payment($refund_train_payment);

                    //更新订单信息(出票系统)
			        $this->train_system_model->update_orders($update_data);

                }else{
                    $ResultNoticeResponse = new stdClass();
                    $ResultNoticeResponse->returnCode = -1;
                    $ResultNoticeResponse->success = false;
                    $ResultNoticeResponse->returnMsg = "订单对应数据没找到!";
                    echo json_encode($ResultNoticeResponse);
                }
            }


           


        }
    }
}
   
   /* End of file lanhaiticket.php */
