<?php

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

class Tulanduo
{
    protected $ci;

    /*! Live */
    /*!
        目的地
        $this->userId = "1134";
        $this->key    = "73d180d05d425fd192e1c5b3097e75ff";
        桂林海纳国旅
        $this->userId = "18";
        $this->key    = "d05c25e6e6c5d4898161e0aaf700d9c7";
     */
    private $send_host = array(
        "30" => array(
            "userId" => 1134
            ,"key" => "73d180d05d425fd192e1c5b3097e75ff"
        )
        ,"1" => array(
            "userId" => 18
            ,"key" => "d05c25e6e6c5d4898161e0aaf700d9c7"
        )
    );
    /*!
     * test:
     */
    // private $send_host = array(
    //     "30" => array(
    //         "userId" => 6035
    //         ,"key" => "3bd16efd5f4165378f144da1f4829996"
    //     )
    //     ,"1" => array(
    //         "userId" => 6035
    //         ,"key" => "3bd16efd5f4165378f144da1f4829996"
    //     )
    // );

    // userId key
    // 1343 2e47c3721e3ff6e816fe6b928d7acc7d
    // 29188 95c3b0d958a79a1216e651df182b3cb4
    // 30548 9db75a2dc17156eb122364295804b7a2

    // test:
    // public $list_url     = "http://ltdj.ltsoftware.net:19919/action/api/searchRouteOrder/";
    // public $detail_url   = "http://ltdj.ltsoftware.net:19919/action/api/detailRouteOrder/";
    // public $neworder_url = "http://ltdj.ltsoftware.net:19919/action/api/addOrUpdateRouteOrder/";
    // public $neworder_url = "http://ltdj.ltsoftware.net:18888/action/api/addOrUpdateRouteOrder/";
    // Live
    public $list_url     = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/";
    public $detail_url   = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/";
    public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/";

    private $tulanduo_trippest_pag = array();
    private $tulanduo_trippest_code = array();

    public function __construct(){
        $this->ci =& get_instance();
        mb_regex_encoding("UTF-8");
        bcscale(4);
        $this->ci->load->helper('array');
        $this->ci->load->library('trippest');
        $this->ci->load->model('Group_model');
        $this->ci->load->model('orders_model');
        $this->ci->load->model('BIZ_orders_model', 'BIZ_order');
        $this->ci->load->model('TuLanDuo_queryContentBuilder', 'tld_order');
        $this->ci->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder');
        // $this->output->enable_profiler(TRUE);

        $this->vendor_ids = array(1343,30548,29188);
    }

    public function order_push($order=null, $set_pvt=0)
    {
        // 初始化所有Trippest合作项目的包价产品
        $this->tulanduo_trippest_pag = $this->ci->BIZ_order->get_packageDetails('', implode(',', $this->vendor_ids));
        $this->tulanduo_trippest_code = array_map(function($ele){return mb_strtoupper($ele->PAG_Code);}, $this->tulanduo_trippest_pag);
        $this->tulanduo_trippest_pag = array_combine($this->tulanduo_trippest_code, $this->tulanduo_trippest_pag);

        // 目的地计划
        if (strval($order->GRI_OrderType) === "227002" && strval($order->department) === "30") {
            return $this->push_trippest($order);
        }
        // 商务
        if (strval($order->GRI_OrderType) === "227002") {
            return $this->push_biz($order, $set_pvt);
        }
        // 传统订单
        if (strval($order->GRI_OrderType) === "227001") {
            return $this->push_tour($order, $set_pvt);
        }

        return "[Tulanduo>order_push] No function match. ";
    }

    /*!
     * 发送线路订单计划
     */
    public function push_tour($vas=null, $set_pvt=0)
    {
        $gri_sn = $vas->GRI_SN;
        $vas_sn = $vas->VAS_SN;
        $vei_sn = $vas->VAS_VEI_SN;
        $grd_info = $this->ci->Group_model->get_vendor_plan_info($gri_sn, $vei_sn);
        if (empty($grd_info)) {
            $this->ci->Group_model->set_plan_received($vas_sn);
            return false;
        }
        $guestlist = $this->ci->orders_model->get_customer_list($gri_sn);
        $request_info = $this->ci->Group_model->get_plan_request($gri_sn);
        $plan_remark = $this->ci->Group_model->get_plan_remark($gri_sn, $vei_sn);
        $plan_remark = strval($plan_remark)==='' ? '' : "请导游准备: " . $plan_remark;
        /**
         * TODO:团队类型? 先写2
         * ??是否同一天含多个包价项目
         */
        /*!
        // 同一天含多个包价产品时, 需要先合并.避免丢失
        $all_trippest_package = array_filter(array_map(function ($ele){return $ele->pag_code_arr;}, $grd_info));
        $reduce_package_code = array();
        foreach ($all_trippest_package as $ktp => $vtp) {
            $reduce_package_code = array_merge($reduce_package_code, $vtp);
        }
        $reduce_package_code = array_filter($reduce_package_code);
         */
        $grd_apart_info = $this->tour_apart($grd_info, $set_pvt);
        $big_order_index = 0;
        $expect_order_cnt = count($grd_apart_info['com'])+intval(!empty($grd_apart_info['big_pvt']))+intval(!empty($grd_apart_info['pvt']));
        foreach ($grd_apart_info as $group_key => $grd_a) {
            $big_order_index = $this->tour_apart_order_exec($group_key, $vas, $request_info, $guestlist, $grd_a, $big_order_index, $plan_remark);
        }
        if ($big_order_index === $expect_order_cnt) {
            /** VendorArrangeState VAS_IsReceive */
            $this->ci->Group_model->set_plan_received($vas_sn);
        }
        return "[Tulanduo>push_tour] Done. ";
    }

