<?php

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

define('PAY_TO_AGENCY',15020);

class TulanduoApi extends CI_Controller
{
    public $special_route = array(
        "BJSIC-42" => "'BJSIC-41','BJSIC-42'"
        ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'"
        ,"XASIC-42" => "'XASIC-41','XASIC-42'"
    );
    public $special_route_name = array(
        "BJSIC-42" => "北京精品两日游（目的地BJSIC-42）"
        ,"BJSIC-43" => "北京精品三日游（目的地BJSIC-43）"
        ,"XASIC-42" => "西安精品两日游（目的地XASIC-42）"
    );
    public $city_info = array(
        "北京分公司" => array(
            "PlanVEI_SN" => 1343
            ,"COLI_sourcetype" => 32090
            ,"routeType" => "北京目的地线路"
        ),
        "总部" => array(
            "PlanVEI_SN" => 1343
            ,"COLI_sourcetype" => 32090
            ,"routeType" => "北京目的地线路"
        ),
        "西安分公司" => array(
            "PlanVEI_SN" => 30548
            ,"COLI_sourcetype" => 32116
            ,"routeType" => "西安目的地线路"
        ),
        "上海分公司" => array(
            "PlanVEI_SN" => 29188
            ,"COLI_sourcetype" => 32112
            ,"routeType" => "上海目的地线路"
        ),
        "北京目的地线路" => array(
            "PlanVEI_SN" => 1343
            ,"COLI_sourcetype" => 32090
            ,"routeType" => "北京目的地线路"
        ),
        "西安目的地线路" => array(
            "PlanVEI_SN" => 30548
            ,"COLI_sourcetype" => 32116
            ,"routeType" => "西安目的地线路"
        ),
        "上海目的地线路" => array(
            "PlanVEI_SN" => 29188
            ,"COLI_sourcetype" => 32112
            ,"routeType" => "上海目的地线路"
        )
    );
    public $vendor_ids = array(1343,30548,29188);

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

    // test
    // public $list_url     = "http://dj.ltsoftware.net:9901/action/api/searchRouteOrder/";
    // public $detail_url   = "http://dj.ltsoftware.net:9901/action/api/detailRouteOrder/";
    public $neworder_url = "http://dj.ltsoftware.net:9901/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/";

    // 发送到图兰朵系统接口的参数jsonParams

    public function __construct(){
        parent::__construct();
        mb_regex_encoding("UTF-8");
        bcscale(4);
        $this->load->helper('array');
        $this->load->library('trippest');
        $this->load->model('Orders_model');
        $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order');
        // $this->output->enable_profiler(TRUE);
        /** test */
        // $this->userId = "358";
        // $this->key    = "a08f26ddc5b1bd4c8e5eafcac28fc1ec";
        /** Live */
        // 目的地
        $this->userId = "1134";
        $this->key    = "73d180d05d425fd192e1c5b3097e75ff";
        // 桂林海纳国旅
        // $this->userId = "18";
        // $this->key    = "d05c25e6e6c5d4898161e0aaf700d9c7";
    }

