<?php

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

class Index extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // $this->output->enable_profiler(TRUE);
        $this->load->model('Paypal_model');
        $this->load->model('Note_model');
        $this->load->model('Group_model');
        bcscale(2);
    }

    public function index() {
        $this->note_list();
    }

    //收款记录列表
    public function index_old($date = 'all', $page = 1) {
        $this->permission->is_admin(true);
        $data = array();
        $data['current_m'] = $date == 'all' ? date('Ym') : date('Ym', strtotime($date));
        $data['current_d'] = $date == 'all' ? '' : date('Ymj', strtotime($date));
        $data['userdata'] = $this->session->userdata('admin_chtcdn');

        $date = $date == 'all' ? 'all' : date('Y-m-d', strtotime($date));
        $list = $this->Paypal_model->get_mail_list(30, '', $date);

        $pages['total'] = count($list); //数据总条数
        $pages['pageSize'] = 30; //每页展示数量
        $pages['url'] = site_url("apps/paypal/index/index/" . $date . '/'); //页码链接
        $pages['current'] = $page; //当前页码
        $data['pageinfo'] = show_page($pages);

        $mail_id_str = 0;


        $list = array_slice($list, $pages['pageSize'] * ($page - 1), $pages['pageSize']);
        foreach ($list as $v) {
            $mail_id_str.=',' . $v->M_SN;
        }
        //echo $mail_id_str;
        $data['list'] = array();
        !empty($list) && $data['list'] = $this->Paypal_model->get_mail_list(30, $mail_id_str);


        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    //收款邮件详情
    public function detail($mail_sn, $tpl = 0) {
        $this->permission->is_admin(true);
        $data = array();
        $mailinfo = $list = $this->Paypal_model->get_mail_list(30, $mail_sn);

        if (empty($mailinfo[0])) {

            //$url=site_url('apps/paypal/index/error_paypal');
            //echo '<b style="color:#000ccc;text-align:center;">无详细信息，三秒后跳转......</b>';
            //echo '<meta http-equiv="refresh"content="3; url='.$url.'"/>';
            //die();
        }
        $mailinfo = $mailinfo[0];

        $data['mail'] = $mailinfo;
        if ($tpl == 0) {
            $data['current_m'] = date('Ym', strtotime($mailinfo->M_AddTime));
            $data['current_d'] = date('Ymj', strtotime($mailinfo->M_AddTime));
            $data['detail_tpl'] = '1';
            $data['userdata'] = $this->session->userdata('admin_chtcdn');
            !empty($mailinfo->pm_orderid) && $data['orderinfo'] = $this->Paypal_model->get_order($mailinfo->pm_orderid, true);
            $this->load->view('n-header', $data);
            $this->load->view('index');
            $this->load->view('n-footer');
        } else {
            $this->load->view('detail', $data);
        }
    }

    //用于HT--交易详情
    public function detail_ht($pm_transaction_id) {
        $data = array();
        //先查询原来的数据
        $data['mailinfo'] = $list = $this->Paypal_model->get_paypal_msg($pm_transaction_id);
        if (!empty($data['mailinfo'])) {
            $data['mailinfo'] = $data['mailinfo'][0];
            $this->load->view('detail_ht', $data);
        } else {
            $data = $this->Note_model->note($pm_transaction_id);
            $this->load->view('mail_templete', $data);
        }
    }

    //收款记录搜索
    public function search() {
        $data = array();
        $data['current_m'] = date('Ym');
        $data['current_d'] = '';
        $data['userdata'] = $this->session->userdata('admin_chtcdn');

        $data['list'] = array();
        $mail_o_orderno = $this->input->post('search_key');
        $data['search_key'] = $mail_o_orderno;
        $data['list'] = $this->Paypal_model->get_search_mails($mail_o_orderno);

        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    //我的收款
    public function my_paypal() {
        $userdata = $this->session->userdata('admin_chtcdn');
        $data['current_m'] = date('Ym');
        $data['current_d'] = '';
        $data['userdata'] = $userdata;

        $data['list'] = array();
        if ($userdata != false && !empty($userdata['OPI_Email']) && !empty($userdata['OPI_FirstName'])) {
            $data['list'] = $this->Paypal_model->get_my_order($userdata['OPI_Email'], $userdata['OPI_FirstName'], $userdata['OPI_Name']);
        }
        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    //从paypal接口获取交易记录列表
    public function get_transactions_list() {
        //查询条件  最后一次更新的时间
        $last_paypal_msg = $this->Paypal_model->last_paypal_msg();
        //修改为，查询最后一个交易记录时间，根据原始文本中的时间来查询，而不是数据库入库时间

        $last_date = empty($last_paypal_msg) ? date('Y-m-d') . ' 00:00:00' : $last_paypal_msg[0]->pm_payment_date;
        $last_date = str_replace(' ', 'T', $last_date) . 'Z';

        $param['request'] = array(
            'TRANSACTIONCLASS' => 'ALL',
            'startdate' => $last_date
        );

        //访问接口，并对返回的数据转换格式
        $sandbox = '0';
        $base = $this->base($sandbox);
        $transactions = $this->get_transactions($base, $param); //获取历史交易记录
        $transactions = urldecode($transactions); //url格式

        $result_count = substr_count($transactions, 'L_TIMESTAMP'); //交易记录条数
        $list = array();
        $temparray = explode('&', $transactions);

        foreach ($temparray as $key => $value) {
            $temp_arr = explode('=', $value);
            if (isset($temp_arr[1])) {
                $list[$temp_arr[0]] = $temp_arr[1];
            }
        }

        //保存信息
        for ($i = 0; $i < $result_count; $i++) {
            //已经更新了的记录就不再保存,并停止处理剩下的数据
            $has_exit = $this->Paypal_model->get_paypal_msg($list['L_TRANSACTIONID' . $i]);
            if (!empty($has_exit)) {
                die('更新了' . $i . '/' . $result_count . '条记录');
            }
            //只保存已经支付完成，且交易类型是付款和退款的交易记录,因为其他类型的交易记录获取不到交易详情
            if ($list['L_STATUS' . $i] != 'Completed' || !in_array($list['L_TYPE' . $i], array('Payment', 'Refund'))) {
                continue;
            }
            //保存交易信息
            $pm_transaction_id = $list['L_TRANSACTIONID' . $i]; //交易号

            $pm_orderid = '';                            //订单号
            $pm_item_name = '';                          //交易备注说明
            $pm_money = $list['L_AMT' . $i];               //交易金额
            $pm_currency = $list['L_CURRENCYCODE' . $i];   //交易币种
            $pm_payer = $list['L_NAME' . $i];              //客人名字
            $pm_payer_email = '';                        //客人邮箱
            $pm_payer_status = '';                       //是否paypal已认证的客人
            $pm_memo = '';                               //交易详情json数据集
            $pm_pay_type = $list['L_TYPE' . $i];           //交易类型
            $pm_payment_date = $list['L_TIMESTAMP' . $i];  //交易时间
            $pm_payment_date = str_replace(array('T', 'Z'), array(' ', ''), $pm_payment_date);
            $insert_res = $this->Paypal_model->save_paypal_msg($pm_transaction_id, $pm_orderid, $pm_item_name, $pm_money, $pm_currency, $pm_payer, $pm_payer_email, $pm_payer_status, $pm_memo, $pm_payment_date, $pm_pay_type);
        }

        echo ('更新了' . ($result_count) . '条记录');
    }

    public function get_transactions_detail_by_paymentToken()
    {
        $token = $this->input->post("t");
        $base = $this->base(0);
        // $post = "METHOD=GetTransactionDetails&VERSION=100.0&TRANSACTIONID=$token";
        // $post = "METHOD=GetExpressCheckoutDetails&VERSION=124.0&TOKEN=$token";

        $token = str_replace(' ', 'T', $token) . 'Z';
        $post = "METHOD=TransactionSearch&VERSION=100.0&TRANSACTIONCLASS=ALL&STARTDATE=$token";

        $detail = $this->call($base, $post);
        var_dump($detail);
        return;
    }

    //根据交易号获取交易详细信息
    public function get_transactions_detail($redirect = 0) {
        //从数据库提取一条还没有更新交易详情的记录获取交易号
        $pay_data = $this->Paypal_model->get_paypal_msg();

        if (empty($pay_data)) {
            if ($redirect == 1) {
                //重定向
                redirect(site_url('apps/paypal'));
            }
            die('暂无更新');
        }
        $pay_data = $pay_data[0];
        $transactionsID = $pay_data->pm_transaction_id;

        //接口信息拼接
        $sandbox = '0';
        $base = $this->base($sandbox);
        $post = "METHOD=GetTransactionDetails&VERSION=100.0&TRANSACTIONID=$transactionsID";
        $detail = $this->call($base, $post);

        //格式化接口返回数据
        $detail = urldecode($detail);
        $detail_list = array();
        $temparray = explode('&', $detail);
        foreach ($temparray as $key => $value) {
            $temp_arr = explode('=', $value);
            if (isset($temp_arr[1])) {
                $detail_list[$temp_arr[0]] = $temp_arr[1];
            }
        }

        //请求数据状态是成功且支付状态是完成的，更新交易记录信息
        if (isset($detail_list['ACK']) && isset($detail_list['PAYMENTSTATUS']) && $detail_list['ACK'] == 'Success' && $detail_list['PAYMENTSTATUS'] == 'Completed') {
            $pm_sn = $pay_data->pm_sn;

            //$pm_orderid=(isset($detail_list['INVNUM']) && !empty($detail_list['INVNUM']))?$detail_list['INVNUM']:isset($detail_list['CUSTOM'])?$detail_list['CUSTOM']:isset($detail_list['L_NAME0'])?$detail_list['L_NAME0']:'';
            //ycc 修改了获取订单号的优先级和优化逻辑判断，INVNUM>L_NUMBER0>CUSTOM>L_NAME0
            $pm_orderid = '';
            if (isset($detail_list['INVNUM']) && !empty($detail_list['INVNUM'])) {
                $pm_orderid = $detail_list['INVNUM'];
            } else {
                if (isset($detail_list['L_NUMBER0']) && !empty($detail_list['L_NUMBER0'])) {
                    $pm_orderid = $detail_list['L_NUMBER0'];
                } else {
                    if (isset($detail_list['CUSTOM']) && !empty($detail_list['CUSTOM'])) {
                        $pm_orderid = $detail_list['CUSTOM'];
                    } else {
                        if (isset($detail_list['L_NAME0']) && !empty($detail_list['L_NAME0'])) {
                            $pm_orderid = $detail_list['L_NAME0'];
                        }
                    }
                }
            }


            $pm_item_name = $pm_orderid;
            $orderinfo = $pm_orderid;
            if (strpos($orderinfo, 'Tracking Code:') !== false) {
                $orderinfo = explode('Tracking Code:', $orderinfo);
                $orderinfo = explode('Travel Advisor', $orderinfo[1]);
                $orderinfo = trim($orderinfo[0]);
            }
            //订单号过滤

            $orderinfo = explode('--', $orderinfo);
            $orderinfo = $orderinfo[0];
            $orderinfo = explode('_', $orderinfo);
            //$orderinfo=$orderinfo[0]; ycc：移到下面去了，在这里赋值的话后面用$orderinfo[1]是不存在的 --2016.02.19

            $ordertype = 'N';
            if (isset($orderinfo[1])) {
                $ordertype_temp = trim($orderinfo[1]);
                if (substr($ordertype_temp, 0, 1) == 'T') {
                    $ordertype = 'T';
                } elseif (substr($ordertype_temp, 0, 1) == 'B') {
                    $ordertype = 'B';
                }
            }
            $orderinfo = $orderinfo[0];
            $orderinfo = explode(',', $orderinfo);
            $orderid = trim($orderinfo[0]);
            $temp_orderid = explode('-', $orderid);
            if (isset($temp_orderid[1])) {
                $orderid = trim($temp_orderid[1]);
            }
            $tempid = explode(' ', $orderid);
            $pm_orderid = $tempid[0]; //订单号


            $pm_payer_email = $detail_list['EMAIL'];         //客人邮箱
            $pm_payer_status = $detail_list['PAYERSTATUS'];  //客人认证状态
            $pm_memo = json_encode($detail_list);            //序列化数据
            $this->Paypal_model->update_paypal_msg($pm_sn, $pm_orderid, $pm_item_name, $pm_payer_email, $pm_payer_status, $pm_memo);

            //查找外联信息
            $M_State = 0;
            if (!empty($pm_orderid)) {
                $pm_invoice = $pm_orderid;
                $advisor_info = $this->Paypal_model->get_order($pm_orderid, false, $ordertype);
                $OPI_Email = isset($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : '';
                $OPI_FirstName = isset($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : isset($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : '';

                //有订单号，但是匹配不到外联（带收款进来的新订单）
                if (empty($OPI_Email) && empty($OPI_FirstName)) {
                    $M_State = 2;
                }
                //匹配到了外联，但是外联没有邮箱
                elseif (empty($OPI_Email) && !empty($OPI_FirstName)) {
                    $M_State = 3;
                }
            }
            //没有订单号，转发给陆燕
            else {
                $OPI_Email = 'lussie@chinahighlights.net';
                $OPI_FirstName = 'Lussie';
            }

            //给外联发送通知邮件
            $fromName = $pay_data->pm_payer;
            $fromEmail = $detail_list['EMAIL'];
            $toName = $OPI_FirstName;
            $toEmail = $OPI_Email;
            $subject = '来自' . $pay_data->pm_payer . '的付款';
            if (!empty($pm_orderid))
                $subject = $pm_orderid . ' / ' . $pay_data->pm_money . $pay_data->pm_currency . ' / ' . $pay_data->pm_payer;

            $data['mailinfo'] = $pay_data;
            $data['mailinfo']->INSURANCEOPTIONSELECTED = isset($detail_list['INSURANCEOPTIONSELECTED']) ? $detail_list['INSURANCEOPTIONSELECTED'] : '';
            $data['mailinfo']->SUBJECT = isset($detail_list['SUBJECT']) ? $detail_list['SUBJECT'] : '';
            $data['mailinfo']->NOTE = isset($detail_list['NOTE']) ? $detail_list['NOTE'] : '';
            $data['mailinfo']->pm_payer_email = $detail_list['EMAIL'];
            $data['mailinfo']->pm_item_name = $pm_item_name;
            $data['mailinfo']->pm_memo = $pm_memo;
            $data['mailinfo']->pm_payer_status = $pm_payer_status;

            $body = $this->load->view('mail_tpl', $data, true);
            $M_RelatedInfo = $pm_sn;
            $M_AddTime = $pay_data->pm_payment_date;
            $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime);

            if (!empty($pm_orderid)) {
                //更新还没有填的客邮和交易号de收款记录（商务订单）
                if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) {
                    $ht_memo = '交易号(自动录入):' . $transactionsID;
                    $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
                    $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $pay_data->pm_money, $pay_data->pm_payment_date, mb_strtoupper($pay_data->pm_currency), $pay_data->pm_payment_date, $pay_data->pm_payment_date, $pay_data->pm_payment_date, '', $detail_list['EMAIL'], $transactionsID, $ht_memo);
                }
                //更新还没有填的客邮和交易号de收款记录（传统订单）
                elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) {
                    //
                }
            }
        }

        if ($redirect == 1) {
            //redirect(site_url('apps/paypal'));
        }
        echo $transactionsID . '更新成功';
    }

    //定时执行：重新设置新订单邮件的外联信息
    public function set_owner() {
        //新订单，无外联,每次更新最新的10条
        $mail_info2 = $this->Paypal_model->get_unsend_list(10, 2);
        if (!empty($mail_info2)) {
            foreach ($mail_info2 as $key => $mail_info) {
                $orderinfo = $mail_info->pm_item_name;
                if (strpos($orderinfo, 'Tracking Code:') !== false) {
                    $orderinfo = explode('Tracking Code:', $orderinfo);
                    $orderinfo = explode('Travel Advisor', $orderinfo[1]);
                    $orderinfo = trim($orderinfo[0]);
                }
                $orderinfo = explode('--', $orderinfo);
                $orderinfo = $orderinfo[0];
                $orderinfo = explode('_', $orderinfo);
                $ordertype = 'N';
                if (isset($orderinfo[1])) {
                    $ordertype_temp = trim($orderinfo[1]);
                    if (substr($ordertype_temp, 0, 1) == 'T') {
                        $ordertype = 'T';
                    } elseif (substr($ordertype_temp, 0, 1) == 'B') {
                        $ordertype = 'B';
                    }
                }
                $advisor_info = $this->Paypal_model->get_order($mail_info->pm_orderid, false, $ordertype);
                $OPI_Email = isset($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : '';
                $OPI_FirstName = isset($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : isset($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : '';
                //设置外联邮箱，并把邮件设置为未发送
                if (!empty($OPI_Email)) {
                    $send_state = 0;
                    $this->Paypal_model->update_mail($mail_info->M_SN, $OPI_Email, $OPI_FirstName, $send_state);
                    echo '新订单外联信息有更新<br>';
                }
            }
        } else {
            echo '暂无“没有设置外联”的新订单<br>';
        }

        //外联无邮箱,每次更新最新的10条
        $mail_info3 = $this->Paypal_model->get_unsend_list(10, 3);
        if (!empty($mail_info3)) {
            foreach ($mail_info3 as $key => $mail_info) {

                $orderinfo = $mail_info->pm_item_name;
                if (strpos($orderinfo, 'Tracking Code:') !== false) {
                    $orderinfo = explode('Tracking Code:', $orderinfo);
                    $orderinfo = explode('Travel Advisor', $orderinfo[1]);
                    $orderinfo = trim($orderinfo[0]);
                }
                $orderinfo = explode('--', $orderinfo);
                $orderinfo = $orderinfo[0];
                $orderinfo = explode('_', $orderinfo);
                $ordertype = 'N';
                if (isset($orderinfo[1])) {
                    $ordertype_temp = trim($orderinfo[1]);
                    if (substr($ordertype_temp, 0, 1) == 'T') {
                        $ordertype = 'T';
                    } elseif (substr($ordertype_temp, 0, 1) == 'B') {
                        $ordertype = 'B';
                    }
                }

                $advisor_info = $this->Paypal_model->get_order($mail_info->pm_orderid, false, $ordertype);
                $OPI_Email = isset($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : '';
                $OPI_FirstName = isset($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : isset($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : '';
                //设置外联邮箱，并把邮件设置为未发送
                if (!empty($OPI_Email)) {
                    $send_state = 0;
                    $this->Paypal_model->update_mail($mail_info->M_SN, $OPI_Email, $OPI_FirstName, $send_state);
                    echo '外联没有邮箱的邮件信息有更新<br>';
                } else {
                    echo $OPI_FirstName . '没有外联邮箱<br>';
                }
            }
        } else {
            echo '暂无外联没有邮箱<br>';
        }
        echo 'ok<br>';
    }

    //设置授权
    public function base($sandbox) {

        if ($sandbox == '1') {
            $base = array(
                'url' => 'https://api-3t.sandbox.paypal.com/nvp',
                'username' => 'pays_api1.chinahighlights.com',
                'password' => 'HWJ7BFSZBZUETZ4K',
                'signature' => 'AxfjDmuPaaxMccY-8ZHIWGDHQKxOAyYzBPToLDzU-cgnldnh6eZGKJMn'
            );
        }

        if ($sandbox == '0') {
            $base = array(
                'url' => 'https://api-3t.paypal.com/nvp',
                'username' => 'pays_api1.chinahighlights.com',
                'password' => 'HWJ7BFSZBZUETZ4K',
                'signature' => 'AxfjDmuPaaxMccY-8ZHIWGDHQKxOAyYzBPToLDzU-cgnldnh6eZGKJMn'
            );
        }

        return $base;
    }

    //获取交易历史记录列表
    public function get_transactions($base, $param) {
        $post = 'METHOD=TransactionSearch&';
        $post .= 'VERSION=100.0';

        foreach ($param['request'] as $key => $value) {
            $post .= '&' . strtoupper($key) . '=' . $value;
        }

        $transactions = $this->call($base, $post);
        return $transactions;
    }

    //请求接口
    public function call($base, $post) {
        $post .= '&PWD=' . $base['password'];
        $post .= '&USER=' . $base['username'];
        $post .= '&SIGNATURE=' . $base['signature'];
        //print_r($post);
        // print_r($base);
        //die();
        //启动服务器代理
        $ch = curl_init($base['url']); //初始化URL
        curl_setopt($ch, CURLOPT_PORT, 443);
        curl_setopt($ch, CURLOPT_HEADER, 0); //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); //在完成交互以后强迫断开连接，不能重用
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); //强制获取一个新的连接，替代缓存中的连接。
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);   //数据全部通过post发送，Content-Type头将会被设置成multipart/form-data
        $response = curl_exec($ch);


        if (empty($response)) {
            return 'No response received.';
        } else {
            return $response;
        }
        curl_close($ch);
    }

    //错误信息
    public function error_paypal($page = 1) {
        $userdata = $this->session->userdata('admin_chtcdn');

        $data['current_m'] = date('Ym');
        $data['current_d'] = '';
        $data['userdata'] = $userdata;

        //获取最近三个月的数据
        $lastinfo = $this->Paypal_model->last_paypal_msg();
        $lastdate = $lastinfo[0]->pm_create_date;
        $lastdate = substr($lastdate, 0, 10);


        $data['list'] = array();
        $data['list'] = $this->Paypal_model->get_all_error_order(0, $lastdate);
        $data['error'] = 1;

        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    //订单不匹配处理
    public function unmatch($type) {
        $userdata = $this->session->userdata('admin_chtcdn');

        $data['current_m'] = date('Ym');
        $data['current_d'] = '';
        $data['userdata'] = $userdata;

        $data['list2'] = array();

        //获取最近三个月的数据
        $lastinfo = $this->Paypal_model->last_paypal_msg();
        $lastdate = $lastinfo[0]->pm_create_date;
        $lastdate = substr($lastdate, 0, 10);




        if (isset($type)) {
            $data['list2'] = $this->Paypal_model->get_unmatch_list($type, $lastdate);
        } else {
            redirect(site_url('apps/paypal'));
            die();
        }


        $data['fg'] = 1; //@fg为订单不匹配时显示的标志
        $this->load->view('n-header', $data);
        $this->load->view('index');
        $this->load->view('n-footer');
    }

    /**
     * IPN
     * 存储paypal发送的消息
     */
    public function paypal_note() {
        $pn_txn_id = $this->input->post('txn_id');
        log_message('error','paypal-note: ' . $pn_txn_id);

        $pn_invoice = $this->input->post('invoice');
        empty($pn_invoice) ? $pn_invoice = $this->input->post('transaction_subject') : false;
        empty($pn_invoice) ? $pn_invoice = '' : false;

        $pn_custom = $this->input->post('custom');
        empty($pn_custom) ? $pn_custom = '' : false;

        $pn_mc_gross = $this->input->post('mc_gross');

        $pn_item_name = $this->input->post('item_name');
        if (empty($pn_item_name)) {
            $pn_item_name = $this->input->post('item_name1'); //APP用SDK支付的话会是item_name1
            empty($pn_item_name) ? $pn_item_name = '' : false;
        }

        $pn_item_number = $this->input->post('item_number');
        if (empty($pn_item_number)) {
            $pn_item_number = $this->input->post('item_number1'); //APP用SDK支付的话会是item_number1
            empty($pn_item_number) ? $pn_item_number = '' : false;
        }

        $pn_mc_currency = $this->input->post('mc_currency');
        $pn_payment_status = $this->input->post('payment_status');
        $pn_payment_date = $this->input->post('payment_date');
        $pn_payer = $this->input->post('first_name') . ' ' . $this->input->post('last_name');
        $pn_payer_email = $this->input->post('payer_email');
        $pn_memo = json_encode($_POST);
        if (!empty($pn_txn_id)) {
            //把PDT时间转成GMT时间
            $pn_payment_date = gmdate('Y-m-d H:i:s', strtotime($pn_payment_date));
            $this->Note_model->save_paypal_note($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo);
            log_message('error','paypal-note-succeed ' . $pn_txn_id . ' # ' . $pn_invoice);
            // echo 'ok';
        } else {
            // echo 'no';
        }
        return ;
    }

    /*!
     * [paypal_webhook description]
     * @author LYT <lyt@hainatravel.com>
     * @date   2019-05-23
     * PAYMENT.SALE.COMPLETED 没有付款人信息
     * * resource.id=txn_id
     * * invoice_number=invoice_number
     */
    public function paypal_webhook()
    {
        $raw_post = file_get_contents('php://input');
        if (empty($raw_post)) {
            return;
        }
        $post_data = json_decode($raw_post);
        if ($post_data->event_type != 'PAYMENT.SALE.COMPLETED' && $post_data->event_type != 'PAYMENT.SALE.REFUNDED') {
            log_message('error',"paypal_webhook" . var_export($raw_post, 1));
            return;
        }
        $pn_txn_id = $post_data->resource->id;

        $pn_invoice = $post_data->resource->invoice_number;

        $pn_mc_gross = $post_data->resource->amount->total;

        // $pn_item_name = $this->input->post('item_name');
        // if (empty($pn_item_name)) {
        //     $pn_item_name = $this->input->post('item_name1'); //APP用SDK支付的话会是item_name1
        //     empty($pn_item_name) ? $pn_item_name = '' : false;
        // }

        // $pn_item_number = $this->input->post('item_number');
        // if (empty($pn_item_number)) {
        //     $pn_item_number = $this->input->post('item_number1'); //APP用SDK支付的话会是item_number1
        //     empty($pn_item_number) ? $pn_item_number = '' : false;
        // }

        $pn_mc_currency = $post_data->resource->amount->currency;
        $pn_payment_status = $post_data->resource->state;
        if ($post_data->event_type == 'PAYMENT.SALE.REFUNDED') {
            $pn_payment_status = 'Refunded';
            $pn_mc_gross = '-' . $post_data->resource->amount->total;
            $post_data->parent_txn_id = $post_data->resource->sale_id;
        }
        $pn_payment_date = $post_data->resource->update_time;
        // $pn_payer = $post_data->resource->amount->currency;
        // $pn_payer_email = $post_data->resource->amount->currency;
        $pn_memo = json_encode($post_data); // $raw_post;
        if (!empty($pn_txn_id)) {
            //把PDT时间转成GMT时间
            $pn_payment_date = gmdate('Y-m-d H:i:s', strtotime($pn_payment_date));
            $this->Note_model->save_paypal_note(
                $pn_txn_id,
                $pn_invoice,
                "",
                $pn_mc_gross,
                "",
                "",
                $pn_mc_currency,
                $pn_payment_status,
                "",
                "",
                $pn_payment_date,
                $pn_memo);
            log_message('error','paypal-webhook-succeed ' . $pn_txn_id . ' # ' . $pn_invoice);
            // echo 'ok';
        } else {
            // echo 'no';
        }
        return;
    }

    //解析出订单号
    public function analysis_orderid($note_invoice_string) {
        $data = array();

        //空字符串或者小于8位都属于不正确的订单号
        if (empty($note_invoice_string) || strlen($note_invoice_string) < 8) {
            return false;
        }

        //APP订单处理，如标题China Train Booking-160617462
        if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) {
            $note_invoice_string = explode('-', $note_invoice_string);
            if (isset($note_invoice_string[1]) && $note_invoice_string[1] !== "ChinaTrainBooking") {
                $note_invoice_string = trim($note_invoice_string[1]);
            } elseif (isset($note_invoice_string[0]) && $note_invoice_string[0] !== "China Train Booking") {
                $note_invoice_string = trim($note_invoice_string[0]);
            }
            return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A')); //APP订单，不需要处理交易记录和通知
        }

        //订单号例子 160420021_B--9608
        //Tracking code:2016-05-06-JJ160319027 /Travel advisor:Fiona Jiang /Content:Shanghai, Beijing, Pingyao, Xian, Guilin, Yangshuo, S

        if (strpos($note_invoice_string, 'Tracking Code:') !== false) {
            $note_invoice_string = explode('Tracking Code:', $note_invoice_string);
            $note_invoice_string = explode('Travel Advisor', $note_invoice_string[1]);
            $note_invoice_string = trim($note_invoice_string[0]);
        }

        //订单号过滤
        $note_invoice_string = explode('--', $note_invoice_string);
        $note_invoice_string = $note_invoice_string[0];
        $note_invoice_string = explode('_', $note_invoice_string);

        //订单类型识别
        $ordertype = 'N';
        if (isset($note_invoice_string[1])) {
            $ordertype_temp = trim($note_invoice_string[1]);
            if (substr($ordertype_temp, 0, 2) == 'TP') {
                $ordertype = 'TP';
            } elseif (substr($ordertype_temp, 0, 1) == 'T') {
                $ordertype = 'T';
            } elseif (substr($ordertype_temp, 0, 1) == 'B') {
                $ordertype = 'B';
            } elseif (substr($ordertype_temp, 0, 1) == 'A') {
                $ordertype = 'B';
            }
        }
        // 2018.05.28 for Trippest, tourMaster的订单号是01开头
        if (substr($note_invoice_string[0], 0, 2) == '01') {
            $ordertype = 'TP';
        }

        //手机订单、机票订单都没有加标示，在这里帮加上，暂时的，今后还是要在网前设置好
        if ($ordertype == 'N' && isset($note_invoice_string[0])) {
            $orderid_temp = $note_invoice_string[0];
            if (strlen($orderid_temp) == 9 && substr($orderid_temp, 0, 2) == '16') {
                $ordertype = 'B';
            }
        }

        //前台预付款订单，以45开头，如45117640类型的订单号，这个类型的订单会分配到某个新订单去，需要查找COLI_AddCode来找新订单号，然后再发送通知

        if ($ordertype == 'N' && isset($note_invoice_string[0])) {
            $orderid_temp = $note_invoice_string[0];
            if (strlen($orderid_temp) == 8 && substr($orderid_temp, 0, 2) == '45') {
                $ordertype = 'M';
            }
        }
        //新的订单号14733661876255
        if ($ordertype == 'N' && isset($note_invoice_string[0])) {
            $orderid_temp = $note_invoice_string[0];
            if (strlen($orderid_temp) == 14 && substr($orderid_temp, 0, 2) == '14') {
                $ordertype = 'M';
            }
        }

        if ($ordertype == 'N') {
            return false; //没有编号的订单直接显示错误，由人工分配
        }

        $note_invoice_string = $note_invoice_string[0];
        $note_invoice_string = explode(',', $note_invoice_string);
        $orderid = trim($note_invoice_string[0]);
        $temp_orderid = explode('-', $orderid);
        if (isset($temp_orderid[1])) {
            $orderid = trim($temp_orderid[1]);
        }
        $tempid = explode(' ', $orderid);
        $pm_orderid = $tempid[0]; //订单号

        if (empty($pm_orderid) || strlen($pm_orderid) < 8) {
            return false;
        }
        return json_encode(array('orderid' => $pm_orderid, 'ordertype' => $ordertype));
    }

    /*
      业务处理流程：
      1. paypal_note函数是用来接收paypal提交过来的数据，每一笔交易记录都会自动post过来
      2. 用定时程序访问send_note函数，查询未发送和发送错误的记录（paypal_note函数存储的记录）
      3. analysis_orderid函数分析记录中的订单号，识别传统订单、商务订单等
      4. Paypal_model->get_order根据订单号和类型找到对应外联信息，构造邮件发送给外联
      5. 添加付款记录到订单信息中
     */

    //找到没有发送的记录
    public function send_note($pn_txn_id = false, $old_ssje=NULL, $pn_sn=NULL) {
        $data = array();
        $handpick = empty($pn_txn_id) ? false : TRUE;

        //优先处理指定的交易号，用于修正交易号直接发送通知
        if (!empty($pn_txn_id)) {
            $data['unsend_list'] = array($this->Note_model->note($pn_txn_id, $pn_sn));
        }

        //找到处理过的的记录
        if (empty($data['unsend_list'])) {
            $data['unsend_list'] = $this->Note_model->unsend(10);
        }

        // 处理失败 并 Completed
        if (empty($data['unsend_list'])) {
            $data['unsend_list'] = $this->Note_model->failnotec(20);
        }

        //没有未处理的数据再查找处理失败的数据
        if (empty($data['unsend_list'])) {
            $data['unsend_list'] = $this->Note_model->failnote(20);
        }

        $show_index = 0;
        foreach ($data['unsend_list'] as $item) {

            //已经发送的不处理，防止重复发送
            if ($item->pn_send == 'send' && empty($pn_txn_id)) {
                continue;
            }

            //显示处理记录
            if (empty($pn_txn_id)) {
                echo ++$show_index . ' ' . $item->pn_txn_id . '<br/>';
            }

            // webhook的跳过
            $webhook_memo = json_decode($item->pn_memo);
            $is_webhook = false;
            if (isset($webhook_memo->id) && substr($webhook_memo->id, 0, 2)==="WH") {
                $is_webhook = true;
            }
            if (empty($pn_txn_id) && true === $is_webhook) {
                $this->Note_model->update_send($item->pn_txn_id, 'send-wh', $item->pn_sn);
                continue;
            }

            //退款状态默认为已经处理，陆燕在退款前手动通知外联了，系统跳过处理
            if (strtolower($item->pn_payment_status) == 'refunded' ) {
                $this->send_refund($item, $handpick, $old_ssje);
                // $this->Note_model->update_send($item->pn_txn_id, 'send');
                continue;
            }
            // 撤销付款:允许手动处理
            if (strtolower($item->pn_payment_status) == 'reversed' && $handpick===true ) {
                $this->send_refund($item, $handpick, $old_ssje);
                continue;
            }

            //只处理完成状态，其他状态由陆燕处理
            if (strtolower($item->pn_payment_status) !== 'completed') {
                $this->Note_model->update_send($item->pn_txn_id, 'sendfail', $item->pn_sn);
                continue;
            }

            // 状态=已完成 退款行为:撤销付款/拒付等
            if (floatval($item->pn_mc_gross) < 0) {
                $this->send_refund($item, $handpick, $old_ssje);
                continue;
            }

            //根据note信息找到订单号
            $get_order_no = $item->pn_invoice;
            $orderid_info = $this->analysis_orderid($item->pn_invoice);
            if (empty($orderid_info)) {
                $get_order_no = $item->pn_custom;
                $orderid_info = $this->analysis_orderid($item->pn_custom);
            }
            if (empty($orderid_info)) {
                $get_order_no = $item->pn_item_name;
                $orderid_info = $this->analysis_orderid($item->pn_item_name);
            }
            if (empty($orderid_info)) {
                $get_order_no = $item->pn_item_number;
                $orderid_info = $this->analysis_orderid($item->pn_item_number);
            }

            //找不到订单号，设置为发送失败标示
            if (empty($orderid_info)) {
                $this->Note_model->update_send($item->pn_txn_id, 'sendfail', $item->pn_sn);
                continue;
            }
            $orderid_info = json_decode($orderid_info);
            // 仅自动程序发送提醒 && false == $handpick &&
            if (strtolower($item->pn_payment_status) === 'completed'
                && $orderid_info->ordertype == 'A'
            ) {
                // APP 组的China Train Booking-开头的订单号
                // 发送邮件提醒外联核对收款金额, 不写入收款记录
                $if_empty_gai = $this->process_notify_APP($item, $orderid_info);
                $send = $if_empty_gai !== true ? 'send-app' : 'sendfail';
                $this->Note_model->update_send($item->pn_txn_id, $send, $item->pn_sn);
                continue;
            }

            //检测是否是APP订单,默认不处理
            // && $item->pn_payment_status !== 'Refunded'
            // if (
            //         ( (strpos($item->pn_memo, 'China Train Booking') !== false)
            //             || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false)
            //         )
            //     && empty($pn_txn_id)
            // ) { //APP自动出票的订单不需要处理
            //     $this->Note_model->update_send($item->pn_txn_id, 'send');
            //     continue;
            // }

            //根据订单号查找外联信息
            $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick);

            //根据订单号查找外联信息, 从临时表
            $advisor_info_from_tmp = $this->Paypal_model->get_order($orderid_info->orderid, false, 'M', $handpick);
            /**
             * 传统订单, 网站支付
             * @author LYT
             */
            if (empty($advisor_info) && ! empty($advisor_info_from_tmp) && $orderid_info->ordertype == 'T') {
                // $this->Note_model->update_send($item->pn_txn_id, 'closeRecord', $item->pn_sn);
                $this->Note_model->set_invoice($item->pn_txn_id, $advisor_info_from_tmp->COLI_ID . '_' . $orderid_info->ordertype);
                continue;
            }

            // for trippest tourMaster 2018.05.28
            if ($orderid_info->ordertype == 'TP') {
                $this->trippest_note($orderid_info, $item);
                continue;
            }

            //查不到订单信息
            if (empty($advisor_info)) {
                $this->Note_model->update_send($item->pn_txn_id, 'sendfail', $item->pn_sn);
                continue;
            }

            //更新正确的订单信息到记录中，以这个为主
            $this->Note_model->set_invoice($item->pn_txn_id, $orderid_info->orderid . '_' . $orderid_info->ordertype);

			//检测是否是APP订单,默认不处理
            // if ($orderid_info->ordertype == 'A' ) { //APP自动出票的订单不需要处理
            //     $this->Note_model->update_send($item->pn_txn_id, 'send');
            //     continue;
            // }

            //添加支付信息入库
            //没有分配订单之前先添加付款记录,这个过程可能会执行多次，必须在添加记录前查找是否有数据
            if (!empty($orderid_info)) {
                $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency));
                $ssje = $old_ssje===NULL ? $ssje : $old_ssje;
                $USD_amount = $this->Paypal_model->get_USD($item->pn_mc_gross, $item->pn_mc_currency);
                $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
                $this->Group_model->update_ck_group_info($GAI_COLI_SN);
                //更新还没有填的客邮和交易号de收款记录（商务订单）
                if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) {
                    $ht_memo = '交易号(自动录入):' . $item->pn_txn_id;
                    //CHTAPP订单添加记录前判断是否有记录，以前的APP版本没有交易号，只能拿金额来判断
                    if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") !== '-biz') {//只判断前6位字符，CHTAPP-fr CHTAPP-jp等各语种都属于APP订单
                        $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo);
                        if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态，并且订单进度是我的订单
                            $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款
                            $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'BS8');
                        }
                    } else {
                        // 把订单状态设置为13-新订单已支付
                        if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) {
                            $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13);
                            $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'BS13');
                        }
                        $this->Paypal_model->add_account_info(
                            $GAI_COLI_SN,
                            $advisor_info->COLI_ID,
                            $item->pn_mc_gross,
                            $item->pn_payment_date,
                            mb_strtoupper($item->pn_mc_currency),
                            $USD_amount,
                            $ssje,
                            $item->pn_payment_date,
                            $item->pn_payment_date,
                            $item->pn_payment_date,
                            $item->pn_payer,
                            $item->pn_payer_email,
                            $item->pn_txn_id,
                            $ht_memo);
                        // 更新订单主表付款方式,防止没访问thankyou-train.asp
                        $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010');
                    }
                }
                //更新还没有填的客邮和交易号de收款记录（传统订单）
                elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) {
                    $ht_memo = '交易号(自动录入):' . $item->pn_txn_id;
                    $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
                    $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo);
                    //添加汉特的订单提醒
                    $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross);
                    // 添加HT任务
                    $this->Paypal_model->exec_addToTask($gai_sn);
                }
            }


            $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net
            $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie
            if ($opi_email===''
                && in_array(strtoupper($advisor_info->COLI_WebCode), array('CHTAPP-JA', 'JP'))
            ) {
                $opi_email = 'contact@arachina.com';
                $opi_firstname = 'contact@arachina.com';
            }
            //没有外联信息表示订单未分配
            if (empty($opi_email) || empty($opi_firstname)) {
                $this->Note_model->update_send($item->pn_txn_id, 'sendfail', $item->pn_sn);
                continue;
            }

            //添加邮件发送记录
            if ( ($item->pn_send !== 'send' && false===$is_webhook ) || true===$handpick) {
                //给外联发送通知邮件
                $fromName = !empty($item->pn_payer) ? $item->pn_payer : '';
                $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : '';
                $toName = !empty($opi_firstname) ? $opi_firstname : '';
                $toEmail = !empty($opi_email) ? $opi_email : '';
                $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName;
                $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo;
                $M_RelatedInfo = $item->pn_sn;
                $M_AddTime = $item->pn_payment_date;
                $M_State = 0;
                $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note');
                //添加邮件发送记录 end

                $this->Note_model->update_send($item->pn_txn_id, 'send', $item->pn_sn);
                $this->Note_model->update_pending_send($item->pn_txn_id, 'send');
            } else {
                $this->Note_model->update_send($item->pn_txn_id, 'send', $item->pn_sn);
                $this->Note_model->update_pending_send($item->pn_txn_id, 'send');
            }
        }
        //echo 'done!';
    }

    /*!
     * 退款处理
     * @date   2019-05-05
     */
    public function send_refund($item, $handpick, $old_ssje=NULL)
    {
        // 找到原始收款交易的订单
        $parent_txn_id = json_decode($item->pn_memo)->parent_txn_id;
        $parent_note = $this->Note_model->note($parent_txn_id);
        if (empty($parent_note)) {
            $this->Note_model->update_send($item->pn_txn_id, 'sendfail');
            return false;
        }
        //订单号
        $orderid_info = $this->analysis_orderid($parent_note->pn_invoice);

        //找不到订单号，设置为发送失败标示
        if (empty($orderid_info)) {
            $this->Note_model->update_send($item->pn_txn_id, 'sendfail');
            return false;
        }
        $orderid_info = json_decode($orderid_info);

        if (in_array($orderid_info->ordertype, array('TP', 'A')) ) {
            $orderid_info->ordertype = 'B';
        }

        //根据订单号查找外联信息
        $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick);

        //根据订单号查找外联信息, 从临时表
        $advisor_info_from_tmp = $this->Paypal_model->get_order($orderid_info->orderid, false, 'M', $handpick);
        /**
         * 传统订单, 网站支付
         * @author LYT
         */
        if (empty($advisor_info) && ! empty($advisor_info_from_tmp) && $orderid_info->ordertype == 'T') {
            // $this->Note_model->update_send($item->pn_txn_id, 'closeRecord', $item->pn_sn);
            $this->Note_model->set_invoice($item->pn_txn_id, $advisor_info_from_tmp->COLI_ID . '_' . $orderid_info->ordertype);
            continue;
        }

        //查不到订单信息
        if (empty($advisor_info)) {
            $this->Note_model->update_send($item->pn_txn_id, 'sendfail');
            return false;
        }

        //更新正确的订单信息到记录中，以这个为主
        $this->Note_model->set_invoice($item->pn_txn_id, $orderid_info->orderid . '_' . $orderid_info->ordertype);

        //添加支付信息入库
        //没有分配订单之前先添加付款记录,这个过程可能会执行多次，必须在添加记录前查找是否有数据
        if (!empty($orderid_info)) {
            $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency));
            $ssje = $old_ssje===NULL ? $ssje : $old_ssje;
            $USD_amount = $this->Paypal_model->get_USD($item->pn_mc_gross, $item->pn_mc_currency);
            //更新还没有填的客邮和交易号de收款记录（商务订单）
            if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) {
                $ht_memo = '(自动录入)退款号:' . $item->pn_txn_id . "\n. ";
                $ht_memo .= '原收款号:' . $parent_txn_id;
                $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
                //CHTAPP订单添加记录前判断是否有记录，以前的APP版本没有交易号，只能拿金额来判断
                if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP'  && strstr($advisor_info->COLI_WebCode, "-") != '-biz') {//只判断前6位字符，CHTAPP-fr CHTAPP-jp等各语种都属于APP订单
                    $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo);
                        $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded');
                } else {
                    if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) {
                        $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded');
                    }
                    $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $USD_amount, $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo);
                }
            }
            //更新还没有填的客邮和交易号的收款记录（传统订单）
            elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) {
                $ht_memo = '(自动)退款号:' . $item->pn_txn_id . "\n. ";
                $ht_memo .= '原交易号:' . $parent_txn_id;
                $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0;
                $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo);
                //添加汉特的订单提醒
                $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已退款 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross);
            }
        }


        $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net
        $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie

        //没有外联信息表示订单未分配
        if (empty($opi_email) || empty($opi_firstname)) {
            $this->Note_model->update_send($item->pn_txn_id, 'sendfail');
            return false;
        }

        //添加邮件发送记录
        if ($item->pn_send !== 'send' && substr($item->pn_send, 0, 5) !== 'send-') {
            // 客人邮件中的外联落款
            // $web_code = 'cht'; // 默认cht
            $web_lgc = 1;
            $web_code = strtolower($advisor_info->COLI_WebCode);
            $site_info = $this->config->item('site');
            if (isset($site_info[$web_code])) {
                $site_info = $site_info[$web_code];
                $item->site = $site_info['site_url'];
                $web_lgc =  $site_info['site_lgc'];
            }
            $advisor_detail = $this->Paypal_model->get_advisor_detail($advisor_info->COLI_SN, $advisor_info->OPI_SN, $web_lgc);
            $item->advisor_detail = $advisor_detail;

            //给外联发送通知邮件
            $fromName = !empty($item->pn_payer) ? $item->pn_payer : '';
            $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : '';
            $toName = !empty($opi_firstname) ? $opi_firstname : '';
            $toEmail = !empty($opi_email) ? $opi_email : '';
            $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName;
            $body = $this->load->view('mail_templete', $item, true);
            $M_RelatedInfo = $item->pn_sn;
            $M_AddTime = $item->pn_payment_date;
            $M_State = 0;
            $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note');
            // 通知客人, 客人邮箱
            // $customer_detail = $this->Paypal_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype);
            $c_fromName = $advisor_detail->fullname ? $advisor_detail->fullname : $opi_firstname;
            $opi_email_list = explode(";", $advisor_detail->email); // 解析外联的邮件
            $c_fromEmail = isset($opi_email_list[0]) ? trim($opi_email_list[0]) : $opi_email;
            $c_toName = $item->pn_payer; // $customer_detail->fullname;
            $c_toEmail = $item->pn_payer_email ; // $customer_detail->email;
            $c_subject = $item->pn_mc_currency . " " . str_replace('-', '', $item->pn_mc_gross) . " Refunded to your account, booking number " . $item->pn_invoice;
            $c_body = $this->load->view('refund_buyer', $item, true);
            $c_M_RelatedInfo = $item->pn_sn;
            $c_M_AddTime = $item->pn_payment_date;
            $c_M_State = 0;
            $this->Paypal_model->save_automail(
                $c_fromName,
                $c_fromEmail,
                $c_toName,
                $c_toEmail,
                $c_subject,
                $c_body,
                $c_M_RelatedInfo,
                $c_M_State,
                $c_M_AddTime,
                'ChinaHighlights refund receipt');
            $this->Note_model->update_send($item->pn_txn_id, 'send-customer', $item->pn_sn);
        }
        //添加邮件发送记录 end
        // 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录
        // 更新是否需要发送财务
        $refund_finance_day = 20;
        $now_day = date('d');
        $late_entry_date_set = $now_day<$refund_finance_day ? date('Y-m-01', strtotime("-1 month")) : date('Y-m-01');
        if ($this->Paypal_model->if_finance_done($advisor_info->COLI_GRI_SN, $late_entry_date_set) === true) {
            $this->Note_model->update_send($item->pn_txn_id, 'send-to-finance', $item->pn_sn);
        }
        return ;
    }

    public function trippest_note($orderid_info, $paypal_msg)
    {
        $send_type = '';
        $tp_orderid = '';
        $real_orderid = $orderid_info->orderid;
        if (substr($orderid_info->orderid, 0, 2) == '01') {
            $tp_orderid = "#" . substr($orderid_info->orderid, 10);
            $real_orderid = '';
        }
        // 获取HT订单号
        $ht_tp_order = $this->Paypal_model->get_trippest_order($tp_orderid, $real_orderid);
        if (empty($ht_tp_order)) {
            /**
             * 此处不直接退出是为了:在(邮件订单不能自动录入/未收到新订单邮件)时也能通知外联已收款,防止漏单
             * 本方法内-以下的非空判断同理: !empty($ht_tp_order)
             * * 未找到订单先邮件通知: pn_send='', 继续排队等待录入. 直到匹配订单变更为send
             */
            // return $this->Note_model->update_send($paypal_msg->pn_txn_id, 'sendfail');
        } else {
            $tp_orderid = $ht_tp_order->COLI_PriceMemo;
            $real_orderid = $ht_tp_order->COLI_ID;
            //更新正确的订单信息到记录中，以这个为主
            $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_TP');
        }
        $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency));
        $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id;
        $USD_amount = $this->Paypal_model->get_USD($paypal_msg->pn_mc_gross, $paypal_msg->pn_mc_currency);
        if (false == $this->Paypal_model->if_biz_gai_exists($paypal_msg->pn_txn_id) ) {
            if ( ! empty($ht_tp_order)) {
                $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13);
                $this->Paypal_model->insert_biz_order_log($ht_tp_order->COLI_SN, 'BS13');
                $this->Paypal_model->update_paymanner($ht_tp_order->COLI_SN, '15010');
            }
            if (trim($paypal_msg->pn_send)!='' && trim($paypal_msg->pn_send)!='send') {
                $opi_firstname = "David";
                $opi_email = "david@trippest.com";
                $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : '';
                $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : '';
                $toName = !empty($opi_firstname) ? $opi_firstname : '';
                $toEmail = !empty($opi_email) ? $opi_email : '';
                $subject = $real_orderid . $tp_orderid . '_' . $orderid_info->ordertype . ' / ' . $paypal_msg->pn_mc_gross . $paypal_msg->pn_mc_currency . ' / ' . $fromName;
                $body = $this->load->view('mail_templete', $paypal_msg, true); //$paypal_msg->pn_memo;
                $M_RelatedInfo = $paypal_msg->pn_sn;
                $M_AddTime = $paypal_msg->pn_payment_date;
                $M_State = 0;
                $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note');
                empty($ht_tp_order) ? $send_type = "" : false ; // 未录订单先通知收款, 置为空继续排队
            }
        }
        if ( ! empty($ht_tp_order)) {
            $this->Paypal_model->add_account_info(
                $ht_tp_order->COLI_SN,
                $ht_tp_order->COLI_ID,
                $paypal_msg->pn_mc_gross,
                $paypal_msg->pn_payment_date,
                mb_strtoupper($paypal_msg->pn_mc_currency),
                $USD_amount,
                $ssje,
                $paypal_msg->pn_payment_date,
                $paypal_msg->pn_payment_date,
                $paypal_msg->pn_payment_date,
                '',
                $paypal_msg->pn_payer_email,
                $paypal_msg->pn_txn_id,
                $ht_memo
            );
            $send_type = "send";
        }

        $this->Note_model->update_send($paypal_msg->pn_txn_id, $send_type, $paypal_msg->pn_sn);
    }

    //所有记录列表
    public function note_list() {
        $this->permission->is_admin(true);
        $data = array();
        //有关键词则不限制日期
        $data['search_key'] = $this->input->get_post('search_key');
        $data['date'] = $this->input->get('date');
        empty($data['date']) ? $data['date'] = date('Y-m-d') : false;

        if (!empty($data['search_key'])) {
            $data['notelist'] = $this->Note_model->search_key($data['search_key']);
        } else {
            $data['notelist'] = $this->Note_model->search_date($data['date']);
        }

        /**
         * 导出记录用的记录节点
         */
        $data['record_flags'] = $this->Note_model->list_export_record();

        $this->load->view('n-header', $data);
        $this->load->view('note_list');
        $this->load->view('n-footer');
    }

    //所有记录列表
    public function note_faillist() {
        $this->permission->is_admin(true);
        $data = array();
        //有关键词则不限制日期
        $data['search_key'] = $this->input->post('search_key');
        $data['date'] = $this->input->get('date');
        empty($data['date']) ? $data['date'] = date('Y-m-d') : false;
        $data['notelist'] = $this->Note_model->failnote(100);
        $this->load->view('n-header', $data);
        $this->load->view('note_list');
        $this->load->view('n-footer');
    }

    /**
     * 按状态查找
     * @author LYT
     */
    public function note_status_list($status) {
        $this->permission->is_admin(true);
        $data = array();
        $data['date'] = $this->input->get('date');
        empty($data['date']) ? $data['date'] = date('Y-m-d') : false;
        $data['notelist'] = $this->Note_model->notestatus(200, $status);
        $this->load->view('n-header', $data);
        $this->load->view('note_list');
        $this->load->view('n-footer');
    }

    /**
     * 按账户查找
     * @author LYT
     */
    public function note_account_list($status) {
        $this->permission->is_admin(true);
        $data = array();
        $data['notelist'] = $this->Note_model->noteaccount(200, $status);
        $this->load->view('n-header', $data);
        $this->load->view('note_list');
        $this->load->view('n-footer');
    }

    //获取note详情，修改各项数据
    public function note_modal($pn_txn_id, $pn_id=false, $pn_invoice=false) {
        $this->permission->is_admin(true);
        $data = array('pn_invoice'=>$pn_invoice);
        if (!empty($pn_txn_id)) {
            $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
            if (!empty($data['note'])) {
                if (!empty($pn_invoice)) {
                    $orderid_info = $this->analysis_orderid($pn_invoice);
                } else {
                    $orderid_info = $this->analysis_orderid($data['note']->pn_invoice);
                }
                $data['pn_invoice'] = $pn_invoice ? $pn_invoice : $data['note']->pn_invoice;
                if (!empty($orderid_info)) {
                    $orderid_info = json_decode($orderid_info);
                    $data['order_info'] = $this->Paypal_model->get_order($orderid_info->orderid, true, $orderid_info->ordertype);
                }

                $order_sn = empty($data['order_info']) ? 0 : $data['order_info']->COLI_SN;
                $data['group_accout_info'] =
                    $this->Paypal_model->get_group_accout_info($order_sn, $data['note']->pn_txn_id);
                echo json_encode($this->load->view('note_setting', $data, true));
                return true;
            }
        }
        echo json_encode('没找到数据！');
    }

    //修改订单名
    public function note_modal_save() {
        $this->gai_modal_save();
        // $data = array();

        // $pn_txn_id = $this->input->post('pn_txn_id');
        // $pn_invoice = $this->input->post('pn_invoice');

        // if (!empty($pn_txn_id) && !empty($pn_invoice)) {
        //     $orderid_info = $this->analysis_orderid($pn_invoice);
        //     if (!empty($orderid_info)) {
        //         $orderid_info = json_decode($orderid_info);
        //         $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype);
        //         if (!empty($advisor_info)) {
        //             $this->Note_model->set_invoice($pn_txn_id, $pn_invoice);
        //             $this->send_note($pn_txn_id);
        //             echo json_encode('修改成功！');
        //             return true;
        //         }
        //     }
        // }
        // echo json_encode('没找到数据！');
    }

    //关闭note通知，用于手动处理通知后
    public function close_note($pn_txn_id) {
        $data = array();
        $data['note'] = $this->Note_model->note($pn_txn_id);
        if (!empty($data['note'])) {
            $this->Note_model->update_send($pn_txn_id, 'send');
            echo json_encode('通知已经关闭！');
            return true;
        }
        echo json_encode('没找到数据！');
    }

    public function get_export_record_currency($currency)
    {
        // $currency = $this->input->get_post('currency');
        $records = $this->Note_model->list_export_record(0, $currency);
        return $this->output->set_content_type('application/json')->set_output(json_encode($records));
    }

    public function export_list()
    {
        $from_date = $this->input->post("from_date");
        $to_date   = $this->input->post("to_date");
        $currency  = $this->input->post("currency");
        $amount  = $this->input->post("set_amount");
        $last_record  = $this->input->post("date_history");
        if (empty($amount)) {
            $export_list = $this->Note_model->date_range($from_date, $to_date, $currency, null, false);
        } else {
            $allmost_day = intval(ceil($amount/10000));
            if ( ! in_array($currency, array('CNY','USD'))) {
                $allmost_day = 30;
            }
            $last_sn = null;
            $last_notice_sn = null;
            $last_notice_record = array();
            if ( ! empty($last_record)) {
                $selection_text = explode("@", $last_record);
                $last_sn = $selection_text[0];
                $last_notice_record = $this->Note_model->list_export_record($last_sn);
                if ( ! empty($last_notice_record[0])) {
                    $last_notice_sn = $last_notice_record[0]->TEL_transactionNoticeId;
                    // 查询导出记录时包含上次导出的最后一条.
                    // 因此目标金额设为本次的目标+上次已导出的部分
                    // 得到结果集之后会把本次的第一条的金额重新计算,即减去上次已导出金额.下述<!$>
                    $amount = bcadd($amount, $last_notice_record[0]->TEL_exportAmount);
                    $from_date = strstr($last_notice_record[0]->TEL_transactionDate, " ", TRUE);
                    $currency = $last_notice_record[0]->TEL_transactionCurrency;
                }
            }
            $all_list = $this->target_amount_recursive($currency, $amount, 0, $from_date, $allmost_day, array(), $last_notice_sn);

            $filter_list = [];
            $txn_list = [];
            $query_list = $all_list['list'];
            foreach ($query_list as $key => $row) {
              if (!in_array($row->pn_txn_id, $txn_list)) {
                $txn_list[] = $row->pn_txn_id;
                $filter_list[] = $row;
              }
            }
            $export_list = $filter_list;
            // <!$>修改导出的第一条记录, 金额改为剩余金额<!$>
            if ( ! empty($last_notice_record[0]) && $last_notice_record[0]->TEL_transactionNoticeId==$export_list[0]->pn_sn) {
                $export_list[0]->pn_mc_gross = bcsub($last_notice_record[0]->TEL_transactionAmount, $last_notice_record[0]->TEL_exportAmount);
            }
        }
        if ($export_list == false) {
            echo "Not found any records for export.";
            return false;
        }
        // 记录这次导出的最后一条
        if (isset($all_list['last_flag']) && ! empty($all_list['last_flag'])) {
            $balance_diff = bcsub($all_list['now_amount'], $amount);
            $last_record_export = $balance_diff>0 ? bcsub($all_list['last_flag']->pn_mc_gross, $balance_diff) : $all_list['last_flag']->pn_mc_gross;
            $insert_db = array(
                "TEL_transactionType" => 15002
                ,"TEL_transactionNoticeId" => $all_list['last_flag']->pn_sn
                ,"TEL_transactionId" => $all_list['last_flag']->pn_txn_id
                ,"TEL_transactionDate" => $all_list['last_flag']->pn_datetime
                ,"TEL_transactionAmount" => $all_list['last_flag']->pn_mc_gross
                ,"TEL_transactionCurrency" => $all_list['last_flag']->pn_mc_currency
                ,"TEL_orderId" => $all_list['last_flag']->pn_invoice
                ,"TEL_exportAmount" => $last_record_export
                ,"TEL_exportDate" => date('Y-m-d H:i:s')
            );
            $this->Note_model->export_record($insert_db);
            // 修改导出的最后一条
            array_pop($export_list);
            $all_list['last_flag']->pn_mc_gross = $last_record_export;
            array_push($export_list, $all_list['last_flag']);
        }

        $this->save_excel($export_list);
    }

    /*!
     * 递归查询收款记录, 直到总金额>=目标总金额
     * @date   2019-02-27
     */
    public function target_amount_recursive($currency, $target_amount, $now_amount, $from_date,$days=10,$list=array(), $last_sn=null, $last_flag=null)
    {
        $to_date = date('Y-m-d', strtotime("+$days days", strtotime($from_date)));
        $former_list = $this->Note_model->date_range($from_date, $to_date, $currency, $last_sn, false);
        if (empty($former_list)) {
            $former_list = $this->Note_model->top_list(100, $currency, $last_sn, false);
        }
        $list_index = 0;
        $last_sn = $last_sn===null ? 0 : $last_sn;
        $last_flag = $last_flag===null ? null : $last_flag;
        while ($now_amount < $target_amount && isset($former_list[$list_index])) {
            $list[] = $former_list[$list_index];
            $now_amount = bcadd($now_amount, $former_list[$list_index]->pn_mc_gross);
            $last_sn = $former_list[$list_index]->pn_sn;
            $last_flag = $former_list[$list_index];
            $list_index++;
        }
        $ret = array(
            "last_flag" => $last_flag,
            "list" => $list,
            "now_amount" => $now_amount
        );
        if (empty($former_list)) {
            return $ret;
        }
        if ($now_amount < $target_amount) {
            return $this->target_amount_recursive($currency, $target_amount, $now_amount, $to_date, 10, $list, $last_sn, $last_flag);
        } else {
            return $ret;
        }
    }

    public function save_excel($export_list)
    {
        $this->load->library('PHPExcel');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        //set width
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        // 对齐
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        // 表标题行
        $objPHPExcel->getActiveSheet()
                    ->SetCellValue('A1', '#')
                    ->SetCellValue('B1', '团号')
                    ->SetCellValue('C1', '金额')
                    ->SetCellValue('D1', '币种')
                    ->SetCellValue('E1', '付款人')
                    ->SetCellValue('F1', '付款人邮箱')
                    ->SetCellValue('G1', '交易号')
                    ->SetCellValue('H1', '收单时间')
                    ->SetCellValue('I1', '付款人国籍')
                    ->SetCellValue('J1', '是否重复');
        $currency_sum = array();
        bcscale(2);
        $rowCount = 2;
        $txn_list = [];
        foreach ($export_list as $key => $row) {
            if( trim($row->pn_mc_currency) != "") {
                $currency_sum[trim($row->pn_mc_currency)] = @ bcadd($currency_sum[trim($row->pn_mc_currency)], $row->pn_mc_gross);
            }
            $payer = $row->pn_payer ? ($row->pn_payer . "<" . $row->pn_payer_email . ">") : "退款";
            $orderid = $row->pn_invoice ? $row->pn_invoice : $row->pn_item_number;
            $txn_duplicated = '';
            if (in_array($row->pn_txn_id, $txn_list)) {
              $txn_duplicated = 'X';
            }
            $txn_list[] = $row->pn_txn_id;

            $objPHPExcel->getActiveSheet()
                        ->SetCellValue('A'.$rowCount, ($rowCount-1))
                        // ->SetCellValue('A'.$rowCount, $row->pn_sn)
                        ->setCellValueExplicit('B'.$rowCount, $orderid,PHPExcel_Cell_DataType::TYPE_STRING)
                        ->setCellValue('C'.$rowCount, number_format($row->pn_mc_gross, 2, ".", ""))
                        ->setCellValueExplicit('D'.$rowCount, trim($row->pn_mc_currency) ,PHPExcel_Cell_DataType::TYPE_STRING)
                        ->SetCellValue('E'.$rowCount, $row->pn_payer)
                        ->SetCellValue('F'.$rowCount, $row->pn_payer_email)
                        ->setCellValueExplicit('G'.$rowCount, $row->pn_txn_id,PHPExcel_Cell_DataType::TYPE_STRING)
                        ->SetCellValue('H'.$rowCount, $row->pn_datetime)
                        ->SetCellValue('I'.$rowCount, $row->payer_country)
                        ->setCellValueExplicit('J'.$rowCount, $txn_duplicated,PHPExcel_Cell_DataType::TYPE_STRING);
            $payer = $orderid = "";
            $rowCount++;
        }
        $rowCount++; // 隔一行
        // 汇总行
        $objPHPExcel->getActiveSheet()
                    ->SetCellValue('A' . $rowCount, '合计');
        foreach ($currency_sum as $kc => $cur) {
            $objPHPExcel->getActiveSheet()
                        ->SetCellValue('B' . $rowCount, $kc)
                        ->setCellValueExplicit('C' . $rowCount, number_format($cur, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING);
            $rowCount++;
        }
        $filename = "export_paypal_" . date('Y-m-d');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    /** 查看收款记录的是否已录入到订单 */
    public function gai_modal($pn_txn_id=null, $pn_id = null, $neworder=null)
    {
        $this->permission->is_admin(true);
        $data = array();
        $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
        $orderid_info = $this->analysis_orderid($data['note']->pn_invoice);
        if (!empty($orderid_info)) {
            $orderid_info = json_decode($orderid_info);
            if ($orderid_info->ordertype === 'TP' || $orderid_info->ordertype === 'A') {
                $orderid_info->ordertype = 'B';
            }
            if ($orderid_info->ordertype === 'T') {
                $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id);
            } elseif ($orderid_info->ordertype === 'B') {
                $data['gai_info'] = $this->Paypal_model->get_money_b($pn_txn_id);
            }
        }
        $data['old_order'] = $data['note']->pn_invoice;
        $data['new_order'] = $neworder;
        $data['order_info'] = null;
        if ($neworder !== null) {
            $neworder_id = $this->analysis_orderid($neworder);
            $neworder_id = json_decode($neworder_id);
            if ($neworder_id->ordertype === 'TP') {
                $neworder_id->ordertype = 'B';
            }
            if ( ! empty($neworder_id)) {
                $data['order_info'] = $this->Paypal_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype);
            }
        }
        echo json_encode($this->load->view('gai_setting', $data, true));
    }

    /** 测试收款记录的是否已录入到订单
     * 测试找不到订单信息使用
    */
    public function test_gai_modal($pn_txn_id=null, $pn_id = null, $neworder=null)
    {
        $data = array();
        $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
        $orderid_info = $this->analysis_orderid($data['note']->pn_invoice);
        if (!empty($orderid_info)) {
            $orderid_info = json_decode($orderid_info);
            $data['old_order_info'] = $orderid_info;
            if ($orderid_info->ordertype === 'TP' || $orderid_info->ordertype === 'A') {
                $orderid_info->ordertype = 'B';
            }
            if ($orderid_info->ordertype === 'T') {
                $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id);
            } elseif ($orderid_info->ordertype === 'B') {
                $data['gai_info'] = $this->Paypal_model->get_money_b($pn_txn_id);
            }
        }
        $data['old_order'] = $data['note']->pn_invoice;
        $data['new_order'] = $neworder;
        $data['order_info'] = null;
        if ($neworder !== null) {
            $neworder_id = $this->analysis_orderid($neworder);
            $neworder_id = json_decode($neworder_id);
            $data['new_order_info'] = $neworder_id;
            if ($neworder_id->ordertype === 'TP') {
                $neworder_id->ordertype = 'B';
            }
            if (!empty($neworder_id)) {
                $data['order_info'] = $this->Paypal_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype);
            }
        }
        echo json_encode($data);
    }

    public function gai_modal_save()
    {
        $data = array();
        $old_ssje = NULL;
        $pn_txn_id = $this->input->post('pn_txn_id');
        $pn_id = $this->input->post('pn_id');
        $neworder = $this->input->post('pn_invoice');

        $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id);
        $orderid_info = $this->analysis_orderid($data['note']->pn_invoice);
        if (!empty($orderid_info)) {
            $orderid_info = json_decode($orderid_info);
            if ($orderid_info->ordertype === 'TP') {
                $orderid_info->ordertype = 'B';
            }
            if ($orderid_info->ordertype === 'T') {
                $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id);
                if ( ! empty($data['gai_info'])) {
                    $old_ssje = $data['gai_info'][0]->GAI_SSJE;
                    $this->Paypal_model->delete_money_t($pn_txn_id);
                }
            } elseif ($orderid_info->ordertype === 'B') {
                $data['gai_info'] = $this->Paypal_model->get_money_b($pn_txn_id);
                if ( ! empty($data['gai_info'])) {
                    $old_ssje = $data['gai_info'][0]->GAI_SSJE;
                    $this->Paypal_model->delete_money_b($pn_txn_id);
                }
            } elseif ($orderid_info->ordertype === 'A') {
                $this->send_note($pn_txn_id);
                echo json_encode('已发送APP！');
                return true;
            }
        }

        if (!empty($pn_txn_id) && !empty($neworder)) {
            $orderid_info = $this->analysis_orderid($neworder);
            if (!empty($orderid_info)) {
                $orderid_info = json_decode($orderid_info);
                if ($orderid_info->ordertype === 'TP') {
                    $orderid_info->ordertype = 'B';
                }
                $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, TRUE);
                if (!empty($advisor_info)) {
                    $this->Note_model->set_invoice($pn_txn_id, $neworder);
                    $this->send_note($pn_txn_id, $old_ssje);
                    echo json_encode('修改成功！');
                    return true;
                }
            }
        }
        echo json_encode('没找到数据！');
        return;
    }
    public function closeGai($pn_txn_id)
    {
        $data = array();
        $data['note'] = $this->Note_model->note($pn_txn_id);
        if (!empty($data['note'])) {
            $this->Note_model->update_send($pn_txn_id, 'closeRecord');
            echo json_encode('该收款记录已经忽略！');
            return true;
        }
        echo json_encode('没找到数据！');
        return;
    }

    public function process_notify_APP($item, $orderid_info)
    {
        $content = json_decode($item->pn_memo, true);
        $post_body = http_build_query($content);
        $post_body .= '&appkey=jdfk*$jfjdk1688';
        $app_return = $this->async_curl("http://wx.chinatrainbooking.com/paypalend/", $post_body, 5);
        if (intval($app_return)===200) {
            return false;   // 下一步更新为send-app
        }
        return true;    // 下一步: sendfail

        $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype);
        //查不到订单信息
        if (empty($advisor_info)) {
            $this->Note_model->update_send($item->pn_txn_id, 'sendfail');
            return false;
        }
        $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net
        $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie
        //没有外联信息表示订单未分配
        if (empty($opi_email) || empty($opi_firstname)) {
            $this->Note_model->update_send($item->pn_txn_id, 'sendfail');
            return false;
        }
        $order_gai_list = $this->Paypal_model->get_money_list($orderid_info->orderid, $item->pn_mc_gross, $item->pn_mc_currency);
        //添加邮件发送记录
        if ($item->pn_send !== 'send' && empty($order_gai_list)) {
            //给外联发送通知邮件
            $fromName = !empty($item->pn_payer) ? $item->pn_payer : '';
            $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : '';
            $toName = !empty($opi_firstname) ? $opi_firstname : '';
            $toEmail = !empty($opi_email) ? $opi_email : '';
            // $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName;
            $subject = "请核对收款_" . $orderid_info->orderid . "_" . $item->pn_mc_currency . "_" . $item->pn_mc_gross;
            $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo;
            $M_RelatedInfo = $item->pn_sn;
            $M_AddTime = $item->pn_payment_date;
            $M_State = 0;
            $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note');
            //添加邮件发送记录 end
            $this->Note_model->update_send($item->pn_txn_id, 'send', $item->pn_sn);
        }
        $order_gai = $this->Paypal_model->get_money_list($orderid_info->orderid);
        return empty($order_gai);
    }

    function async_curl($url, $body=null, $second = 1)
    {
        $ch = curl_init();
        $curlVersion = curl_version();
        $ua = "Webht (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." " . "AsyncJob";
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        if(stripos($url,"https://")!==FALSE){
            // curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        } else {
            // curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
            // curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
        }
        curl_setopt($ch,CURLOPT_USERAGENT, $ua);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }

        //运行curl
        $data = curl_exec($ch);
        if (curl_errno($ch) && !in_array(curl_errno($ch),array(0,28)) ) {
            log_message('error',"Webht Async Curl Call 出错，错误码:" . curl_errno($ch) . ": " . curl_error($ch) . ",  url: " . $url);
        }
        if (!in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE),array(0,200)) ) {
            log_message('error', "Webht Async Curl Call Request html Status Code: ".curl_getinfo($ch, CURLINFO_HTTP_CODE)."; curl url: ".$url);
        }
        $http_ret_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $http_ret_code;
    }

}