    /*!
     * @Author: LYT
     * @Date: 2019-05-30 16:11:34
     * @Desc: 执行发送订单计划信息. 参数已拆分归类好的行程
     */
    public function tour_apart_order_exec($group_type, $vas, $request_info, $guestlist=null, $grd, $total_order_index, $plan_remark=null)
    {
        if (empty($grd)) {
            return $total_order_index;
        }
        $userId  = $this->send_host["1"]["userId"];
        $userKey = $this->send_host["1"]["key"];
        $destination = $grd['details'][0]->tocity;
        $destination_code = $grd['details'][0]->citycode;
        if (empty($destination)) {
            $vendor_city = $this->ci->Group_model->get_vendor_city($vas->VAS_VEI_SN);
            $destination = $vendor_city->cityname;
            $destination_code = $vendor_city->citycode;
        }
        switch ($group_type) {
            case 'big_pvt':
                $total_order_index ++;
                $all_grd = array($grd);
                $routeName = "中华游" . $destination . "常规线路";
                $routeType = $routeName;
                $agcOrderNo = $vas->GRI_Name;
                // $agcOrderNo .= "(" . $vas->operator . ")";
                $order_type = 1;
                break;
            case 'pvt':
                $total_order_index ++;
                $all_grd = array($grd);
                $routeName = empty($grd['details'][0]->GRD_Landscape) ? $grd['details'][0]->PAG_Title : $grd['details'][0]->GRD_Landscape;
                $routeName .= "(" . $grd['details'][0]->PAG_Code . ")";
                $routeType = $destination . "目的地线路";
                $agcOrderNo = $vas->GRI_Name;
                // $agcOrderNo .= "(" . $vas->operator . ")";
                $order_type = 1;
                break;
            case 'com':
            default:
                $all_grd = ($grd);
                $order_type = 2;
                break;
        }
        foreach ($all_grd as $ko => $vo) {
            if ($order_type === 2) {
                $total_order_index ++;
                $routeName = $vo['PAG_Name'];
                if (empty($routeName)) {
                    $routeName = $vo['details'][0]->GRD_Landscape . "(" . $vo['details'][0]->PAG_Code . ")";
                }
                $routeType = $destination . "目的地线路";
                $agcOrderNo = $vas->GRI_Name;
                // $agcOrderNo .= "(" . $vas->operator . ")";
            }
            $first_date = $vo['details'][0]->day_no_raw;
            $last_date = COUNT($vo['details'])-1;
            $end_date = $vo['details'][$last_date]->day_no_raw;
            $this->ci->tldOrderBuilder->resetBizContent();
            $this->ci->tldOrderBuilder->setUserId($userId)
                                    ->setKey($userKey)
                                    ->setOrderType($order_type)
                                    ->setRouteName($routeName)
                                    ->setRouteType($routeType)
                                    ->setAgcOrderNo($agcOrderNo)
                                    ->setAdultNum(intval($vo['details'][0]->ACI_PersonNum))
                                    ->setChildNum(intval(bcadd($vo['details'][0]->ACI_ChildNum, $vo['details'][0]->ACI_BabyNum)))
                                    // ->setDestination($destination)
                                    ->setDestination("海纳常规系列")
                                    ->setTravelDate($first_date)
                                    ->setLeavedDate($end_date)
                                    // ->setRoomStandard($request_info->GCI_HotelRequest)   // 住房标准
                                    ->setRouteStandard($request_info->GCI_Request) // 行程服务标准
                                    ->setOperationUserName('常彩荣')
                                    ;
            // 订单备注
            if (strval($plan_remark) !== '') {
                $this->ci->tldOrderBuilder->setOrderRemark($plan_remark);
            }
            $from_country = ""; // 客源地
            if ($guestlist===null) {
                // 商务订单的客人列表
                $g_cold_str = array_map(function ($ele){return $ele->GRD_COLD_SN;}, $vo['details']);
                $guestlist = $this->ci->BIZ_order->get_guestlist(implode(',',$g_cold_str));
                $from_country = current(array_filter(array_map(function ($ele){return $ele->Country;},$guestlist)));
                // 联系人
                $biz_contact = $this->ci->BIZ_order->get_customer_contact(implode(',',$g_cold_str));
                $guestlist[0]->phone = $biz_contact->phone;
                if (strval($from_country)==='') {
                    $from_country = $biz_contact->Country;
                }
            }
            foreach ($guestlist as $key => $vg) {
                $this_otherinfo = "";
                $this->ci->tldOrderBuilder->setCustomersName($key, $vg->MemberName )
                                        ->setCustomersPeopleType($key, (calc_age_type($vg->BirthDay)==1 ? "成人" : "儿童"))
                                        ->setCustomersDocumentType($key, "护照") // Passport No.
                                        ->setCustomersDocumentNo($key, $vg->PassportNo)
                                        ->setCustomersPhoneNo($key, $vg->phone);
                if (strval($vg->Country) !== '') {
                    $this_otherinfo .= $vg->Country;
                    $from_country = strval($from_country) === '' ? $vg->Country : $from_country;
                }
                if (strval($vg->Gender) !== '') {
                    $this_otherinfo .= "; " . $vg->Gender;
                }
                if (strval($vg->BirthDay) !== '') {
                    $this_otherinfo .= "; 生日:". substr($vg->BirthDay,0,10) . "; " . calc_age($vg->BirthDay) . "岁";
                }
                if (strval($vg->PassportValidDate) !== '') {
                    $this_otherinfo .= "; 护照有效期:" . $vg->PassportValidDate;
                }
                $this->ci->tldOrderBuilder->setCustomersOtherInfo($key, $this_otherinfo);
            }
            // 客源地
            $this->ci->tldOrderBuilder->setCustomerFromCity($from_country);
            // 补全空的日期,行程为空
            $date1 = new DateTime($first_date);
            $date_end = new DateTime($end_date);
            $date_diff = $date_end->diff($date1);
            $d = ($date_diff->format("%a"));
            $all_date = array();
            for ($j=0; $j < ($d+1); $j++) {
                $all_date[] = date('Y-m-d', strtotime("+$j day", strtotime($first_date)));
            }
            $real_date = array_map(function ($ele){return $ele->day_no_raw;}, $vo['details']);
            foreach ($all_date as $kd => $vd) {
                if ( ! in_array($vd, $real_date)) {
                    $this->ci->tldOrderBuilder->setScheduleDetailsTitle($kd, "无")
                                            ->setScheduleDetailsContent($kd, "无")
                                            ->setScheduleDetailsAccommodation($kd, "")
                                            // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0))
                                            ->setScheduleDetailsBreakFirst($kd, 0 )
                                            ->setScheduleDetailsDinner($kd, 0)
                                            ->setScheduleDetailsLunch($kd, 0)
                                            ;
                    continue;
                }
                foreach ($vo['details'] as $kgrd => $vgrd) {
                    if ($vd==$vgrd->day_no_raw) {
                        $this->ci->tldOrderBuilder->setScheduleDetailsTitle($kd, $vgrd->GRD_OrderDate)
                                                ->setScheduleDetailsContent($kd,
                                                    $vgrd->GRD_LeaveCity . "-" . $vgrd->GRD_ServiceCity . "\r\n" .
                                                    $vgrd->GRD_Landscape . "\r\n" . $vgrd->GRD_Traffic)
                                                ->setScheduleDetailsTraffic($kd, ($vgrd->GRD_Traffic))
                                                ->setScheduleDetailsBreakFirst($kd, 0 )
                                                ->setScheduleDetailsDinner($kd, (trim($vgrd->GRD_Meal_S)==="" ? 0 : 1 ))
                                                ->setScheduleDetailsLunch($kd, (trim($vgrd->GRD_Meal_L)==="" ? 0 : 1 ))
                                                ;
                        // 酒店只写名字在线路信息中
                        if (isset($vgrd->hotel_name) && strval($vgrd->hotel_name)!=='') {
                            $this->ci->tldOrderBuilder->setScheduleDetailsAccommodation($kd, $vgrd->hotel_name);
                        } else {
                            $this->ci->tldOrderBuilder->setScheduleDetailsAccommodation($kd, $vgrd->GRD_Hotel);
                        }
                        if (strval($vgrd->GRD_Hotel) !=='' ) {
                            $this->ci->tldOrderBuilder->setRoomStandard($vgrd->GRD_OrderDate . " " . trim($vgrd->GRD_Hotel));
                        }
                        // 商务订单信息
                        if (isset($vgrd->hotel_checkin)) {
                            $this->ci->tldOrderBuilder->setRoomStandard(trim($vgrd->hotel_checkin));
                        }
                        if (isset($vgrd->to_traffic)) {
                            $this->ci->tldOrderBuilder->setToTraffic(trim($vgrd->to_traffic));
                        }
                        if (isset($vgrd->back_traffic)) {
                            $this->ci->tldOrderBuilder->setBackTraffic(trim($vgrd->back_traffic));
                        }
                        if (isset($vgrd->vendor_memo)) {
                            $this->ci->tldOrderBuilder->setOrderRemark(trim($vgrd->vendor_memo));
                        }
                    }
                }
            }
            // 查询是否变更 deprecated at 2019-05
            $sync_orderstate = 10;
            $set_update = false;
            $this->ci->tldOrderBuilder->clearModifyLogInfo();
            // echo $this->ci->tldOrderBuilder->getBizContent();exit;
            $resp = $this->excute_curl($this->neworder_url, $this->ci->tldOrderBuilder);
            $response = json_decode($resp);
            if ($response->status == 1) {
                /** VendorPlanSync */
                $sync_ret = array(
                    "VPS_VAS_SN" => $vas->VAS_SN
                    ,"VPS_GRI_SN" => $vas->GRI_SN
                    ,"VPS_VEI_SN" => $vas->VAS_VEI_SN
                    ,"VPS_startDate" => $first_date
                    ,"VPS_endDate" => $end_date
                    ,"VPS_sendHost" => $userId
                    ,"VPS_externalId" => $response->responseData->orderId
                    ,"VPS_externalorderType" => $order_type
                    ,"VPS_externalorderState" => $sync_orderstate
                    ,"VPS_sendTime" => date('Y-m-d H:i:s')
                );
                $sync_id = $this->ci->Group_model->insert_VendorPlanSync($sync_ret);
            }
        }
        return $total_order_index;
    }