    /*!
     * 获取订单列表
     * @date   2018-05-02
     */
    public function get_orderlist($order_number=null)
    {
        $startOrderDate = date('Y-m-d', strtotime("-2 days"));
        $endOrderDate   = date('Y-m-d');
        $startTravelDate = date('Y-m-d');
        $endTravelDate   = date('Y-m-d', strtotime("+2 days"));
        $this->tld_order->setUserId($this->userId)
                        ->setKey($this->key)
                        ->setPageSize(20)
                        ->setPageIndex(1) ;
        if ( ! empty($order_number)) {
            $this->tld_order->setAgcOrderNo($order_number);
        } else {
            if (date('i') == '00') {
                return;
            }
            $get_type = rand(0, 1); // 需要按预定时间和出发时间, 避免有漏的
            if ($get_type === 0) {
                log_message('error','Got order list From TuLanDuo By travel Date' );
                $this->tld_order->setStartTravelDate($startTravelDate)
                                ->setEndTravelDate($endTravelDate) ;
            } else {
                log_message('error','Got order list From TuLanDuo By order Date' );
                $this->tld_order->setStartOrderDate($startOrderDate)
                                ->setEndOrderDate($endOrderDate) ;
            }
        }
        $resp = $this->excute_curl($this->list_url, $this->tld_order);
        $resp_arr = json_decode($resp, true);
        if ($resp_arr['status'] !== 1) {
            log_message('error','TulanduoApi Got order list failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent()));
            return;
        }
        if ($resp_arr["responseData"]["totalRows"] == 0) {
            return;
        }
        $all_list = $resp_arr["responseData"]["orders"];
        for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) {
            $this->tld_order->setPageIndex($pi);
            $f_resp = $this->excute_curl($this->list_url, $this->tld_order);
            $f_resp_arr = json_decode($f_resp, true);
            if ($resp_arr['status'] !== 1) {
                log_message('error','TulanduoApi Got order list failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent()));
                continue;
            }
            $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]);
        }
        $cnt = 0;
        $order_id_str = "";
        $pag_no_tmp = $this->pag_no_tmp();
        mb_regex_encoding("UTF-8");
        $unique_order = array();
        foreach ($all_list as $k => $vo) {
            if (in_array($vo['orderId'], $unique_order)) {
                continue;
            }
            $unique_order[] = $vo['orderId'];
            // paypal 手续费订单没有团号
            $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo'];
            $vo['agcOrderNo'] = (trim($vo['agcOrderNo'])); // 去掉中文的全角空格

            $this->Orders_model->BIZ_COLI_SN = null;
            $this->Orders_model->GRI_SN = null;
            $this->Orders_model->GCI_SN = null;
            $tmpv = $this->city_info[$vo['routeType']]['PlanVEI_SN'] ? $this->city_info[$vo['routeType']]['PlanVEI_SN'] : 1343;
            // set GCI_SN
            $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过
            if ($this->Orders_model->BIZ_COLI_SN === null) {
                $real_groupCode_info = analysis_groupCode($vo['agcOrderNo']);
                $real_groupCode = $real_groupCode_info["cut"];
                // set BIZ_COLI_SN, GRI_SN at Orders_model
                $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']);
                if (empty($group_info)) {
                    $real_groupCode = $real_groupCode_info["all"];
                    $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']);
                }
            }
            if ($this->Orders_model->GRI_SN === null) {
                /** GRoupInfo */
                $this->insert_gri($vo);
            }
            /** insert HT */
            if ($this->Orders_model->BIZ_COLI_SN === null) {
                /** BIZ_Guest */
                $this->Orders_model->GUT_LastName = $vo['customerName'];
                $this->Orders_model->biz_guest_save();
                /** BIZ_ConfirmLineInfo*/
                $this->insert_coli($vo);
                /** BIZ_ConfirmLineDetail*/
                $this->insert_cold($vo);

                $cnt++;
            }
            if ($this->Orders_model->GCI_SN === null) {
                /*biz_groupcombineinfo*/
                $this->insert_gci($vo);

                $order_id_str .= ", " . $vo["orderId"];
            }
        }
        $output_text = "Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . ". Insert COLI : " . $cnt;
        $output_text .= "; " . $order_id_str;
        log_message('error', $output_text);
        echo $output_text;
        return;
    }

    /*!
     * 更新订单的详情;[客人列表, 团费, 调度信息]
     * * 定时执行, 约5分钟一次, 每次更新一个订单
     * @date   2018-05-02
     * @param  [type]     $coli_sn HT系统的订单key
     */
    public function insert_HT_order_operation($coli_sn=null,$get_vendorID=null, $output=true)
    {
        // log_message('error','get_order_operation From TuLanDuo ');
        $this->load->model('Order_update');
        if ($coli_sn !== null && $coli_sn != 0) {
            $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn);
        } elseif ($get_vendorID !== null) {
            $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $get_vendorID);
        } else {
            // $startDate = ('2018-04-21');
            // $endDate = ('2018-04-22'); // test
            $startDate = date('Y-m-d');
            $endDate = date('Y-m-d', strtotime("+2 days"));
            $to_update_list = $this->Orders_model->get_groupCombineInfo(0, null, $startDate, $endDate);
            if (empty($to_update_list)) {
                $to_update_list = $this->Orders_model->get_groupCombineInfo_finance();
            }
        }
        if (empty($to_update_list) ) {
            if ( $output===true) { echo "empty"; }
            return false;
        }
        $unique_orderGroupCombine = array();    // 录入拼团调度时,避免重复
        $order = $to_update_list[0];    // 只更新一个, 按更新时间升序, 被拆分之后需要多次出发更新(发现成本不对则手动更新)
        log_message('error','vendorID ' . $order->GCI_VendorOrderId);
        $this->tld_order->setOrderId($order->GCI_VendorOrderId)
                        ->setUserId($this->userId)
                        ->setKey($this->key);
        $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order);
        $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());
            if ( $detail_jsonResp->errMsg == "未查询到对应的订单") {
                $this->plan_cancel($order->GCI_VendorOrderId);
                if (intval($order->COLI_OPI_ID) === 435) {
                    $this->order_cancel($order->COLI_ID);
                }
            }
            if ($detail_jsonResp->errMsg == "您没有查看本订单的权限!") {
                $this->plan_cancel($order->GCI_VendorOrderId, "forbidden");
                if (intval($order->COLI_OPI_ID) === 435) {
                    $this->order_cancel($order->COLI_ID);
                }
            }
            if ( $output===true) { echo "cancel"; }
            return;
        }
        if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "重复") !== false) {
            /** groupcombineinfo */
            $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; // 不明确指定供应商id,出现过不对应的情况
            $gci_update_column = array(
                "GCI_createTime" => date('Y-m-d H:i:s')
                ,"GCI_combineNo" => null
            );
            $gci_info = $this->Order_update->biz_groupcombineinfo_update($gci_update_column);
            return;
        }
        if (isset($detail_jsonResp->orderDetail->agcOrderNo) && $detail_jsonResp->orderDetail->agcOrderNo!="") {
        } else {
            $detail_jsonResp->orderDetail->agcOrderNo = $detail_jsonResp->orderDetail->groupOrderNo;
        }
        if (isset($detail_jsonResp->orderDetail->groupOrderNo)) {
            $detail_jsonResp->orderDetail->groupOrderNo = (trim($detail_jsonResp->orderDetail->groupOrderNo));
        }
        $detail_jsonResp->orderDetail->agcOrderNo = (trim($detail_jsonResp->orderDetail->agcOrderNo)); // 去掉中文的全角空格
        // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态
        if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) {
            // $this->plan_cancel($order->GCI_VendorOrderId);
            if (intval($order->COLI_OPI_ID) === 435) {
                $this->order_cancel($order->COLI_ID);
            }
            if ($order->COLI_SN===null) {
                $this->plan_cancel($order->GCI_VendorOrderId);
                return;
            }
            // return;
        }
        $allDetails_to_HT = "";
        $allDetails_to_HT .= "\r\n日程: ";
        foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) {
            $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; ";
        }
        if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) {
            $allDetails_to_HT .= "\r\n导游: ";
            foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) {
                $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); ";
            }
        }
        if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) ) {
            $allDetails_to_HT .= "\r\n用车: ";
            foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vtc) {
                $allDetails_to_HT .= $vtc->name .": " . $vtc->driver." (". $vtc->driverTel . ") ";
                $allDetails_to_HT .= "[". $vtc->remark . "];  ";
            }
        }
        if (strval($detail_jsonResp->orderDetail->orderStatus) === '0') {
            if ( $output===true) { echo "not confirm"; }
            /** groupcombineinfo */
            $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "' and GCI_VEI_SN in (" . implode(',', $this->vendor_ids) . ")"; // 不明确指定供应商id,出现过不对应的情况
            $gci_update_column = array(
                "GCI_createTime" => date('Y-m-d H:i:s')
            );
            $gci_info = $this->Order_update->biz_groupcombineinfo_update($gci_update_column);
            return;
        }
        /** HT 开始 */
        $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->routeType]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->routeType]['PlanVEI_SN'] : 1343;
        $getInfo_byGroupCode = null;
        $getInfo_byGroupCodeArr = array();
        if (isset($detail_jsonResp->orderDetail->agcOrderNo) && $detail_jsonResp->orderDetail->agcOrderNo != "") {
            $real_groupCode_info = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo);
            $real_groupCode = $real_groupCode_info['cut'];
            if (strlen($real_groupCode) < 9) {
                $real_groupCode = $real_groupCode_info['all'];
            }
            if (strlen($real_groupCode_info['order']) >= 9
                && $detail_jsonResp->orderDetail->agcName=='D目的地桂林组'
            ) {
                $real_groupCode = $real_groupCode_info['order'];
            }
            $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode, $order->GCI_VendorOrderId, $vei_SN);
        }
        $duplicate = false;
        // 由同步新增的订单 或 未找到团号关联
        if (intval($order->COLI_OPI_ID) === 435
                || intval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) === 435
                || $order->COLI_ID === null
                || empty($getInfo_byGroupCodeArr)
        ) {
            if ( empty($getInfo_byGroupCodeArr)){
                $getInfo_byGroupCode = null;    // 没有该团号的团信息
            } elseif ($order->COLI_ID !== null && strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0
                $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0];     // 渠道和目的地有重复操作的团
                $duplicate = true;
            } else {
                $null_gci = array_map(function ($ele) {
                    if (intval($ele->COLI_OPI_ID)===435 && $ele->senderIP===''
                        && $ele->gci===null
                    ) {
                        return $ele->COLI_ID;
                    } else {
                        return null;
                    }
                }, $getInfo_byGroupCodeArr);
                foreach (array_unique(array_filter($null_gci)) as $knull => $vnull) {
                    $this->order_cancel($vnull);
                }
                foreach ($getInfo_byGroupCodeArr as $kg => $vg) {
                    // 同步的订单, 修改了团号, 用地接社id匹配
                    if(intval($order->COLI_OPI_ID)===435 && $order->GCI_VendorOrderId == $vg->gci) {
                        $getInfo_byGroupCode = $vg;
                        break;
                    }
                    if ($vg->COLI_GroupCode === substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49)) {
                        // 地接拆分的团号,需要全部匹配; 否则为没有团信息
                        $getInfo_byGroupCode = $vg;
                        break;
                    }
                }
            }
            if ($getInfo_byGroupCode === null) {
                /** INSERT */
                $order_detail_arr = (array)$detail_jsonResp->orderDetail;
                /** GRoupInfo */
                $groupSN = $this->insert_gri($order_detail_arr);
                /** BIZ_Guest */
                $this->Orders_model->GUT_SN = null;
                if (isset($detail_jsonResp->orderDetail->customers)) {
                    $this->Orders_model->GUT_LastName = $detail_jsonResp->orderDetail->customers[0]->name;
                    $this->Orders_model->biz_guest_save();
                }
                /** BIZ_ConfirmLineInfo*/
                $order_detail_arr['orderDate'] = $order_detail_arr['orderTime'];
                $coli_sn = $this->insert_coli($order_detail_arr);
                $coli_id = $this->Orders_model->BIZ_COLI_ID;
                /**BIZ_ConfirmLineDetail*/
                $cold_sn = $this->insert_cold($order_detail_arr);
            }
            $groupSN = isset($groupSN) ? $groupSN : $getInfo_byGroupCode->GRI_SN;
            $coli_sn = isset($coli_sn)&&intval($coli_sn)!==0 ? $coli_sn : $getInfo_byGroupCode->COLI_SN;
            $coli_id = isset($coli_id) ? $coli_id : $getInfo_byGroupCode->COLI_ID;
            $cold_sn = isset($cold_sn) ? $cold_sn : $getInfo_byGroupCode->COLD_SN;
            $coli_opi_id = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OPI_ID : 435;
            $coli_memo = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_Memo : "";
            $coli_state = (intval($coli_opi_id) !== 435) ? $getInfo_byGroupCode->COLI_State : 9;
            $coli_orderdetailtext = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OrderDetailText : "";
            $cold_memotext = isset($cold_sn) ? $this->Orders_model->COLD_MemoText : $getInfo_byGroupCode->COLD_MemoText;
        } else {
            // 已找到的目的地发的计划
            // $getInfo_byGroupCode = $order;
            $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0];
            $groupSN     = $getInfo_byGroupCode->COLI_GRI_SN;
            $coli_sn     = $getInfo_byGroupCode->COLI_SN;
            $coli_id     = $getInfo_byGroupCode->COLI_ID;
            $coli_memo   = $getInfo_byGroupCode->COLI_Memo;
            $coli_state  = $getInfo_byGroupCode->COLI_State;
            $cold_sn     = $getInfo_byGroupCode->COLD_SN; // ???多个子订单 !!!仅用于435创建的订单的更新, 因此仅一个
            $coli_opi_id = $getInfo_byGroupCode->COLI_OPI_ID;
            $coli_orderdetailtext = $getInfo_byGroupCode->COLI_OrderDetailText;
            $cold_memotext = $getInfo_byGroupCode->COLD_MemoText;
        }
        /** UPDATE */
        // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效
        if ($duplicate === true) {
            if ( $order->COLI_ID && $order->COLI_ID != $getInfo_byGroupCode->COLI_ID) {
                $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID;
                $this->order_cancel($order->COLI_ID);
            }
        }
        // 团款总金额
        // 渠道实收
        $travel_fee = 0;
        $travel_fee_currency = 'RMB';
        if (isset($detail_jsonResp->orderDetail->travelFees) ) {
            foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) {
                $travel_fee = bcadd($travel_fee, $vtf->sumMoney);
            }
            unset($vtf);
        }
        // 地接代收
        $agency_receipt = 0;
        if (isset($detail_jsonResp->orderDetail->replaceCollections) ) {
            foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) {
                $agency_receipt = bcadd($agency_receipt, $vrc->money);
            }
            unset($vrc);
        }
        /** groupcombineinfo */
        $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "' and GCI_VEI_SN in (" . implode(',', $this->vendor_ids) . ")"; // 不明确指定供应商id,出现过不对应的情况
        $gci_update_column = array(
            "GCI_combineNo"   => isset($detail_jsonResp->orderDetail->groupOrderNo) ? trim_str($detail_jsonResp->orderDetail->groupOrderNo) : null
            ,"GCI_VEI_SN"        => $vei_SN
            ,"GCI_GRI_SN"        => $groupSN
            ,"GCI_travelDate"    => $detail_jsonResp->orderDetail->travelDate
            ,"GCI_leaveDate"     => $detail_jsonResp->orderDetail->leaveDate
            ,"GCI_createTime"    => date('Y-m-d H:i:s')
            ,"GCI_priceCNY"      => $travel_fee
            ,"GCI_agencyReceipt" => $agency_receipt
        );
        $gci_info = $this->Order_update->biz_groupcombineinfo_update($gci_update_column);
        /** GRoupInfo */
        $coli_groupcode_ht = analysis_groupCode($getInfo_byGroupCode->COLI_GroupCode);
        $groupcode_ht = $coli_groupcode_ht['cut'];
        if (intval($coli_opi_id) === 435 ) {
            $gri_update_column = array(
                "GRI_No" => $detail_jsonResp->orderDetail->agcOrderNo
                ,"GRI_Name" => $detail_jsonResp->orderDetail->agcOrderNo
            );
            $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN;
            $this->Order_update->biz_groupinfo_update($gri_update_column);
        } elseif (strlen($groupcode_ht) > 9 && strpos($getInfo_byGroupCode->GRI_Name, $groupcode_ht)===false) {
            // $gri_update_column = array(
            //     "GRI_No" => $getInfo_byGroupCode->COLI_GroupCode
            //     ,"GRI_Name" => $getInfo_byGroupCode->COLI_GroupCode
            // );
            // $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN;
            // $this->Order_update->biz_groupinfo_update($gri_update_column);
        }

        /** BIZ_ConfirmLineInfo */
        $this->Order_update->coli_where_update = " COLI_SN=" . $coli_sn;
        $old_memo = mb_strstr($coli_memo, " orderRemark", true)!==false ? mb_strstr($coli_memo, " orderRemark", true) : $coli_memo;
        $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n";
        $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext;
        $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n";
        // 判断收款方并提示
        $finance_memo = "";
        if (intval($coli_opi_id) === 435 && in_array($gci_info->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) {
            $finance_memo .= "备注: 本订单组团社是渠道, 账单收款方应为地接社代收, 同步回来却是Trippest自营, 请注意核对.\r\n";
            $new_memo .= mb_strstr($new_memo, "orderRemark", true)!==false ? $finance_memo : ("orderRemark " . $finance_memo);
        } else if (intval($coli_opi_id) !== 435 && ! in_array($gci_info->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) {
            $finance_memo .= "备注: 本订单是自营团, 账单收款方应为海纳收款, 同步得到结果是桂林海纳分销渠道, 请注意核对.\r\n";
            $new_memo .= mb_strstr($new_memo, "orderRemark", true)!==false ? $finance_memo : ("orderRemark " . $finance_memo);
        }
        // 渠道价
        $partner_fee = 0;
        $partner_fee_currency = 'RMB';
        $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId);
        $total_num = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum;
        // $all_pag = $this->trippest->get_complex_pag(strtoupper($pag_info->PAG_Code));
        /** 渠道价不再补充计算, 直接计算所预订的产品渠道价 */
        $all_pag = array(strtoupper($pag_info->PAG_Code));
        foreach ($all_pag as $kp => $vp) {
            $partner_price = $this->Orders_model->get_partner_price(strtoupper($vp), $total_num, $detail_jsonResp->orderDetail->travelDate);
            if ( ! empty($partner_price)) {
                $partner_fee_currency = $partner_price->PKP_Currency ? $partner_price->PKP_Currency : "RMB";
                if (strval($partner_price->PKP_PriceType) === "1") {
                    // 每团
                    $partner_fee += $partner_price->PKP_AdultCost;
                } else {
                    // 每人
                    $adult_price = bcmul($detail_jsonResp->orderDetail->adultNum, $partner_price->PKP_AdultCost);
                    $child_price = bcmul($detail_jsonResp->orderDetail->childNum, $partner_price->PKP_ChildCost);
                    $partner_fee += bcadd($adult_price, $child_price);
                }
            }
            $partner_price = null;
        }
        if ($partner_fee > 0 && $partner_fee >= $travel_fee) {
            $travel_fee = $partner_fee;
            $travel_fee_currency = $partner_fee_currency;
        }
        $coli_update_column = array(
            "COLI_Memo"             => mb_convert_encoding(substr($new_memo, 0, 400), 'UTF-8')
            ,"COLI_OrderDetailText" => mb_convert_encoding($new_detail, 'UTF-8')
        );
        if (intval($coli_opi_id)===435) {
            $coli_update_column["COLI_IsSuccess"] = 1;  // 表示成行订单
            $coli_update_column["COLI_State"] = $coli_state;
            $coli_update_column["COLI_Price"] = $travel_fee;
            $coli_update_column["COLI_CUrrency"] = $travel_fee_currency;
            $coli_update_column["COLI_GroupCode"] = substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49);
            $coli_update_column["COLI_sourcetype"] = empty($this->city_info[$detail_jsonResp->orderDetail->routeType]) ? 32090 : $this->city_info[$detail_jsonResp->orderDetail->routeType]['COLI_sourcetype'];
        }
        $this->Order_update->biz_confirmlineinfo_update($coli_update_column);
        /**
         * update BIZ_ConfirmLineDetail
         * insert BIZ_BookPeople,BIZ_PackageOrderInfo
         */
        /** BIZ_ConfirmLineDetail */
        $COLD_MemoText = raw_json_encode(array("Pick up"=>$detail_jsonResp->orderDetail->toTraffic, "Drop off"=>$detail_jsonResp->orderDetail->backTraffic));
        $new_memotext = trim($cold_memotext)===""||(json_decode($cold_memotext)!==null&&!is_numeric(json_decode($cold_memotext))) ? $COLD_MemoText : $cold_memotext;
        $cold_update_column = array(
            "COLD_MemoText" => $COLD_MemoText
        );
        if (intval($coli_opi_id)===435) {
            $cold_update_column['COLD_MemoText']    = $COLD_MemoText;
            $cold_update_column['COLD_PersonNum']   = $detail_jsonResp->orderDetail->adultNum;
            $cold_update_column["COLD_ChildNum"]    = $detail_jsonResp->orderDetail->childNum;
            $cold_update_column["COLD_ServiceSN"]   = $pag_info->serviceinfo->PAG2_PAG_SN;
            $cold_update_column["COLD_ServiceSN2"]  = $pag_info->pag_sub;
            $cold_update_column["COLD_ServiceCity"] = $pag_info->serviceinfo->PAG_CII_SN;
            $cold_update_column["COLD_PlanVEI_SN"]  = $vei_SN;
            $cold_update_column["COLD_StartDate"]   = $detail_jsonResp->orderDetail->travelDate;
            $cold_update_column["COLD_EndDate"]     = $detail_jsonResp->orderDetail->leaveDate;
        }
        $this->Order_update->cold_where_update = " COLD_SN=" . $cold_sn;
        $this->Order_update->biz_confirmlinedetail_update($cold_update_column);
        if (intval($coli_opi_id) === 435) {
            /** INSERT */
            /*BIZ_BookPeople*/
            if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) {
                if (isset($detail_jsonResp->orderDetail->customers)) {
                    foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) {
                        $this->Orders_model->BPE_FirstName = substr($vd->name, 0, 40);
                        $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2;
                        $this->Orders_model->BPE_Passport  = $vd->documentNo;
                        $bpe_sn[] = $this->Orders_model->biz_book_people_save();
                        // BIZ_BookPeopleList
                        $this->Orders_model->biz_bookpeople_List_save($cold_sn, $this->Orders_model->BPE_SN);
                    }
                }
            }
            /*BIZ_PackageOrderInfo*/
            $this->Orders_model->POI_COLD_SN       = $cold_sn;
            $this->Orders_model->POI_Time          = $detail_jsonResp->orderDetail->travelDate;
            $this->Orders_model->POI_Hotel         = isset($detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation) ? $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation : '';
            $this->Orders_model->POI_HotelAddress  = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationAddress;
            $this->Orders_model->POI_HotelPhone    = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationTelNo;
            $this->Orders_model->POI_EndTime       = $detail_jsonResp->orderDetail->leaveDate;
            $this->Orders_model->POI_QuotationType = 1; // 1 报价 2 网络支付价 3 促销价
            $this->Orders_model->biz_packageorder_save();
        }
        // query latest order detail
        $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id);
        /** BIZ_GroupAccountInfo */
        // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户
        $paytype = PAY_TO_AGENCY; // 地接代收
        $pay_currency = 'RMB';
        $auto_text = "dataAutoEnter ";
        // 删除旧的录入
        $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype);
        if (intval($latest_order_detail[0]->COLI_OPI_ID)===435) {
            $gai_vei_sn = $latest_order_detail[0]->COLD_PlanVEI_SN;
            // 团款
            if (isset($detail_jsonResp->orderDetail->travelFees) ) {
                foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) {
                    $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vtf->sumMoney, $vtf->sumMoney,$gai_vei_sn, $auto_text . "团款" . $vtf->type . ", " . $vtf->remark);
                }
            }
            // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入.
            // 代收
            // 此处代收是地接社角度的代收, 计算利润时需扣减还给地接社, 因此录入为负.
            //     代付同理
            // if (isset($detail_jsonResp->orderDetail->replaceCollections) ) {
            //     foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) {
            //         $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, '-' . $vrc->money, '-' . $vrc->money,$gai_vei_sn, $auto_text . "代收" . $vrc->type . ", " . $vrc->remark);
            //     }
            // }
            if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) {
                foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $koor => $voor) {
                    $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $voor->sumMoney, $voor->sumMoney, $gai_vei_sn, $auto_text . "其他收入" . $voor->type . ", " . $voor->remark);
                }
            }
            // 代付
            // if (isset($detail_jsonResp->orderDetail->replacePays) ) {
            //     foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) {
            //         $GAI_SQJE = $vrp->money;
            //         $GAI_SSJE = $vrp->money;
            //         $GAI_Memo = $auto_text . "代付" . $vrp->type . ", " . $vrp->remark;
            //         $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $gai_vei_sn, $GAI_Memo);
            //     }
            // }
            // 没有收款记录, 则写入一条=0, 以免财务表无法保存
            if ( ! isset($detail_jsonResp->orderDetail->operationDetails->otherReceives)
                  &&  ! isset($detail_jsonResp->orderDetail->travelFees) ) {
                $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, 0, 0, $gai_vei_sn, $auto_text );
            }
        }
        /*BIZ_GroupCombineOperationDetail*/
        if ( isset($detail_jsonResp->orderDetail->groupOrderNo) ) {
        // 删除旧的录入
        $this->Orders_model->biz_groupcombineoperationdetail_cut(trim_str($detail_jsonResp->orderDetail->groupOrderNo), $vei_SN);
        // 门票
        if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo);
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "sceneryOperations";
                $this->Orders_model->GCOD_subType       = $vso->type;
                $this->Orders_model->GCOD_title         = $vso->name;
                $this->Orders_model->GCOD_startDate     = $vso->useDate;
                $this->Orders_model->GCOD_endDate       = $vso->useDate;
                $this->Orders_model->GCOD_useNum        = $vso->useNum;
                $this->Orders_model->GCOD_sumMoney      = $vso->sumMoney;
                $this->Orders_model->GCOD_remark        = $vso->remark;
                $this->Orders_model->GCOD_dutyName      = "";
                $this->Orders_model->GCOD_dutyTel       = null;
                $this->Orders_model->GCOD_dutyPhoto     = null;
                $this->Orders_model->GCOD_standard      = "";
                $this->Orders_model->GCOD_carLicense    = "";
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        // 用房
        if (isset($detail_jsonResp->orderDetail->operationDetails->accommodationOperations) ) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->accommodationOperations as $vao) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ;
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "accommodationOperations";
                $this->Orders_model->GCOD_subType       = $vao->type;
                $this->Orders_model->GCOD_title         = $vao->name;
                $this->Orders_model->GCOD_startDate     = $vao->useDate;
                $this->Orders_model->GCOD_endDate       = $vao->useDate;
                $this->Orders_model->GCOD_useNum        = $vao->useNum;
                $this->Orders_model->GCOD_sumMoney      = $vao->sumMoney;
                $this->Orders_model->GCOD_standard      = "";
                $this->Orders_model->GCOD_remark        = $vao->remark;
                $this->Orders_model->GCOD_dutyName      = "";
                $this->Orders_model->GCOD_dutyTel       = null;
                $this->Orders_model->GCOD_dutyPhoto     = null;
                $this->Orders_model->GCOD_carLicense    = "";
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        // 用餐
        if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ;
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "restraurantOperations";
                $this->Orders_model->GCOD_subType       = $vro->type;
                $this->Orders_model->GCOD_title         = $vro->name;
                $this->Orders_model->GCOD_startDate     = $vro->useDate;
                $this->Orders_model->GCOD_endDate       = $vro->useDate;
                $this->Orders_model->GCOD_useNum        = $vro->useNum;
                $this->Orders_model->GCOD_sumMoney      = $vro->sumMoney;
                $this->Orders_model->GCOD_standard      = $vro->standard;
                $this->Orders_model->GCOD_remark        = $vro->remark;
                $this->Orders_model->GCOD_dutyName      = "";
                $this->Orders_model->GCOD_dutyTel       = null;
                $this->Orders_model->GCOD_dutyPhoto     = null;
                $this->Orders_model->GCOD_carLicense    = "";
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        // 用车
        if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ;
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "touristCarOperations";
                $this->Orders_model->GCOD_subType       = $vco->type;
                $this->Orders_model->GCOD_title         = $vco->name;
                $this->Orders_model->GCOD_dutyName      = $vco->driver;
                $this->Orders_model->GCOD_dutyTel       = trim_str($vco->driverTel);
                $this->Orders_model->GCOD_startDate     = $vco->startDate;
                $this->Orders_model->GCOD_endDate       = $vco->endDate;
                $this->Orders_model->GCOD_sumMoney      = $vco->sumMoney;
                $this->Orders_model->GCOD_carLicense    = $vco->carLicense;
                $this->Orders_model->GCOD_useNum        = 1;
                $this->Orders_model->GCOD_standard      = "";
                $this->Orders_model->GCOD_dutyPhoto     = null;
                $this->Orders_model->GCOD_remark        = $vco->remark;
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        // 导游服务
        if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ;
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "guiderOperations";
                $this->Orders_model->GCOD_subType       = "";
                $this->Orders_model->GCOD_title         = "";
                $this->Orders_model->GCOD_dutyName      = $vgo->name;
                $this->Orders_model->GCOD_dutyTel       = trim_str($vgo->mobelPhone);
                $this->Orders_model->GCOD_dutyPhoto     = isset($vgo->guiderPhoto) ? $vgo->guiderPhoto : '';
                $this->Orders_model->GCOD_startDate     = $vgo->startDate;
                $this->Orders_model->GCOD_endDate       = $vgo->endDate;
                $this->Orders_model->GCOD_sumMoney      = $vgo->sumMoney;
                $this->Orders_model->GCOD_carLicense    = "";
                $this->Orders_model->GCOD_standard      = "";
                $this->Orders_model->GCOD_remark        = $vgo->remark;
                $this->Orders_model->GCOD_useNum        = 1;
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        // 其他支出
        if (isset($detail_jsonResp->orderDetail->operationDetails->otherCosts) ) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->otherCosts as $voc) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ;
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "otherCosts";
                $this->Orders_model->GCOD_subType       = $voc->type;
                $this->Orders_model->GCOD_title         = "";
                $this->Orders_model->GCOD_dutyName      = "";
                $this->Orders_model->GCOD_dutyTel       = "";
                $this->Orders_model->GCOD_dutyPhoto     = '';
                $this->Orders_model->GCOD_startDate     = "";
                $this->Orders_model->GCOD_endDate       = "";
                $this->Orders_model->GCOD_sumMoney      = $voc->sumMoney;
                $this->Orders_model->GCOD_carLicense    = "";
                $this->Orders_model->GCOD_standard      = "";
                $this->Orders_model->GCOD_remark        = $voc->remark;
                $this->Orders_model->GCOD_useNum        = $voc->useNum;
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        // 其他收入
        // if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) {
        //     foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $vor) {
        //         $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ;
        //         $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
        //         $this->Orders_model->GCOD_operationType = "otherReceives";
        //         $this->Orders_model->GCOD_subType       = $vor->type;
        //         $this->Orders_model->GCOD_title         = "";
        //         $this->Orders_model->GCOD_dutyName      = "";
        //         $this->Orders_model->GCOD_dutyTel       = "";
        //         $this->Orders_model->GCOD_dutyPhoto     = '';
        //         $this->Orders_model->GCOD_startDate     = "";
        //         $this->Orders_model->GCOD_endDate       = "";
        //         $this->Orders_model->GCOD_sumMoney      = $vor->sumMoney;
        //         $this->Orders_model->GCOD_carLicense    = "";
        //         $this->Orders_model->GCOD_standard      = "";
        //         $this->Orders_model->GCOD_remark        = $vor->remark;
        //         $this->Orders_model->GCOD_useNum        = $vor->useNum;
        //         $this->Orders_model->biz_groupcombineoperationdetail_save();
        //     }
        // }
        if (isset($detail_jsonResp->orderDetail->operationDetails->trafficOperations)) {
            foreach ($detail_jsonResp->orderDetail->operationDetails->trafficOperations as $vto) {
                $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ;
                $this->Orders_model->GCOD_VEI_SN        = $vei_SN;
                $this->Orders_model->GCOD_operationType = "trafficOperations";
                $this->Orders_model->GCOD_subType       = $vto->birthland . " " . $vto->destination;
                $this->Orders_model->GCOD_title         = $vto->trafficNo;
                $this->Orders_model->GCOD_dutyName      = "";
                $this->Orders_model->GCOD_dutyTel       = "";
                $this->Orders_model->GCOD_dutyPhoto     = '';
                $this->Orders_model->GCOD_startDate     = $vto->useDate;
                $this->Orders_model->GCOD_endDate       = "";
                $this->Orders_model->GCOD_sumMoney      = $vto->sumMoney;
                $this->Orders_model->GCOD_carLicense    = "";
                $this->Orders_model->GCOD_standard      = "";
                $this->Orders_model->GCOD_remark        = $vto->remark;
                $this->Orders_model->GCOD_useNum        = $vto->useNum;
                $this->Orders_model->biz_groupcombineoperationdetail_save();
            }
        }
        }
        $output_text = "Got order operations from TuLanDuo:" . $detail_jsonResp->orderDetail->orderId . ". " . $coli_id;
        log_message('error', $output_text);
        if ( $output===true) { echo $output_text; }
        if (strval($order->isHistory) === '1') {
            require_once('order_finance.php');
            $vendor_class = new Order_finance();
            $vendor_class->single_order_report($coli_sn);
        }
        return;
    }

    public function order_complement()
    {
        $start_date = NULL; $end_date = NULL;
        $group_code = $this->input->get_post("group_code");
        /**
         * 解析输入字段, 可能为拼团号或原始团号
         * * 拼团号: 直接解析为发团时间, 按发团时间查询列表
         * * 原始团号: 按团号查询
         */
        preg_match_all('/\d{4}\-\d{1,2}\-\d{2}/i', $group_code, $matchs_arr);
        if ( ! empty($matchs_arr[0])) {
            $start_date = $matchs_arr[0][0];
            $end_date = $matchs_arr[0][0];
            $group_code = NULL;
        }
        $order_list = $this->new_order_to_ht("travel", $start_date, $end_date, $group_code);
        if ( ! empty($order_list['data'])) {
            foreach ($order_list['data'] as $key => $order) {
                $this->insert_HT_order_operation(NULL, $order);
            }
        }
        return $this->output->set_content_type('application/json')->set_output(json_encode($order_list));
    }

    public function new_order_to_ht($date_type="travel", $start_date=NULL, $end_date=NULL, $group_code=NULL)
    {
        $this->load->model('Tulanduo_sync_model', 'sync_model');
        $ret = array();
        $ret['data'] = array();
        $ret['msg'] = "";
        $this->tld_order->setUserId($this->userId)
                        ->setKey($this->key)
                        ->setPageSize(50)
                        ->setPageIndex(1);
        if ( ! empty($group_code)) {
            $this->tld_order->setAgcOrderNo($group_code);
        } else {
            if ($date_type === "travel") {
                $this->tld_order->setStartTravelDate($start_date)
                                ->setEndTravelDate($end_date) ;
            } else {
                $this->tld_order->setStartOrderDate($start_date)
                                ->setEndOrderDate($end_date) ;
            }
        }
        $resp = $this->excute_curl($this->list_url, $this->tld_order);
        $resp_arr = json_decode($resp, true);
        if (intval($resp_arr['status']) !== 1) {
            log_message('error','TulanduoApi order_list failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent()));
            $ret['msg'] = "failed";
            return $ret;
        }
        // return $this->tld_order->getBizContent();
        if ($resp_arr["responseData"]["totalRows"] == 0) {
            $ret['msg'] = "notFound";
            return $ret;
        }
        $all_list = $resp_arr["responseData"]["orders"];
        for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) {
            $this->tld_order->setPageIndex($pi);
            $f_resp = $this->excute_curl($this->list_url, $this->tld_order);
            $f_resp_arr = json_decode($f_resp, true);
            if ($resp_arr['status'] !== 1) {
                log_message('error','TulanduoApi order_list failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent()));
                $ret['msg'] = "failed";
                continue;
            }
            $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]);
        }
        $all_vendor_order_id = array_map(function($ele){ return $ele['orderId'];}, $all_list);
        $all_vendor_order_id_str = implode(',', $all_vendor_order_id);
        $exists_ht = $exists_ht_order_id = null;
        $exists_ht = $this->sync_model->get_exists_vendorOrderId($all_vendor_order_id_str);
        $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht);
        $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id);
        if (empty($to_insert)) {
            $ret['msg'] = "synced";
        }
        foreach ($all_list as $k => $vo) {
            if ( ! in_array($vo['orderId'], $to_insert)) {
                continue;
            }
            // paypal 手续费订单没有团号
            $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo'];
            $vo['agcOrderNo'] = (trim_str($vo['agcOrderNo'])); // 去掉中文的全角空格

            $this->Orders_model->BIZ_COLI_SN = null;
            $this->Orders_model->GRI_SN = null;
            $this->Orders_model->GCI_SN = null;
            $tmpv = $this->city_info[$vo['routeType']]['PlanVEI_SN'] ? $this->city_info[$vo['routeType']]['PlanVEI_SN'] : 1343;
            // set GCI_SN
            $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过
            if ($this->Orders_model->BIZ_COLI_SN === null) {
                $real_groupCode_info = analysis_groupCode($vo['agcOrderNo']);
                $real_groupCode = $real_groupCode_info["cut"];
                // set BIZ_COLI_SN, GRI_SN at Orders_model
                $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']);
                if (empty($group_info)) {
                    $real_groupCode = $real_groupCode_info["all"];
                    $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']);
                }
            }
            if ($this->Orders_model->GRI_SN === null) {
                /** GRoupInfo */
                $this->insert_gri($vo);
            }
            /** insert HT */
            if ($this->Orders_model->BIZ_COLI_SN === null) {
                /** BIZ_Guest */
                $this->Orders_model->GUT_LastName = $vo['customerName'];
                $this->Orders_model->biz_guest_save();
                /** BIZ_ConfirmLineInfo*/
                $this->insert_coli($vo);
                /** BIZ_ConfirmLineDetail*/
                $this->insert_cold($vo);
            }
            if ($this->Orders_model->GCI_SN === null) {
                /*biz_groupcombineinfo*/
                $this->insert_gci($vo);
            }
        }
        $ret['data'] = array_values($to_insert);
        return $ret;
    }

    /*!
     * 往前获取历史数据
     * @date   2018-08-21
     */
    public $date_roll = 0;
    public function get_history_order_list($oldest_date=null)
    {
        return false; // 已全部结束
        // 避免执行超时, 滚动3次之后结束
        if ($this->date_roll > 2) {
            log_message('error', "Got order list from TuLanDuo. Roll end. " . $oldest_date);
            return false;
        }
        $this->date_roll ++;
        $this->load->model('Tulanduo_sync_model', 'sync_model');
        $oldest_date===null ? $oldest_date = $this->sync_model->get_oldest_offset() : null;
        // $oldest_date===null ? $oldest_date = '2018-05-10' : null;   // test
        // $oldest_date===null ? $oldest_date = '2018-04-28' : null;   // test
        $startTravelDate = date('Y-m-d', strtotime("-1 day", strtotime($oldest_date)));
        $endTravelDate = $oldest_date;
        $start_date = $this->input->get_post("start");
        $end_date = $this->input->get_post("end");
        // $date_type = "travel";
        // $date_type = isset($this->input->get_post("end")) ? $this->input->get_post("end") : "travel";
        $startTravelDate = $start_date ? $start_date : $startTravelDate;
        $endTravelDate = $end_date ? $end_date : $endTravelDate;
        $this->tld_order->setUserId($this->userId)
                        ->setKey($this->key)
                        ->setPageSize(20)
                        ->setPageIndex(1)
                        ->setStartTravelDate($startTravelDate)
                        ->setEndTravelDate($endTravelDate) ;
        $resp = $this->excute_curl($this->list_url, $this->tld_order);
        $resp_arr = json_decode($resp, true);
        if (intval($resp_arr['status']) !== 1) {
            log_message('error','TulanduoApi get_orderlist history failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent()));
            // return;
        }
        if ($resp_arr["responseData"]["totalRows"] == 0) {
            log_message('error','TulanduoApi get_orderlist history 0. ');
            // 继续往前滚日期
            return $this->get_history_order_list($startTravelDate);
        }
        $all_list = $resp_arr["responseData"]["orders"];
        for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) {
            $this->tld_order->setPageIndex($pi);
            $f_resp = $this->excute_curl($this->list_url, $this->tld_order);
            $f_resp_arr = json_decode($f_resp, true);
            if ($resp_arr['status'] !== 1) {
                log_message('error','TulanduoApi get_orderlist history failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent()));
                continue;
            }
            $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]);
        }
        $all_vendor_order_id = array_map(function($ele){ return $ele['orderId'];}, $all_list);
        $all_vendor_order_id_str = implode(',', $all_vendor_order_id);
        $exists_ht = $exists_ht_order_id = null;
        $exists_ht = $this->sync_model->get_exists_vendorOrderId($all_vendor_order_id_str);
        $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht);
        $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id);
        if (empty($to_insert)) {
            // 继续往前滚日期
            return $this->get_history_order_list($startTravelDate);
        }
        $cnt = 0;
        foreach ($all_list as $k => $vo) {
            if ( ! in_array($vo['orderId'], $to_insert)) {
                continue;
            }
            $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo'];
            $vo['agcOrderNo'] = (trim($vo['agcOrderNo'])); // 去掉中文的全角空格
            $tmpv = $this->city_info[$vo['routeType']]['PlanVEI_SN'] ? $this->city_info[$vo['routeType']]['PlanVEI_SN'] : 1343;
            $this->Orders_model->BIZ_COLI_SN = null;
            $this->Orders_model->GRI_SN = null;
            if ( isset($vo['agcOrderNo']) && $vo['agcOrderNo'] != "") {
                $real_groupCode_info = analysis_groupCode($vo['agcOrderNo']);
                $real_groupCode = $real_groupCode_info["cut"];
                // check BIZ_COLI_SN,GRI_SN
                $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']);
                if (empty($group_info)) {
                    $real_groupCode = $real_groupCode_info["all"];
                    $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']);
                }
            }
            /** INSERT */
            /** GRoupInfo */
            if ($this->Orders_model->GRI_SN === null) {
                $this->insert_gri($vo);
            }
            if ($this->Orders_model->BIZ_COLI_SN === null) {
                /** BIZ_Guest */
                $this->Orders_model->GUT_LastName = $vo['customerName'];
                $this->Orders_model->biz_guest_save();
                /** BIZ_ConfirmLineInfo */
                $this->insert_coli($vo);
                /** BIZ_ConfirmLineDetail */
                $this->insert_cold($vo);
                $cnt++;
            }
            /** biz_groupcombineinfo */
            $this->insert_gci($vo);
        }
        $output_text = "Got order list from TuLanDuo (" . $startTravelDate . " ~ " . $endTravelDate . "). count: " . $resp_arr["responseData"]["totalRows"] . ". Insert COLI : " . $cnt;
        log_message('error',$output_text);
        echo $output_text;
        return;
    }

    public function insert_gai($coli_sn, $gri_sn, $coli_id, $paytype, $currency, $sqje, $ssje, $gai_vei_sn, $memo="")
    {
        $this->Orders_model->GAI_Operator     = 435;
        $this->Orders_model->GAI_COLI_SN      = $coli_sn;
        $this->Orders_model->GAI_GRI_SN       = $gri_sn;
        $this->Orders_model->GAI_COLI_ID      = $coli_id;
        $this->Orders_model->GAI_Type         = $paytype;
        $this->Orders_model->GAI_SQJE         = $sqje;
        $this->Orders_model->GAI_SQJECurrency = $currency;
        $this->Orders_model->GAI_SSJE         = $ssje;
        $this->Orders_model->GAI_SSDate       = date("Y-m-d H:i:s");
        $this->Orders_model->GAI_Memo         = $memo;
        $this->Orders_model->GAI_VEI_SN       = $gai_vei_sn;
        return $this->Orders_model->biz_groupaccountinfo_save();
    }

    public function insert_cold($list_ele)
    {
        $COLD_MemoText = raw_json_encode(array("Pick up"=>$list_ele['toTraffic'], "Drop off"=>$list_ele['backTraffic']));
        $pag_info = $this->analysis_productcode($list_ele['routeName'], $list_ele['orderId']);
        $this->Orders_model->COLD_COLI_SN     = $this->Orders_model->BIZ_COLI_SN;
        $this->Orders_model->COLD_ServiceType = "D";
        $this->Orders_model->COLD_ServiceSN   = $pag_info->serviceinfo->PAG2_PAG_SN;
        $this->Orders_model->COLD_ServiceSN2  = $pag_info->pag_sub;
        $this->Orders_model->COLD_ServiceCity = $pag_info->serviceinfo->PAG_CII_SN;
        $this->Orders_model->COLD_StartDate   = $list_ele['travelDate'];
        $this->Orders_model->COLD_EndDate     = $list_ele['leaveDate'];
        $this->Orders_model->COLD_PersonNum   = $list_ele['adultNum'];
        $this->Orders_model->COLD_ChildNum    = $list_ele['childNum'];
        $this->Orders_model->cold_state       = $list_ele['orderStatus']==1 ? 9 : 104; // 9订妥 // 104联络地接中
        $this->Orders_model->DeleteFlag       = 0;
        $this->Orders_model->COLD_PlanVEI_SN  = $this->city_info[$list_ele['routeType']]['PlanVEI_SN'] ? $this->city_info[$list_ele['routeType']]['PlanVEI_SN'] : 1343;
        $this->Orders_model->COLD_MemoText = $COLD_MemoText;
        return $this->Orders_model->biz_confirm_detail_save();
    }

    public function insert_coli($list_ele)
    {
        $this->Orders_model->BIZ_COLI_GRI_SN          = $this->Orders_model->GRI_SN ;
        $this->Orders_model->BIZ_COLI_GroupCode       = $this->Orders_model->GRI_No ;
        $this->Orders_model->BIZ_GUT_SN               = $this->Orders_model->GUT_SN;
        $this->Orders_model->BIZ_COLI_ID              = $this->Orders_model->biz_make_order_number();
        $this->Orders_model->BIZ_COLI_ApplyDate       = $list_ele['orderDate'];
        $this->Orders_model->BIZ_COLI_sourcetype      = empty($this->city_info[$list_ele['routeType']]) ? 32090 : $this->city_info[$list_ele['routeType']]['COLI_sourcetype'];
        $this->Orders_model->BIZ_COLI_State           = 9;
        $this->Orders_model->BIZ_COLI_servicetype     = 'D';
        $this->Orders_model->BIZ_COLI_ConfirmType     = 52001;
        $this->Orders_model->BIZ_COLI_Memo            = "";
        $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $list_ele["orderId"] . ";线路:" . $list_ele['routeName'] . "; 团名: " . $list_ele['agcOrderNo'];
        $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null;
        $this->Orders_model->BIZ_COLI_OPI_ID = 435;
        $this->Orders_model->BIZ_COLI_IsSuccess = 1;
        $this->Orders_model->BIZ_COLI_PayManner = PAY_TO_AGENCY;
        return $this->Orders_model->biz_confirm_save();
    }

    public function insert_gri($list_ele)
    {
        $travelDate = new DateTime($list_ele['travelDate']);
        $leaveDate  = new DateTime($list_ele['leaveDate']);
        $date_diff  = $travelDate->diff($leaveDate);
        $this->Orders_model->GRI_No        = substr(trim_str($list_ele['agcOrderNo']), 0, 49);
        $this->Orders_model->GRI_OrderType = 227002; // 商务
        $this->Orders_model->GRI_Name      = substr(trim_str($list_ele['agcOrderNo']), 0, 49);
        $this->Orders_model->GRI_PersonNum = $list_ele['adultNum']+$list_ele['childNum'];
        $this->Orders_model->GRI_Days      = intval($date_diff->format('%R%a')+1);
        $this->Orders_model->GRI_IsCancel  = 0;
        $this->Orders_model->DeleteFlag    = 0;
        $this->Orders_model->GRI_OPI_ID    = 435;
        $this->Orders_model->GRI_operator  = 435;
        $this->Orders_model->GRI_Creator   = 435;
        return $this->Orders_model->groupinfo_save();
    }

    public function insert_gci($list_ele)
    {
        $this->Orders_model->GCI_combineNo     = isset($list_ele['groupOrderNo']) ? $list_ele['groupOrderNo'] : '';
        $this->Orders_model->GCI_GRI_SN        = $this->Orders_model->GRI_SN;
        $this->Orders_model->GCI_VEI_SN        = $this->city_info[$list_ele['routeType']]['PlanVEI_SN'] ? $this->city_info[$list_ele['routeType']]['PlanVEI_SN'] : 1343;
        $this->Orders_model->GCI_VendorOrderId = $list_ele['orderId'];
        $this->Orders_model->GCI_FromAgc       = $list_ele['agcName'];
        $this->Orders_model->GCI_groupType     = $list_ele['orderType'];
        $this->Orders_model->GCI_travelDate    = $list_ele['travelDate'];
        $this->Orders_model->GCI_leaveDate     = $list_ele['leaveDate'];
        $this->Orders_model->GCI_createTime    = date('Y-m-d H:i:s');
        return $this->Orders_model->biz_groupcombineinfo_save();
    }

    // 解析产品编号
    public function analysis_productcode($route_name, $vendor_orderid)
    {
        $ret = new stdClass();
        $ret->PAG_Code = null;
        $ret->pag_sub = null;
        $ret->serviceinfo = new stdClass();
        $pag_no_tmp = $this->pag_no_tmp();
        preg_match('/[a-zA-Z]+\-[0-9\-]+/', characet($route_name, "UTF-8"), $temp_array);
        if (empty($temp_array) && isset($pag_no_tmp[$route_name])) {
            $ret->PAG_Code = $pag_no_tmp[$route_name];
            $split_code = explode("-", $ret->PAG_Code);
            $ret->PAG_Code = $split_code[0] . "-" . $split_code[1];
            isset($split_code[2]) ? $ret->pag_sub=$split_code[2] : null;
        } else if ( ! empty($temp_array)) {
            $ret->PAG_Code = null;
            $ret->pag_sub = null;
            $split_code = explode("-", $temp_array[0]);
            $ret->PAG_Code = $split_code[0] . "-" . $split_code[1];
            isset($split_code[2]) ? $ret->pag_sub=$split_code[2] : null;
        } else {
            log_message('error',"UnKnown route name " . $ret->PAG_Code . " " . $vendor_orderid . " " . $route_name . var_export($temp_array, 1));
            $ret->serviceinfo->PAG2_SN     = null;
            $ret->serviceinfo->PAG_CII_SN  = null;
            $ret->serviceinfo->PAG2_PAG_SN = null;
        }
        $ret->PAG_Code = in_array($ret->PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $ret->PAG_Code;
        if ($ret->PAG_Code) {
            $ret->serviceinfo = $this->Orders_model->get_packageSN($ret->PAG_Code);
        }
        return $ret;
    }

    /*!
     * 取消团
     * @date   2018-05-02
     * @param  string    $COLI_ID HT系统订单号
     */
    public function order_cancel($COLI_ID="")
    {
        if ($COLI_ID == '') {
            return false;
        }
        log_message('error','update order_cancel ' . $COLI_ID);
        /** UPDATE HT */
        /** BIZ_ConfirmLineInfo */
        $this->Order_update->coli_where_update = " COLI_ID='" . $COLI_ID . "'";
        $coli_update_column = array(
            "COLI_State" => 50
            ,"COLI_IsSuccess" => NULL
        );
        return $this->Order_update->biz_confirmlineinfo_update($coli_update_column);
    }
    public function groupinfo_delete($gri_sn=0)
    {
        if ($gri_sn === 0) {
            return false;
        }
        /** GRoupInfo */
        $this->Order_update->gri_where_update = " GRI_SN='" . $gri_sn . "'";
        $gri_update_column = array(
            "DeleteFlag" => 1
        );
        return $this->Order_update->biz_groupinfo_update($gri_update_column);
    }
    public function plan_cancel($vendorID=0, $state="cancel")
    {
        if ($vendorID === 0) {
            return false;
        }
        /** groupcombineinfo */
        $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $vendorID . "'";
        $gci_update_column = array(
            "GCI_combineNo"   => $state
            ,"GCI_createTime" => date('Y-m-d H:i:s')
        );
        $this->Order_update->biz_groupcombineinfo_update($gci_update_column);
    }

    /*!
     * 发送预订计划到地接系统
     * TODO read word into remark
     * @date   2018-05-02
     * @param  string    $COLI_ID HT系统订单号
     */
    public function order_push($COLI_ID="") // test
    {
        // exit();
        /** 目的地 test */
        $this->userId = "358";
        $this->key    = "a08f26ddc5b1bd4c8e5eafcac28fc1ec";
        $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder');
        $orderinfo = $this->Orders_model->get_orderinfo_detail($COLI_ID);
        if(empty($orderinfo)) {return;}
        $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $orderinfo )) ;
        $guestlist       = $this->Orders_model->get_guestlist($COLD_SN_str);
        $scheduleDetails = $this->Orders_model->get_scheduleDetails($COLD_SN_str);
        $routeName = isset($this->special_route_name[$scheduleDetails[0]->PAG_Code]) ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name;
        // 子线路
        if ($scheduleDetails[0]->PAGS_CN_Title) {
            $routeName .= "[" . $scheduleDetails[0]->PAGS_CN_Title . "]";
        }
        $routeName .= " " . $scheduleDetails[0]->PAG_Code;
        if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) {
            $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]);
        }
        $travelFees = $this->Orders_model->get_paymentDetails($COLI_ID);
        bcscale(4);
        $this->tldOrderBuilder->setUserId($this->userId)
                              ->setKey($this->key)
                              ->setOrderType(2) // todo
                              ->setRouteName($routeName)
                              ->setRouteType($scheduleDetails[0]->CII2_Name . "目的地线路")
                              ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode . "-" . $scheduleDetails[0]->CII2_Name)
                              ->setAdultNum($orderinfo[0]->COLD_PersonNum)
                              ->setChildNum($orderinfo[0]->COLD_ChildNum)
                              ->setDestination($scheduleDetails[0]->CII2_Name)
                              ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true))
                              ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true))
                              ->setOrderRemark(trim($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText)); // todo 抵离交通
        foreach ($guestlist as $key => $vg) {
            $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName)
                                  ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童"))
                                  ->setCustomersDocumentType($key, "护照") // Passport No.
                                  ->setCustomersDocumentNo($key, $vg->BPE_Passport)
                                  ->setCustomersOtherInfo($key, $this->Orders_model->GetNationalityName($orderinfo[0]->GUT_NationalityID));
        }
        foreach ($scheduleDetails as $ks => $vs) {
            $this->tldOrderBuilder->setScheduleDetailsContent($ks, $vs->PAG2_Title)
                                  ->setScheduleDetailsTitle($ks, $vs->PAG2_Name)
                                  // ->set_scheduleDetails($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0))
                                  ->setScheduleDetailsBreakFirst($ks, 0 )
                                  ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0) )
                                  ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0));
        }
        foreach ($travelFees as $kf => $vf) { // todo 发生退款或多笔收款
            $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group")
                                  ->setTravelFeesMoney($kf, $vf->GAI_SQJE)
                                  ->setTravelFeesNum($kf, 1)
                                  ->setTravelFeesUnit($kf, bcdiv($vf->GAI_SSJE, $vf->GAI_SQJE))
                                  ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE)
                                  ->setTravelFeesRemark($kf, $vf->GAI_Memo);
        }
        var_dump(($this->tldOrderBuilder->getBizContent()));
        // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder);
        /** BIZ_GroupCombineInfo */
//         if (json_decode($resp)->status == 1) {
// log_message('error','in GCI ' . json_decode($resp)->responseData->orderId);
//             $this->Orders_model->GCI_COLI_SN       = $orderinfo[0]->COLI_SN;
//             $this->Orders_model->GCI_GRI_SN        = $orderinfo[0]->COLI_GRI_SN;
//             $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId;
//             $this->Orders_model->GCI_FromAgc       = "D目的地桂林组";
//             $this->Orders_model->biz_groupcombineinfo_save();
//         }
        // email 供应商 todo
        echo "Order Push done.";
        return;
    }

    /*!
     * 订单状态变更,调度变更
     * (地接社调用, 并邮件通知外联)
     */
    public function order_change()
    {
        $this->load->model('Order_update');
        $ret['status'] = -1;
        $ret['errMsg'] = "未知错误";
        $input = $this->input->post();
        $vendorID = $input['userId'];
        $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->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID);
            if (empty($vas_info) && ! empty($input['agcOrderNo'])) {
                $real_groupCode = analysis_groupCode($input['agcOrderNo']);
                $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID);
            }
        } elseif ($input['agcName'] == '桂林海纳国旅') {
            $real_groupCode = analysis_groupCode($input['agcOrderNo']);
            $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID);
        }

        if (empty($vas_info)) {
            $ret['errMsg'] = "未找到订单.";
        } else {
            $vendor_manager = $this->Orders_model->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->Orders_model->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));
    }

    public function refresh_operation($coli_sn=0)
    {
        $this->load->model('OrderFinance_model', 'combine_model');
        // return $this->insert_HT_order_operation($coli_sn);
        // echo "string";
        $data['combineNo_arr'] = $this->combine_model->get_order_combineNo($coli_sn);
        foreach ($data['combineNo_arr'] as $kcn => $vcn) {
            $data['combineNo_arr'][$kcn]->cost = $this->combine_model->get_combine_sumMoney($vcn->GCI_combineNo);
        }
        $this->load->view('operation',$data);
    }

    protected 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;
    }

    /*!
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    protected function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = "UTF-8";
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                // $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }

    public function pag_no_tmp($routeName='')
    {
        return array(
            "故宫深度一日游（目的地）" => "BJSIC-44"
            ,"故宫深度游拼团（目的地）" => "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-41"
            ,"西安精品两日游（目的地）" => "XASIC-42"
            ,"西安单租车服务（目的地）" => "XASIC-17"
            ,"西安单租车接送服务（目的地）" => "XASIC-17"
            ,"西安单租车接送服务" => "XASIC-17"
            ,"西安兵马俑精品一日游（目的地）" => "XASIC-41"
            ,"西安兵马俑精华一日游（目的地）" => "XASIC-41"
            ,"西安兵马俑精品半日游（目的地）" => "XASIC-15"
            ,"西安兵马俑精华半日游（目的地）" => "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;
    }

    public function call_do()
    {
        $this->Orders_model->test();
    }


}