    /*!
     * @Author: LYT
     * @Date: 2019-05-29 14:54:17
     * @Desc: 线路订单计划拆分.
     * 合并同样的行程
     * 根据行程类型拆分
     * @return $ret = array(
     * 'big_pvt'=>array(),  // 不是合作项目的产品
     * 'pvt'=>array(),      // 合作项目中的pvt
     * 'com'=>array(        // 合作项目中的拼团
     *          'details' => [],'PAG_Code'=> 'XXX'
     *        )
     * )
     */
    public function tour_apart($all_pag_info, $set_pvt=0)
    {
        $apart = array(); $ret = array();
        foreach ($all_pag_info as $key => $pag) {
            if ( ! isset($pag->PAG_DEI_SN)) {
                // 通宵火车或其他, 不含该社行程
                continue;
            }
            // CH下的产品编号修正
            // if (intval($pag->PAG_DEI_SN)===1 && ! empty($pag->PAG_Code)) {
            //     $pag->PAG_Code = $this->ci->trippest->ch_code_transfer( mb_strtoupper($pag->PAG_Code));
            //     $pag->PAG_ExtendType = $this->tulanduo_trippest_pag[$pag->PAG_Code]->PAG_ExtendType;
            // } else if (false !== stripos($pag->GRD_Landscape, 'trippest')) {
            //     $apart["com"]['details'][$pag->PAG_Code][] = $pag;
            //     continue;
            // }
            if (empty($pag->PAG_Code)) // 已在grd查询中增加是否目的地产品的判断
            {
                $apart['big_pvt']['details'][] = $pag;
                continue;
            }
            if (empty($pag->PAG_Title) ) {
                $pag->PAG_Title = $this->tulanduo_trippest_pag[$pag->PAG_Code]->PAG_Title;
            }
            // 合作的产品
            // 商务订单全部按PVT || isset($pag->is_biz)
            if ($this->ci->trippest->if_tour_pvt(array($pag))===1 || $set_pvt!==0) {
                $apart["pvt"]['details'][] = $pag;
            } else {
                $apart["com"]['details'][$pag->PAG_Code][] = $pag;
            }
        }
        $apart_com = array();
        if ( ! empty($apart['com'])) {
            $all_com_pag = array_keys($apart['com']['details']);
            $full_pag = array();
            $process_pag = array();
            foreach ($all_com_pag as $kp => $vp) {
                $apart_com[$vp]['details'] = array();
                $this_include_pags = $this->ci->trippest->tour_code($vp);
                if( isset($this->ci->trippest->special_route[$vp]) ) {
                    $full_pag = array_diff($this_include_pags, array_merge($full_pag,$process_pag));
                    foreach ($this_include_pags as $vi) {
                        if ($vi !== $vp) {
                            unset($apart_com[$vi]);
                        }
                        if (empty($apart_com[$vp]['details'])) {
                            $apart_com[$vp]['details'] = array();
                        }
                        // $apart_com[$vp]['details'][] = $apart['com']['details'][$vi];
                        $apart_com[$vp]['details'] = array_merge($apart_com[$vp]['details'], $apart['com']['details'][$vi]);
                        $apart_com[$vp]['PAG_Code'] = $vp;
                        $apart_com[$vp]['PAG_Name'] = $this->ci->trippest->special_route[$vp]['name'];
                    }
                } else {
                    $full_pag = array_merge($full_pag, $this_include_pags);
                    // $apart_com[$vp]['details'][] = $apart['com']['details'][$vp];
                    $apart_com[$vp]['details'] = array_merge($apart_com[$vp]['details'], $apart['com']['details'][$vp]);
                    $apart_com[$vp]['PAG_Code'] = $vp;
                    $apart_com[$vp]['PAG_Name'] = "";
                }
                $process_pag[] = $vp;
                $this_include_pags = array();
            }
        }
        $ret['big_pvt'] = empty($apart['big_pvt']) ? null : $apart['big_pvt'];
        $ret['pvt'] = empty($apart['pvt']['details']) ? null : ($apart['pvt']);
        $ret['com'] = array_values($apart_com);
        return $ret;
    }

    /*!
     * @Author: LYT
     * @Date: 2019-06-04 11:47:38
     * @Desc: 发送商务订单计划
     */
    public function push_biz($vas=null, $set_pvt=0)
    {
        $userId  = $this->send_host["1"]["userId"];
        $userKey = $this->send_host["1"]["key"];
        $gri_sn = $vas->GRI_SN;
        $vas_sn = $vas->VAS_SN;
        $vei_sn = $vas->VAS_VEI_SN;
        $grd_info = $this->ci->Group_model->get_vendor_plan_info($gri_sn, $vei_sn, true);
        if (empty($grd_info)) {
            $this->ci->Group_model->set_plan_received($vas_sn);
            return false;
        }
        $route_name = "";
        $order_type = 1;
        $COLD_SN_str = implode(',', array_map( function($element){return $element->GRD_COLD_SN;}, $grd_info )) ;
        $all_colds = $this->ci->BIZ_order->get_all_cold($COLD_SN_str);
        $coli_sn = $all_colds[0]->COLI_SN;
        $train_coldsn_arr = array();$train_order = array();
        $pag_coldsn_arr = array();$pag_order = array();
        foreach ($all_colds as $kd => $vcold) {
            if (strval($vcold->COLD_ServiceType)==='2') {
                $train_coldsn_arr[] = $vcold->COLD_SN;
                continue;
            }
            if (strval($vcold->COLD_ServiceType)==='D') {
                $pag_coldsn_arr[] = $vcold->COLD_SN;
                continue;
            }
        }
        if ( ! empty($train_coldsn_arr)) {
            $route_name .= $route_name==="" ? "" : "+";
            $route_name .= "单订国际列车票服务";
            $order_type = 1;
            $train_order = $this->ci->BIZ_order->get_train_flight_order(implode(',', $train_coldsn_arr));
            $agcOrderNo = $vas->GRI_Name;
            $last_date = count($train_order)-1;
            $end_date = strstr($train_order[$last_date]->COLD_EndDate, " ", true);
            $end_date = $end_date ? $end_date : strstr($train_order[0]->COLD_StartDate, " ", true);
            $this->ci->tldOrderBuilder->setUserId($userId)
                                    ->setKey($userKey)
                                    ->setOrderType($order_type)
                                    ->setRouteName($route_name)
                                    ->setRouteType("单订国际列车票服务")
                                    ->setAgcOrderNo($agcOrderNo)
                                    ->setAdultNum($train_order[0]->adult_num)
                                    ->setChildNum($train_order[0]->child_num)
                                    // ->setDestination($train_order[0]->city_name)
                                    ->setDestination("海纳常规系列")
                                    ->setTravelDate(strstr($train_order[0]->COLD_StartDate, " ", true))
                                    ->setLeavedDate($end_date)
                                    ->setOperationUserName('常彩荣')
                                    ;
            $train_guest_list = $this->ci->BIZ_order->get_guestlist(implode(',', $train_coldsn_arr));
            // 客人列表
            $from_country = ""; // 客源地
            foreach ($train_guest_list as $key => $vg) {
                $this_otherinfo = "";
                $this->ci->tldOrderBuilder->setCustomersName($key, $vg->MemberName )
                                      ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童"))
                                      ->setCustomersDocumentType($key, "护照") // Passport No.
                                      ->setCustomersDocumentNo($key, $vg->PassportNo)
                                      ;
                if (strval($vg->Country) !== '' ) {
                    $from_country = strval($from_country) === '' ? $vg->Country : $from_country;
                    $this_otherinfo .= $vg->Country;
                }
                if (strval($vg->Gender) !== '') {
                    $this_otherinfo .= "; " . $vg->Gender;
                }
                if (strval($vg->BirthDay) !== '') {
                    $this_otherinfo .= "; 生日:". $vg->BirthDay;
                }
                if (strval($vg->PassportValidDate) !== '') {
                    $this_otherinfo .= "; 护照有效期:" . $vg->PassportValidDate;
                }
                $this->ci->tldOrderBuilder->setCustomersOtherInfo($key, $this_otherinfo);
                // todo:电话
                // if (trim($vf['cold'][0]->GUT_TEL) != "" && $key===0) {
                //     $this_otherinfo .= "; 电话:";
                //     $this_otherinfo .= trim($vf["cold"][0]->GUT_POST)!=="" ? "+".trim($vf["cold"][0]->GUT_POST) : "" ;
                //     $this_otherinfo .= " " . trim($vf["cold"][0]->GUT_TEL);
                //     $this->ci->tldOrderBuilder->setCustomersOtherInfo($key, $this_otherinfo);
                // }
            }
            $this->ci->tldOrderBuilder->setCustomerFromCity($from_country);
            $s_index = 0;
            foreach ($train_order as $train) {
                $this_content = '';
                $this_content .= $train->departure_date . " " . $train->depart_station . "-" . $train->arrival_station . " " . $train->FlightsNo ;
                $this_content .= "(" . $train->duration . ")" . " "  . $train->cabin_name . " " . $train->adultcost . "元\r\n";
                $this_content .= "请购票成功后通知外联。";
                if (trim($train->TicketAddress) != '') {
                    $this_content .= "并于客人入住前两天，快递送达客人酒店，谢谢！\r\n";
                    $this_content .= $train->TicketAddress;
                }
                $this->ci->tldOrderBuilder->setScheduleDetailsTitle($s_index, $train->departure_date)
                                        ->setScheduleDetailsContent($s_index, $this_content)
                                        ;
                $s_index++;
            }
            $this->ci->tldOrderBuilder->clearModifyLogInfo();
            // echo $this->ci->tldOrderBuilder->getBizContent();exit;
            $resp = $this->excute_curl($this->neworder_url, $this->ci->tldOrderBuilder);
            $response = json_decode($resp);
            $sync_orderstate = 10;
            $vps_sn = 0;
            if ($response->status == 1) {
                /** VendorPlanSync */
                $sync_ret = array(
                    "VPS_VAS_SN" => $vas_sn
                    ,"VPS_GRI_SN" => $gri_sn
                    ,"VPS_VEI_SN" => $vei_sn
                    ,"VPS_startDate" => strstr($train_order[0]->COLD_StartDate, " ", true)
                    ,"VPS_endDate" => $end_date
                    ,"VPS_sendHost" => $userId
                    ,"VPS_externalId" => $response->responseData->orderId
                    ,"VPS_externalorderType" => $order_type
                    ,"VPS_externalorderState" => $sync_orderstate
                    ,"VPS_sendTime" => date('Y-m-d H:i:s')
                );
                if ($vps_sn === 0) {
                    $sync_id = $this->ci->Group_model->insert_VendorPlanSync($sync_ret);
                    $this->ci->BIZ_order->insert_biz_order_log($coli_sn, "vendorPlanSendout_");
                }
                /** VendorArrangeState VAS_IsReceive */
                $this->ci->Group_model->set_plan_received($vas_sn);
            }
        }
        if ( ! empty($pag_coldsn_arr)) {
            $this->biz_pag_order_exec($vas,$grd_info, $set_pvt);
        }
        return false;
    }

    private function biz_pag_order_exec($vas, $grd, $set_pvt=0)
    {
        if (empty($grd)) {
            return false;
        }
        // 补全小包价的日程
        $complete_grd = array();
        $special_grd = array();
        $normal_grd = array();
        // object 在foreach中自身会被改变, 先转换成array
        $grd = json_decode(json_encode($grd), true);
        foreach ($grd as $kp => $vpag) {
            $hotels_traffic = $this->ci->BIZ_order->get_package_order($vpag['GRD_COLD_SN']);
            $vpag['GRD_Hotel'] = $hotels_traffic[0]->POI_Hotel;
            $vpag['to_traffic'] = $hotels_traffic[0]->POI_Hotel;
            $vpag['back_traffic'] = $hotels_traffic[0]->POI_Hotel;
            // if (trim($hotels_traffic[0]->POI_HotelAddress) != "") {
            //     $vpag['GRD_Hotel'] .= "\r\n酒店地址:" . $hotels_traffic[0]->POI_HotelAddress;
            // }
            $vpag['hotel_checkin'] = trim($hotels_traffic[0]->POI_HotelCheckInName)!=="" ? "入住人:".$hotels_traffic[0]->POI_HotelCheckInName : "";
            $vpag['hotel_checkin'] .= trim($hotels_traffic[0]->POI_HotelCheckIn)!=="" ? "  入住日期:".$hotels_traffic[0]->POI_HotelCheckIn : "";
            if ($hotels_traffic[0]->POI_FlightsNo) {
                $vpag['GRD_Traffic'] = $hotels_traffic[0]->POI_FlightsNo;
                if ($hotels_traffic[0]->POI_FromCity || $hotels_traffic[0]->POI_ToCity) {
                    $vpag['GRD_Traffic'] .= ", (" . $hotels_traffic[0]->POI_FromCity . "-" . $hotels_traffic[0]->POI_ToCity . ")";
                }
                if ($hotels_traffic[0]->POI_Time || $hotels_traffic[0]->POI_EndTime) {
                    $vpag['GRD_Traffic'] .= ", " . $hotels_traffic[0]->POI_Time . " " . $hotels_traffic[0]->POI_EndTime;
                }
                if ($hotels_traffic[0]->POI_AirPort) {
                    $vpag['GRD_Traffic'] .= ", " . $hotels_traffic[0]->POI_AirPort;
                }
            }
            if (isset($this->ci->trippest->special_route[$vpag['PAG_Code']])) {
                $this_pag_total_day = $this->ci->trippest->special_route[$vpag['PAG_Code']]['day'];
                $this_code = $vpag['PAG_Code'];
                for($p=0; $p<$this_pag_total_day; $p++) {
                    $vpag['GRD_OrderDate'] = date("Y-m-d", strtotime("+$p day", strtotime($vpag['day_no_raw'])));
                    $vpag['day_no_raw'] = $vpag['GRD_OrderDate'];
                    $vpag['PAG_Code'] = $this->ci->trippest->special_route[$this_code]['code'][$p];
                    $pag_detail = $this->ci->BIZ_order->get_packageDetails("'" . $vpag['PAG_Code'] . "'", implode(",",$this->vendor_ids), false);
                    $vpag['PAG_Title'] = $pag_detail[0]->PAG2_Name;
                    $vpag['GRD_Landscape'] = $vpag['PAG_Title'];
                    $vpag['GRD_Meal_L'] = (in_array($pag_detail[0]->PAG_Meal, array('61002', '61004')) ? "1" : "");
                    $vpag['GRD_Meal_S'] = (in_array($pag_detail[0]->PAG_Meal, array('61003', '61004')) ? "1" : "");
                    $special_grd[] = $vpag;
                }
            } else {
                $pag_detail = $this->ci->BIZ_order->get_packageDetails("'" . $vpag['PAG_Code'] . "'", implode(",",$this->vendor_ids), false);
                $vpag['GRD_Meal_L'] = (in_array($pag_detail[0]->PAG_Meal, array('61002', '61004')) ? "1" : "");
                $vpag['GRD_Meal_S'] = (in_array($pag_detail[0]->PAG_Meal, array('61003', '61004')) ? "1" : "");
                // 接送的子订单行程
                if (isset($vpag['PAG_sub_sn']) && $vpag['PAG_sub_sn'] != 0) {
                    $sub_pag = $this->ci->BIZ_order->get_sub_pag_info($vpag['PAG_sub_sn']);
                    if (! empty($sub_pag)) {
                        $vpag['GRD_Landscape'] =  "[" . $sub_pag->PAGS_CN_Title . "] " . $vpag['GRD_Landscape'];
                        if (strval($sub_pag->PAGS_Direction) === '0') {
                            $vpag['to_traffic'] = $vpag['GRD_Traffic'];
                        } else {
                            $vpag['back_traffic'] = $vpag['GRD_Traffic'];
                        }
                    }
                }
                $normal_grd[] = $vpag;
            }
        }
        $complete_grd = array_merge($special_grd, $normal_grd);
        $complete_grd = json_decode(json_encode($complete_grd));
        $grd_apart_info = $this->tour_apart($complete_grd, $set_pvt);
        // echo json_encode($grd_apart_info);exit;
        $request_info = $this->ci->Group_model->get_plan_request($vas->GRI_SN);
        $big_order_index = 0;
        $expect_order_cnt = count($grd_apart_info['com'])+intval(!empty($grd_apart_info['big_pvt']))+intval(!empty($grd_apart_info['pvt']));
        foreach ($grd_apart_info as $group_key => $grd_part) {
            $big_order_index = $this->tour_apart_order_exec($group_key, $vas, $request_info, null, $grd_part, $big_order_index);
        }
        if ($big_order_index === $expect_order_cnt) {
            /** VendorArrangeState VAS_IsReceive */
            $this->ci->Group_model->set_plan_received($vas->VAS_SN);
        }
    }

    /*!
     * 发送目的地项目组预订计划到图兰朵地接系统
     */
    public function push_trippest($vas=null)
    {
        /** 目的地  */
        $userId  = $this->send_host["30"]["userId"];
        $userKey = $this->send_host["30"]["key"];

        $gri_sn = $vas->GRI_SN;
        $vas_sn = $vas->VAS_SN;
        $vei_sn = $vas->VAS_VEI_SN;
        $vei_sn_str = implode(",", $this->vendor_ids);
        $orderinfo = $this->ci->BIZ_order->get_orderinfo_detail($gri_sn, $vei_sn_str);
        if(empty($orderinfo)) {return "[Tulanduo>push_trippest] Not found order detail. ";}
        $COLI_ID = $orderinfo[0]->COLI_ID;
        $set_pvt = strval($orderinfo[0]->is_pvt);
        // 增加收款方参数, 增加代收款项
        $vei_with_haina = $GLOBALS['__HAINA_VEI__'] . "," . $vei_sn_str;
        $all_payment = $this->ci->BIZ_order->get_paymentDetails($COLI_ID, $vei_with_haina);
        $paid_to_trippest = array();
        $pay_to_vendor = array();
        foreach ($all_payment as $kall => $vall) {
            if (in_array($vall->payment_vei, array($GLOBALS['__HAINA_VEI__'], 0)) ) {
                $paid_to_trippest[] = $vall;
            } else {
                $pay_to_vendor[] = $vall;
            }
        }
        // 收款合并为一条
        if ( ! empty($paid_to_trippest)) {
            $travel_fees = $paid_to_trippest[0];
            $travel_fees->SUM_SSJE = 0;
            foreach ($paid_to_trippest as $ktf => $vtf) {
                $travel_fees->SUM_SSJE = bcadd($travel_fees->SUM_SSJE, $vtf->GAI_SSJE);
            }
        }
        // 代收合并为一条
        if ( ! empty($pay_to_vendor)) {
            $replace_collections = $pay_to_vendor[0];
            $replace_collections->SUM_SSJE = 0;
            $replace_collections->ALL_Memo = "";
            foreach ($pay_to_vendor as $ktv => $vtv) {
                $replace_collections->SUM_SSJE = bcadd($replace_collections->SUM_SSJE, $vtv->GAI_SSJE);
                $replace_collections->ALL_Memo .= $vtv->ALL_Memo;
            }
        }
        // 按产品拆分 按订单类型拆分? 单团/拼团; 未设置则按产品类型:接送
        $fill_order = array();
        $processed_date = array();
        $processed_cold = array();
        foreach ($orderinfo as $ko => $cold) {
            if ( ! in_array($cold->COLD_SN, $processed_cold) && $cold->pag_code != '') {
                $processed_cold[] = $cold->COLD_SN;
                $all_package = $this->ci->trippest->tour_code($cold->pag_code);
                $pag_info = $this->ci->BIZ_order->get_packageDetails(my_implode("'",",",$all_package), implode(",",$this->vendor_ids));
                if (strval($cold->settle) === '4') {
                    $fill_order['normal_' . $cold->COLD_PlanVEI_SN]["cold"][] = $cold;
                } else
                if ($set_pvt==='1') {
                    $fill_order['pvt_' . $cold->COLD_PlanVEI_SN]["cold"][] = $cold;
                } else {
                    $fill_order[$cold->pag_code]["cold"][] = $cold;
                    $fill_order[$cold->pag_code]["package_info"] = $pag_info;
                }
            }
        }
        // 多产品PVT的合并,避免丢失产品
        // if ($set_pvt==='1') {
            // foreach ($fill_order['pvt']['cold'] as $kcd => $vcd) {
            //     $multi_package = $this->ci->trippest->tour_code($vcd->pag_code);
            //     $pvt_pagcode = array_merge($pvt_pagcode, $multi_package);
            // }
            // $fill_order['pvt']["package_info"] = $this->ci->BIZ_order->get_packageDetails(my_implode("'",",",$pvt_pagcode), implode(",",$this->vendor_ids));
        // }
        foreach ($fill_order as $key => $part) {
            $pvt_pagcode = array();
            if (strpos($key, 'pvt_') ===0 || strpos($key, 'normal_')===0) {
                foreach ($part['cold'] as $kcd => $vcd) {
                    $multi_package = $this->ci->trippest->tour_code($vcd->pag_code);
                    $pvt_pagcode = array_merge($pvt_pagcode, $multi_package);
                }
                $fill_order[$key]["package_info"] = $this->ci->BIZ_order->get_packageDetails(my_implode("'",",",$pvt_pagcode), implode(",",$this->vendor_ids));
                $multi_package = null; $pvt_pagcode=null;
            }
        }
        // echo json_encode($fill_order);exit;
        // $fill_order = array_values($fill_order);
        $i=0;
        $take_apart = count($fill_order)>1 ? true : false;
        $coli_sn = 0;
        foreach ($fill_order as $kf => $vf) {
            $i++;
            $coli_sn = $vf['cold'][0]->COLI_SN;
            $this->ci->tldOrderBuilder->resetBizContent();
            $order_type = $set_pvt;
            if ($set_pvt==='0') {
                $order_type = $this->ci->trippest->if_tour_pvt($vf["package_info"]);
            }
            $last_code = count($vf["package_info"])-1;
            $last_date = count($vf["cold"])-1;
            $tour_code = mb_strtoupper($vf["cold"][0]->pag_code);
            $routeName = $vf["package_info"][0]->PAG2_Name . "(" . $tour_code . ")";
            $first_date = strstr($vf["cold"][0]->COLD_StartDate, " ", true);
            $end_date = strstr($vf["cold"][$last_date]->COLD_EndDate, " ", true);
            if (isset($this->ci->trippest->special_route[$vf["cold"][0]->pag_code])) {
                $routeName = $this->ci->trippest->special_route[$vf["cold"][0]->pag_code]["name"];
                $extra_day = $this->ci->trippest->special_route[$vf["cold"][0]->pag_code]["day"]-1;
                $end_date = date("Y-m-d", strtotime("+$extra_day day", strtotime($vf["cold"][0]->COLD_StartDate)));
            }
            // $agcOrderNo = $vf["cold"][0]->COLI_GroupCode . "-" . $vf["package_info"][0]->city_code;
            if ($take_apart===true) {
                // $agcOrderNo .= "-" . $i;
                $tour_code = mb_strtoupper($vf["cold"][0]->pag_code);
            }
            // $agcOrderNo .= "(" . $vf["cold"][0]->operator . ")";
            $agcOrderNo = $vf["cold"][0]->COLI_GroupCode;
            if (trim($vf["cold"][0]->COLI_PriceMemo) !== '' && '4' !== strval($vf["cold"][0]->settle)) {
                $agcOrderNo .= " (" . $vf["cold"][0]->COLI_PriceMemo . ")";
            }
            $order_remark = "";
            if ($i===1) {   // 只写一次备注.备注中可能包含代收信息,避免多次收取
                $order_remark_arr = array_filter(array_map( function($element){return $element->COLD_vendorMemo;}, $vf["cold"] )) ;
                $order_remark = empty($order_remark_arr) ? "" : implode("\n", $order_remark_arr) ;
            }

            $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $vf["cold"] )) ;
            $guestlist = $this->ci->BIZ_order->get_guestlist($COLD_SN_str);
            $this->ci->tldOrderBuilder->setUserId($userId)
                                  ->setKey($userKey)
                                  ->setOrderType($order_type)
                                  ->setRouteName($routeName)
                                  ->setRouteType($vf["package_info"][0]->city_chinese . "目的地线路")
                                  ->setAgcOrderNo($agcOrderNo)
                                  ->setAdultNum($vf["cold"][0]->COLD_PersonNum)
                                  ->setChildNum($vf["cold"][0]->COLD_ChildNum)
                                //   ->setDestination($vf["package_info"][0]->city_chinese)
                                  ->setDestination("TP系列")
                                  ->setTravelDate(strstr($vf["cold"][0]->COLD_StartDate, " ", true))
                                  ->setLeavedDate($end_date)
                                  ->setOrderRemark($order_remark)
                                  ->setOperationUserName('付玉乔')
                                  // todo: 抵离交通
                                  // ->setToTraffic($toTraffic)
                                  // ->setBackTraffic($backTraffic)
                                  ;
            // 客人列表
            $from_country = '';
            foreach ($guestlist as $key => $vg) {
                $this_otherinfo = "";
                $this->ci->tldOrderBuilder->setCustomersName($key, $vg->MemberName )
                                      ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童"))
                                      ->setCustomersDocumentType($key, "护照") // Passport No.
                                      ->setCustomersDocumentNo($key, $vg->PassportNo)
                                      ;
                if (trim($vf['cold'][0]->GUT_TEL) != "" && $key===0) {
                    $this_otherinfo .= trim($vf["cold"][0]->GUT_POST)!=="" ? "+".trim($vf["cold"][0]->GUT_POST) : "" ;
                    $this_otherinfo .= " " . trim($vf["cold"][0]->GUT_TEL);
                    $this->ci->tldOrderBuilder->setCustomersPhoneNo($key, $this_otherinfo);
                }
                if ( strval($vg->Country) !== '') {
                    $from_country = strval($from_country) === '' ? $vg->Country : $from_country;
                    $this_otherinfo .= "; " . $vg->Country;
                }
                if (strval($vg->Gender) !== '') {
                    $this_otherinfo .= "; " . $vg->Gender;
                }
                if (strval($vg->BirthDay) !== '') {
                    $this_otherinfo .= "; 生日:". $vg->BirthDay;
                }
                if (strval($vg->PassportValidDate) !== '') {
                    $this_otherinfo .= "; 护照有效期:" . $vg->PassportValidDate;
                }
                $this->ci->tldOrderBuilder->setCustomersOtherInfo($key, $this_otherinfo);
            }
            // 客源地
            if (strval($from_country)==='') {
                $biz_contact = $this->ci->BIZ_order->get_customer_contact($COLD_SN_str);
                $from_country = $biz_contact->Country;
            }
            $this->ci->tldOrderBuilder->setCustomerFromCity($from_country);
            $scheduleDetails = $this->ci->BIZ_order->get_scheduleDetails($COLD_SN_str);
            $schedule_obj = array();
            foreach ($scheduleDetails as $ks => $vs) {
                $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['date'] = substr($vs->COLD_StartDate, 0, 10);
                $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['lunch'] = (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0);
                $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['dinner'] = (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0);
                $this_content = $this_title = "";
                if ( ! isset($schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'])) {
                    $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'] = "";
                }
                // 人数
                $this_content .= "\r\n人数:" . $vs->COLD_PersonNum . "大";
                ($vs->COLD_ChildNum>0) ? $this_content .= $vs->COLD_ChildNum . "小" : null;
                ($vs->COLD_BabyNum>0) ? $this_content .= $vs->COLD_BabyNum . "婴" : null;
                $this_content .= "\r\n客人:";
                $this_guest = "";
                foreach ($guestlist as $dkg => $dvg) {
                    if ($dvg->BPL_COLD_SN == $vs->COLD_SN) {
                        $this_guest .= "," . $dvg->BPE_FirstName . " " . $dvg->BPE_LastName;
                    }
                }
                $this_content .= substr($this_guest, 1);
                // 酒店
                $hotels = $this->ci->BIZ_order->get_package_order($vs->COLD_SN);
                if (trim($hotels[0]->POI_HotelAddress) != "") {
                    $this_content .= "\r\n酒店地址:" . $hotels[0]->POI_HotelAddress;
                }
                if (trim($hotels[0]->POI_Hotel) != '') {
                    $this->ci->tldOrderBuilder->setToTraffic($hotels[0]->POI_Hotel);
                    $this->ci->tldOrderBuilder->setBackTraffic($hotels[0]->POI_Hotel);
                }
                $checkin_name = trim($hotels[0]->POI_HotelCheckInName)!=="" ? "\r\n入住人:".$hotels[0]->POI_HotelCheckInName : "";
                $checkin_date = trim($hotels[0]->POI_HotelCheckIn)!=="" ? "\r\n入住日期:".$hotels[0]->POI_HotelCheckIn : "";
                $this_content .= $checkin_name;
                $this_content .= $checkin_date;
                if ($checkin_name!=='' || $checkin_date!=='') {
                    $this->ci->tldOrderBuilder->setRoomStandard(trim($checkin_name) . ", " . trim($checkin_date));
                }
                if ($hotels[0]->POI_FlightsNo) {
                    $this_content .= "\r\n航/车次:" . $hotels[0]->POI_FlightsNo;
                    if ($hotels[0]->POI_FromCity || $hotels[0]->POI_ToCity) {
                        $this_content .= ", (" . $hotels[0]->POI_FromCity . "-" . $hotels[0]->POI_ToCity . ")";
                    }
                    if ($hotels[0]->POI_Time || $hotels[0]->POI_EndTime) {
                        $this_content .= ", " . $hotels[0]->POI_Time . " " . $hotels[0]->POI_EndTime;
                    }
                    if ($hotels[0]->POI_AirPort) {
                        $this_content .= ", " . $hotels[0]->POI_AirPort;
                    }
                }
                $this_content .= "\r\n";
                $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['accommodation'] = $hotels[0]->POI_Hotel;
                // 补充行程
                $fill_date = array();
                if (isset($this->ci->trippest->special_route[$vs->PAG_Code])) {
                    for ($j=0; $j < $this->ci->trippest->special_route[$vs->PAG_Code]['day']; $j++) {
                        $e_day = date("Y-m-d", strtotime("+$j day", strtotime($vs->COLD_StartDate)));
                        if ( ! isset($schedule_obj[$e_day]['content'])) {
                            $schedule_obj[$e_day]['content'] = "";
                        }
                        $schedule_obj[$e_day]['date'] = $e_day;
                        $fill_date[] = $e_day;
                        $schedule_obj[$e_day]['code'] = $this->ci->trippest->special_route[$vs->PAG_Code]['code'][$j];
                        $pag_detail = $this->ci->BIZ_order->get_packageDetails("'" . $schedule_obj[$e_day]['code'] . "'", implode(",",$this->vendor_ids));
                        $schedule_obj[$e_day]['title'] = $pag_detail[0]->PAG2_Name;
                        $schedule_obj[$e_day]['lunch'] = (in_array($pag_detail[0]->PAG_Meal, array('61002', '61004')) ? 1 : 0);
                        $schedule_obj[$e_day]['dinner'] = (in_array($pag_detail[0]->PAG_Meal, array('61003', '61004')) ? 1 : 0);
                        $schedule_obj[$e_day]['content'] .= $schedule_obj[$e_day]['title'] . $this_content;
                        $schedule_obj[$e_day]['accommodation'] = $hotels[0]->POI_Hotel;
                    }
                }
                // 行程
                if ($vs->PAGS_CN_Title) {
                    $this_title .= "[" . $vs->PAGS_CN_Title . "]";
                }
                if ($this_title == "") {
                    $this_title .= $vs->PAG2_Name;
                }
                // 补充的行程避免重复
                if ( ! in_array(substr($vs->COLD_StartDate, 0, 10), $fill_date)) {
                    $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'] .= $this_title . $this_content;
                }
                // 当前产品连续日期的补充
                $date_s = new DateTime(strstr($vs->COLD_StartDate, " ", TRUE));
                $date_e = new DateTime(strstr($vs->COLD_EndDate, " ", TRUE));
                $date_d = $date_e->diff($date_s);
                $d_t = ($date_d->format("%a"));
                if ($d_t > 0 && empty($fill_date)) {
                    for ($d_i=0; $d_i < ($d_t+1); $d_i++) {
                        $f_d = date('Y-m-d', strtotime("+$d_i day", strtotime(substr($vs->COLD_StartDate, 0, 10))));
                        $schedule_obj[$f_d] = $schedule_obj[substr($vs->COLD_StartDate, 0, 10)];
                        $schedule_obj[$f_d]['date'] = $f_d;
                    }
                }
            }
            // 补全空的日期
            $date1 = new DateTime($first_date);
            $date_end = new DateTime($end_date);
            $date_diff = $date_end->diff($date1);
            $d = ($date_diff->format("%a"));
            $all_date = array();
            for ($j=0; $j < ($d+1); $j++) {
                $all_date[] = date('Y-m-d', strtotime("+$j day", strtotime($first_date)));
            }
            $real_date = array_column(array_values($schedule_obj), 'date');
            foreach ($all_date as $kd => $vd) {
                if ( ! in_array($vd, $real_date)) {
                    $this->ci->tldOrderBuilder->setScheduleDetailsTitle($kd, "无")
                                            ->setScheduleDetailsContent($kd, "无")
                                            ->setScheduleDetailsAccommodation($kd, "")
                                            // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0))
                                            ->setScheduleDetailsBreakFirst($kd, 0 )
                                            ->setScheduleDetailsDinner($kd, 0)
                                            ->setScheduleDetailsLunch($kd, 0)
                                            ;
                    continue;
                }
                foreach (array_values($schedule_obj) as $kso => $vso) {
                    if ($vd==$vso['date']) {
                        $this->ci->tldOrderBuilder->setScheduleDetailsTitle($kd, $vso['date'])
                                                ->setScheduleDetailsContent($kd, $vso['content'])
                                                ->setScheduleDetailsAccommodation($kd, $vso['accommodation'])
                                                // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0))
                                                ->setScheduleDetailsBreakFirst($kd, 0 )
                                                ->setScheduleDetailsDinner($kd, $vso['dinner'] )
                                                ->setScheduleDetailsLunch($kd, $vso['lunch'])
                                                ;
                    }
                }
            }
            $fee_index=0;
            if (strval($vf['cold'][0]->settle) !== '4') {
                $cold_amount = $this->ci->BIZ_order->get_cold_amount($COLD_SN_str);
                if ( ! empty($cold_amount) ) {
                    foreach ($cold_amount as $kca => $vca) {
                        $this->ci->tldOrderBuilder->setTravelFeesType($fee_index, "Per Group")
                                                ->setTravelFeesMoney($fee_index, $vca->CNY_price)
                                                ->setTravelFeesNum($fee_index, 1)
                                                ->setTravelFeesUnit($fee_index, 1)
                                                ->setTravelFeesSumMoney($fee_index, $vca->CNY_price);
                        ++$fee_index;
                    }
                }
            }

            // 拆分的订单团款录第一个
            if ($i===1) {
                // if ( ! empty($travel_fees) ) {
                    // $this->ci->tldOrderBuilder->setTravelFeesType($fee_index, "Per Group")
                    //                         ->setTravelFeesMoney($fee_index, $travel_fees->SUM_SSJE)
                    //                         ->setTravelFeesNum($fee_index, 1)
                    //                         ->setTravelFeesUnit($fee_index, 1)
                    //                         ->setTravelFeesSumMoney($fee_index, $travel_fees->SUM_SSJE);
                    // ++$fee_index;
                // }
                if ( ! empty($replace_collections) ) {
                    $this->ci->tldOrderBuilder->setReplaceCollectionsType(0, "Per Group")
                                            ->setReplaceCollectionsMoney(0, $replace_collections->SUM_SSJE)
                                            ->setReplaceCollectionsRemark(0, $replace_collections->ALL_Memo);
                    $this->ci->tldOrderBuilder->setTravelFeesType($fee_index, "Per Group")
                                            ->setTravelFeesMoney($fee_index, $replace_collections->SUM_SSJE)
                                            ->setTravelFeesNum($fee_index, 1)
                                            ->setTravelFeesUnit($fee_index, 1)
                                            ->setTravelFeesSumMoney($fee_index, $replace_collections->SUM_SSJE)
                                            ->setTravelFeesRemark($fee_index, "代收; " .  $replace_collections->ALL_Memo);
                }
            }
            // 查询是否变更 deprecated
            $sync_orderstate = 10;
            $vps_sn = 0;
            $vendor_orderid = 0;
            $this->ci->tldOrderBuilder->clearModifyLogInfo();
            $resp = $this->excute_curl($this->neworder_url, $this->ci->tldOrderBuilder);
            $response = json_decode($resp);
            if ($response->status == 1) {
                /** VendorPlanSync */
                $sync_ret = array(
                    "VPS_VAS_SN" => $vas_sn
                   ,"VPS_GRI_SN" => $gri_sn
                   ,"VPS_VEI_SN" => $vei_sn
                   ,"VPS_startDate" => $first_date
                   ,"VPS_endDate" => $end_date
                   ,"VPS_tourCode" => $tour_code
                   ,"VPS_sendHost" => $userId
                   ,"VPS_externalId" => $response->responseData->orderId
                   ,"VPS_externalorderType" => $order_type
                   ,"VPS_externalorderState" => $sync_orderstate
                   ,"VPS_sendTime" => date('Y-m-d H:i:s')
                );
                if ($vps_sn === 0) {
                    $sync_id = $this->ci->Group_model->insert_VendorPlanSync($sync_ret);
                    $this->ci->BIZ_order->insert_biz_order_log($coli_sn, "vendorPlanSendout_" . $tour_code);
                } else {
                    $update = $this->ci->Group_model->update_VendorPlanSync($vps_sn, $sync_ret);
                    $this->ci->BIZ_order->insert_biz_order_log($coli_sn, "vendorPlanUpdateSendout_" . $tour_code);
                }
                /** VendorArrangeState VAS_IsReceive */
                $this->ci->Group_model->set_plan_received($vas_sn, $gri_sn);
            }
        }
        return "[Tulanduo>push_trippest] Done. " . $COLI_ID;
    }

    public function tourguide_update($input, $vps, $eva)
    {
        return false;
        $ret['status'] = -1;
        $ret['err'] = 100;
        $ret['errMsg'] = "未知错误";
        $eva_g_sn = $eva[0]->has_tourguide;
        if (strval($vps->department)==="30") {
            $userId = $this->send_host["30"]['userId'];
            $userKey = $this->send_host["30"]['key'];
        } else {
            $userId = $this->send_host["1"]['userId'];
            $userKey = $this->send_host["1"]['key'];
        }
        $this->tld_order->setOrderId($vps->VPS_externalId)
                        ->setUserId($userId)
                        ->setKey($userKey);
        $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order);
        // $detail_resp = '{"status":1,"errMsg":"","orderDetail":{"orderId":' . rand(1000,9999) . ',"operationDetails": {"guiderOperations":[{"name":"北京翟梦琪Susie","mobelPhone":"18801326155","startDate":"2017-04-25","endDate":"2017-04-25","sumMoney":400,"remark":"","guiderPhoto":"http://djb3c.ltsoftware.net:9921/projects/djb3c//uploadImages/guider/1526898234415.png"}]}}}'; // test:
        $detail_jsonResp = json_decode($detail_resp);
        // 判断
        if ($detail_jsonResp->status !== 1) {
            log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent());
            $ret['err'] = 100; // 获取详情失败
            $ret['errMsg'] = "获取详情失败";
            return $ret;
        }
        // 导游信息
        $tourguige_name = "";
        $tourguide_mobile = null;
        if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) {
            $tourguige_name = $detail_jsonResp->orderDetail->operationDetails->guiderOperations[0]->name;
            $tourguide_mobile = real_phone_number($detail_jsonResp->orderDetail->operationDetails->guiderOperations[0]->mobelPhone, 86);
        }
        if ($tourguige_name === "") {
            $ret['err'] = 102; // 未查询到导游
            $ret['errMsg'] = "未查询到导游";
            return $ret;
        }
        preg_match_all('/[^\w\s\-]+/', characet($tourguige_name, "UTF-8"), $cn_name_arr);   // 取中文
        $tourguige_name_cn = preg_replace('/^(上海|北京|西安)/', '', characet($cn_name_arr[0][0],'UTF-8'));
        preg_match_all('/[a-zA-Z]+/', characet($tourguige_name, "UTF-8"), $en_name_arr);   // 取英文
        $tourguige_name_en = characet($en_name_arr[0][0],'UTF-8');
        $ht_tourguide = $this->Group_model->search_tourguide($input['openId'], $tourguige_name_cn, $tourguige_name_en, $tourguide_mobile);
        if (empty($ht_tourguide)) {
            $ret['err'] = 200; // 导游信息未录入
            $ret['errMsg'] = "导游信息未录入";
            return $ret;
        }
        $vendor_contactor = $this->Group_model->get_vendorContact($eva[0]->EOI_ObjSN);
        $eva_tgi_column = array(
            "EOI_Type"               => 3
            ,"EOI_GRI_SN"            => $eva[0]->EOI_GRI_SN
            ,"EOI_VEI_SN"            => $eva[0]->EOI_ObjSN
            ,"EOI_ObjSN"             => $ht_tourguide->TGI_SN
            ,"EOI_CII_SN"            => $eva[0]->EOI_CII_SN
            ,"EOI_GetDate"           => $eva[0]->EOI_GetDate
            ,"EOI_Date"              => $eva[0]->EOI_Date
            ,"EOI_Cancel"            => $eva[0]->EOI_Cancel
            ,"EOI_GroupType"         => $eva[0]->EOI_GroupType
            ,"EOI_FillWorkers_SN"    => $vendor_contactor->LMI_SN
            ,"EOI_FWks_LastEditTime" => date('Y-m-d H:i:s')
        );
        $this->Group_model->set_plan_tourguide($eva_g_sn, $eva_tgi_column);
        $ret['status'] = 1;
        $ret['err'] = 0;
        $ret['errMsg'] = "";
        return $ret;
    }

    /*!
     * 订单状态变更,调度变更
     * (地接社调用, 并邮件通知外联)
     */
    public function order_change()
    {
        return false;
        $this->load->model('Order_update');
        $ret['status'] = -1;
        $ret['errMsg'] = "未知错误";
        $input = $this->input->post();
        $vendorID = $input['openId'];
        $validate = $this->calc_key($vendorID, $input['key']);
        if ($validate !== TRUE) {
            $ret['errMsg'] = "身份验证失败.";
            return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        }
        // $vendorID = 29188;//29188 1343; // test:
        $vas_info = array();
        if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) {
            $vas_info = $this->BIZ_order->get_vendorarrangestate_byVendor($input['orderId'], $vendorID);
            if (empty($vas_info) && ! empty($input['agcOrderNo'])) {
                $real_groupCode = analysis_groupCode($input['agcOrderNo']);
                $vas_info = $this->BIZ_order->get_vendorarrangestate_byGroup($real_groupCode, $vendorID);
            }
        } elseif ($input['agcName'] == '桂林海纳国旅') {
            $real_groupCode = analysis_groupCode($input['agcOrderNo']);
            $vas_info = $this->BIZ_order->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID);
        }

        if (empty($vas_info)) {
            $ret['errMsg'] = "未找到订单.";
        } else {
            $vendor_manager = $this->BIZ_order->get_vendorContact($vendorID);
            /** VendorArrangeState */
            $VAS_ConfirmInfo = $input['orderRemark'] . "\r\n======确认人: " . $input['orderDuty'] . ", 确认时间: " . $input['orderTime'];
            $VAS_ConfirmInfo .= "\r\n" . $vas_info[0]->VAS_ConfirmInfo;
            $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $vendor_manager->LMI_SN, $VAS_ConfirmInfo);
            if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { // 传统团的不需要更新订单主表
                /** BIZ_confirmlineinfo */
                $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN;
                $coli_update_column = array(
                    "COLI_State" => 7
                );
                $update_coli = $this->Order_update->biz_confirmlineinfo_update($coli_update_column);
            }
            if ($update_vas === TRUE) {
                $ret['status'] = 1;
                $ret['errMsg'] = "";
            }
        }
        if ($ret['status'] !== 1) {
            log_message('error','图兰朵确认上报失败. POST RAW: ' . raw_json_encode($input) . "; Result: " . raw_json_encode($ret));
        }
        $sender_name = "中华游供应商合作平台";
        $sender_mail = "info@chinahighlights.net";
        $from_name   = $vendor_manager->LMI2_Name;
        $from_mail   = $vendor_manager->LMI_ListMail;
        $to_name     = $vas_info[0]->OPI_Name;
        $to_mail     = $vas_info[0]->OPI_Email;
        $subject     = $input['agcOrderNo'] . "团已确认: " . $vendor_manager->VEI2_CompanyBN;
        $mail_body   = $vendor_manager->VEI2_CompanyBN . "对团" . $input['agcOrderNo'] . "的计划在" . $input['orderTime'] . "已确认。\r\n";
        $mail_body  .= "确认说明：" . $input['orderRemark'] . "\r\n";
        $mail_body  .= "确认人：$vendor_manager->LMI2_Name $vendor_manager->LMI_ListMail 固定电话: $vendor_manager->LMI_Telephone 移动电话:$vendor_manager->LMI_Mobile\r\n";
        $mail_body  .= "变更内容: " . $vas_info[0]->VAS_ChangeText . "\r\n";
        $this->BIZ_order->save_automail($sender_name, $sender_mail, $from_name, $from_mail, $to_name, $to_mail, $subject, $mail_body, $sender_name);

        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    private function excute_curl($url, $content_builder)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Accept: application/json"
        ));

        $params_str = $content_builder->getBizContent();
        $postBody = array('jsonParams' => $params_str, "notHander" => 1);

        if (is_string($params_str) && 0 < mb_strlen($params_str)) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
        }

        $reponse = curl_exec($ch);
        $eval_resp = json_decode($reponse);

        if (curl_errno($ch) || $eval_resp->status == 0) {
            log_message('error', "curl error code: ".curl_error($ch) . $eval_resp->errMsg . "; curl postBodyString: ".json_encode($postBody));
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                log_message('error', "Request html Status Code: ".$httpStatusCode."; curl postBodyString: ".json_encode($postBody));
            }
        }
        curl_close($ch);
        return $reponse;
    }

    public function pag_no_tmp($routeName='')
    {
        return array(
            "故宫深度一日游（目的地）" => "BJSIC-44"
            ,"故宫深度游拼团（目的地）" => "BJSIC-44"
            ,"北京精品一日游（目的地）" => "BJSIC-41"
            ,"北京精品一日游（PVT）（目的地）" => "BJSIC-41"
            ,"北京精品两日游（目的地）" => "BJSIC-42"
            ,"北京精品两日游（PVT）（目的地）" => "BJSIC-42"
            ,"北京精品三日游（目的地）" => "BJSIC-43"
            ,"北京精品游D2（目的地）" => "BJSIC-42"
            ,"北京精品游D3（目的地）" => "BJSIC-43"
            ,"北京单租车服务（目的地）" => "BJALC-209"
            ,"北京单租车接送（常规）" => "BJALC-209"
            ,"北京单租车接送服务（目的地）" => "BJALC-209"
            ,"北京市内-天津新港大车接送（目的地）" => "BJSIC-16"
            ,"天津新港-北京市内大车接送（目的地）" => "BJSIC-16"
            ,"箭扣-慕田峪徒步一日游（目的地）" => "BJSIC-45"
            ,"箭扣-慕田峪徒步一日游（PVT）（目的地）" => "BJSIC-45"
            ,"箭扣-慕田峪长城徒步拼团（目的地）" => "BJSIC-45"
            ,"司马台西-金山岭徒步一日游（目的地）" => "BJSIC-46"
            ,"司马台西-金山岭徒步一日游（PVT）（目的地）" => "BJSIC-46"
            ,"司马台西-金山岭长城徒步拼团（目的地）" => "BJSIC-46"
            ,"慕田峪半日游拼团（目的地）" => "BJSIC-47"
            ,"慕田峪半日游PVT（目的地）" => "BJSIC-47"
            ,"古北口长城徒步一日游（目的地）" => "BJSIC-48"
            ,"古北口（目的地）" => "BJSIC-48"
            ,"半日游广场故宫拼团（目的地）" => "BJSIC-41"
 // ,=>
            ,"西安精品一日游（目的地）" => "XASIC-41"
            ,"西安精品一日游PVT（目的地）" => "XASIC-41"
            ,"西安市内精品一日游（目的地）" => "XASIC-41"
            ,"西安精品两日游（目的地）" => "XASIC-42"
            ,"西安单租车服务（目的地）" => "XASIC-17"
            ,"西安单租车接送服务（目的地）" => "XASIC-17"
            ,"西安单租车接送服务" => "XASIC-17"
            ,"西安兵马俑精品一日游（目的地）" => "XASIC-41"
            ,"西安兵马俑精华一日游（目的地）" => "XASIC-41"
            ,"西安兵马俑精品半日游（目的地）" => "XASIC-15"
            ,"西安兵马俑精品半日游PVT（目的地）" => "XASIC-15"
            ,"西安汉阳陵市内精品一日游（目的地）" => "XASIC-42"
 // ,=>
            ,"上海精品一日游（目的地）" => "SHSIC-41"
            ,"上海精品游PVT线路（目的地）" => "SHSIC-41"
            ,"上海市内精品一日游（目的地）" => "SHSIC-42"
            ,"周庄锦溪精品一日游（目的地）" => "SHSIC-43"
            ,"苏州精品一日游（目的地）" => "SHSIC-44"
            ,"上海单租车（目的地）" => "SHSIC-45" //"SHALC-6,7,8,9"
            ,"上海单租车接送服务（目的地）" => "SHSIC-45" //"SHALC-6,7,8,9"
        );
    }

    public function calc_key($userId, $key)
    {
        $default = "b825e39422a54875a95752fc7ed6f5d2";
        $ret = md5(hash("sha256", $userId.$default));
        return $ret===$key;
    }


}
