<?php

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

class Paypal_model extends CI_Model {

    private $HT;

    function __construct() {
        parent::__construct();
        $this->HT = $this->load->database('HT', TRUE);
        //$this->DEST = $this->load->database('DEST', TRUE);
    }

    //根据订单号获取外联邮箱
    public function get_order($COLI_ID, $orderinfo = false, $ordertype = 'N', $handpick=false) {
        $result = '';
        $fieldsql = $orderinfo == false ? '' : " ,* ";
        //先查商务订单B,APP订单A、再查传统订单T
        if ($ordertype == 'B' || $ordertype == 'A') {
            $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo
                            LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN
               where COLI_ID =?  order by CHARINDEX('50',COLI_State) asc"; // and COLI_State<>50
            $query = $this->HT->query($sql, array($COLI_ID));
            $result = $query->result();
        }
        //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。
        if (empty($result) && ($ordertype == 'T')) {
            $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo
                           LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN
                   where RTRIM(COLI_ID) like '%$COLI_ID'
                   order by CHARINDEX('$COLI_ID', COLI_ID)  ";
            $query = $this->HT->query($sql);
            $result = $query->result();
            if ($handpick === TRUE) {
              $result = array($result[0]);
            }
        }

        //查传统订单add_code，网前实时支付会先生成一个临时订单号存在add_code里，如订单45103248

        if (empty($result) && ($ordertype == 'M')) {
            $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo
          LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN
          where COLI_AddCode =? ";
            $query = $this->HT->query($sql, array($COLI_ID));
            $result = $query->result();
        }

        if (empty($result) && ($ordertype == 'M')) {
            $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli
          LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN
          where
                EXISTS (
                         SELECT TOP 1 1
                         FROM   ConfirmLineInfoTmp clit
                         WHERE  clit.COLI_ID = ?
                                AND cli.COLI_AddCode = CAST(clit.COLI_SN AS VARCHAR(10))
                     )
                     ";
            $query = $this->HT->query($sql, array($COLI_ID));
            $result = $query->result();
        }

        //订单号查询不到尝试使用团号查询
        if (empty($result) && $ordertype == 'B') {
            $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo
                            LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN
               where COLI_GroupCode like '%-$COLI_ID%' order by CHARINDEX('50',COLI_State) asc";
            $query = $this->HT->query($sql);
            $result = $query->result();
        }
        //团号查询不到尝试使用客人邮箱查询(预订多次的老客户得按日期新旧排序，取最新的数据)

        if (!empty($result) && is_array($result) ) {
            //print_r($result[0]);
            //die();
            if (count($result) > 1 && $handpick===false) {
                $result = array();
            } else {
                $result = $result[0];
            }
        }

        return $result;
    }

    /**
     * 查找付款记录，用于判断是否已经审核。
     * 已经审核过得记录不能修改订单号。
     */
    public function get_group_accout_info($coli_sn, $pn_txn_id) {
        // select * from BIZ_GroupAccountInfo where GAI_COLI_SN = 559007281 and GAI_AccreditNo = '91R84932UM059045C'
        $info_sql = "select GAI_SN, GAI_State from BIZ_GroupAccountInfo
        where GAI_COLI_SN = $coli_sn and GAI_AccreditNo = '$pn_txn_id'
        union
        select GAI_SN, GAI_State from GroupAccountInfo
        where GAI_COLI_SN = $coli_sn and GAI_AccreditNo = '$pn_txn_id'";

        $info_query = $this->HT->query($info_sql);
        $info_result = $info_query->result();
        $group_accout_info = array(
            'GAI_SN' => 0,
            'GAI_State' => 0
        );
        if (!empty($info_empty)) {
            $group_accout_info = $info_result[0];
        }
        return $group_accout_info;
    }

    //获取收款记录(商务订单)
    public function get_money_list($GAI_COLI_ID, $GAI_SQJE=null, $GAI_SQJECurrency=null) {
        $je_sql = $GAI_SQJE===null ? " " : " and GAI_SQJE=? ";
        $currency_sql = $GAI_SQJECurrency===null ? " " : " and GAI_SQJECurrency=? ";
        $sql = "SELECT GAI_SN,GAI_CusEmail,GAI_Memo
                FROM BIZ_GroupAccountInfo bgai
               WHERE bgai.GAI_COLI_ID = ?  $je_sql  $currency_sql
               ORDER BY bgai.GAI_SN ASC";
        $query = $this->HT->query($sql, array($GAI_COLI_ID, $GAI_SQJE, $GAI_SQJECurrency));
        $result = $query->result();
        return $result;
    }

    //获取收款记录(传统订单)
    public function get_money_list2($COLI_ID, $GAI_SQJE, $GAI_SQJECurrency) {
        $sql = "SELECT COLI_ID,GroupAccountInfo.*
                from GroupAccountInfo
                     left join ConfirmLineInfo on GAI_COLI_SN=COLI_SN
               where COLI_ID=? and GAI_SQJE=? and GAI_SQJECurrency=?
               ORDER BY GAI_SN ASC";
        $query = $this->HT->query($sql, array($COLI_ID, $GAI_SQJE, $GAI_SQJECurrency));
        $result = $query->result();
        return $result;
    }

    //更新收款记录(商务订单)
    public function update_account_info($GAI_CusEmail, $GAI_Memo, $GAI_SN, $GAI_AccreditNo) {
        $sql = "UPDATE BIZ_GroupAccountInfo SET GAI_CusEmail=?, GAI_Memo=?,GAI_AccreditNo=? WHERE GAI_SN=?";
        $query = $this->HT->query($sql, array($GAI_CusEmail, $GAI_Memo, $GAI_AccreditNo, $GAI_SN));
        return $query;
    }

    //更新收款记录(传统订单)
    public function update_account_info2($GAI_CusEmail, $GAI_Memo, $GAI_SN) {
        $sql = "UPDATE GroupAccountInfo SET GAI_CusEmail=?, GAI_Memo=? WHERE GAI_SN=?";
        $query = $this->HT->query($sql, array($GAI_CusEmail, $GAI_Memo, $GAI_SN));
        return $query;
    }

    //修改订单状态
    public function update_biz_coli_state($coli_sn, $coli_state) {
        $success_sql = in_array($coli_state, array(8,13)) ? ", COLI_IsSuccess=1" : "";
        $sql = "
                IF EXISTS
                ( SELECT OPI_DEI_SN
                 FROM OperatorInfo
                 INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID
                 WHERE COLI_SN=? AND OPI_DEI_SN=10
                )
                  UPDATE BIZ_ConfirmLineInfo
                  SET COLI_State=?
                  $success_sql
                  WHERE COLI_SN=?
                ELSE
                  UPDATE BIZ_ConfirmLineInfo
                  SET COLI_State=?
                  $success_sql
                  WHERE COLI_SN=?
                  AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999)
          ";
        $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn));
        return $query;
    }

    public function if_biz_gai_exists($GAI_AccreditNo)
    {
        $sql = " SELECT TOP 1 1 FROM   BIZ_GroupAccountInfo
                   WHERE  (GAI_AccreditNo = ?  OR  GAI_Memo LIKE '%$GAI_AccreditNo%')
                    AND DeleteFlag=0";
        $result = $this->HT->query($sql, array($GAI_AccreditNo));
        return ($result->num_rows() > 0);
    }

    //添加收款记录(商务订单),APP会自动增加记录，所以添加前根据金额来判断是否有重复记录
    public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) {
        //先判断是否有这条数据
        $sql = "
            IF NOT EXISTS(
                   SELECT TOP 1 1
                   FROM   BIZ_GroupAccountInfo
                   WHERE  GAI_COLI_SN = ? AND DeleteFlag=0 AND GAI_Type='15010'
                   and (
                        (GAI_AccreditNo IS NULL AND GAI_SQJE=?  )
                   OR
                   (GAI_AccreditNo='$GAI_AccreditNo')
                   )
               )
            INSERT INTO BIZ_GroupAccountInfo (
                        GAI_COLI_SN
                       ,GAI_COLI_ID
                       ,GAI_Type
                       ,GAI_SQJE
                       ,GAI_SQDate
                       ,GAI_SQJECurrency
                       ,GAI_SSJE
                       ,GAI_SSDate
                       ,GAI_AccountDate
                       ,GAI_SubmitDate
                       ,GAI_CusName
                       ,GAI_CusEmail
                       ,GAI_AccreditNo
                       ,GAI_Memo
                       ,GAI_State
                       ,DeleteFlag,LastEditTime
                    ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,?,0,0,GETDATE())";
        $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo));
        $insertid = $this->HT->last_id('BIZ_GroupAccountInfo');
        return $query;
    }

    //添加收款记录(商务订单)
    public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) {
        //先判断是否有这条数据
        $sql = "

            IF NOT EXISTS(
                   SELECT TOP 1 1
                   FROM   BIZ_GroupAccountInfo
                   WHERE  (GAI_AccreditNo = ?  OR  GAI_Memo LIKE '%$GAI_AccreditNo%') AND DeleteFlag=0
               )
            INSERT INTO BIZ_GroupAccountInfo (
                        GAI_COLI_SN
                       ,GAI_COLI_ID
                       ,GAI_Type
                       ,GAI_SQJE
                       ,GAI_SQDate
                       ,GAI_SQJECurrency
                       ,GAI_Money
                       ,GAI_SSJE
                       ,GAI_SSDate
                       ,GAI_AccountDate
                       ,GAI_SubmitDate
                       ,GAI_CusName
                       ,GAI_CusEmail
                       ,GAI_AccreditNo
                       ,GAI_Memo
                       ,GAI_State
                       ,DeleteFlag,LastEditTime
                    ) VALUES (?,?,15002,?,?,?,?,?,?,?,?,?,?,?,?,0,0,GETDATE())";
        $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo));
        $insertid = $this->HT->last_id('BIZ_GroupAccountInfo');
        return $query;
    }

    //添加收款记录(传统订单)
    public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) {
        //先判断是否有这条数据
        $sql = "

            IF NOT EXISTS(
                   SELECT TOP 1 1
                   FROM   GroupAccountInfo
                   WHERE  (GAI_AccreditNo = ?  OR  GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0
               )
            INSERT INTO GroupAccountInfo (
                        GAI_COLI_SN
                       ,GAI_Type
                       ,GAI_SQJE
                       ,GAI_SQDate
                       ,GAI_SQJECurrency
                       ,GAI_SSJE
                       ,GAI_SSDate
                       ,GAI_AccountDate
                       ,GAI_SubmitDate
                       ,GAI_CusName
                       ,GAI_CusEmail
                       ,GAI_AccreditNo
                       ,GAI_Memo
                       ,GAI_State
                       ,DeleteFlag,LastEditTime
                    ) VALUES (?,15002,?,?,?,?,?,?,?,?,?,?,?,0,0,GETDATE())";
        $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo));
        $insertid = $this->HT->last_id('GroupAccountInfo');
        return $insertid;
    }

    //更新线路提醒
    public function update_coli_introduction($coli_sn, $msg) {
        $sql = "
            update ConfirmLineInfo
             set COLI_Introduction=ISNULL(COLI_Introduction,'')+' '+?
             where 1=1
             AND ISNULL(COLI_Introduction,'')=''
              AND COLI_SN=?
            ";
			// isnull(COLI_Sended,0) in (0,1) 之前判断是新订单或者未分配状态才添加提示的，有些团是后面付款的，所以把限制取消掉
        $query = $this->HT->query($sql, array($msg, $coli_sn));
        return $query;
    }

    //存储paypal的实时通知
    public function save_paypal_note($pn_txn_id, $pn_invoice, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer_email, $pn_payment_date, $pn_memo) {
        $sql = "
                INSERT INTO paypal_note
                  (
                    pn_txn_id,pn_invoice, pn_mc_gross, pn_item_name, pn_item_number,pn_mc_currency, pn_payment_status,pn_payer_email,pn_payment_date, pn_memo,pn_datetime
                  )
                VALUES
                  (
                    ?,?,?,N?,N?,?,?,N?,?, N?, GETDATE()
                  )
        ";
        $query = $this->HT->query($sql, array($pn_txn_id, $pn_invoice, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer_email, $pn_payment_date, $pn_memo));
        $insertid = $this->HT->last_id('paypal_note');
        return $query;
    }

    public function 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) {
        $sql = "INSERT INTO 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
                               ,pm_create_date)
                         VALUES (?,N?,N?,?,N?,N?,N?,?,N?,?,?,getdate())";
        $this->HT->query($sql, array($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));
        $insertid = $this->HT->last_id('paypal_msg');
        return $insertid;
    }

    public function update_paypal_msg($pm_sn, $pm_orderid, $pm_item_name, $pm_payer_email, $pm_payer_status, $pm_memo) {
        $sql = "UPDATE paypal_msg
                 SET
                     pm_orderid=N?,
                     pm_item_name=N?,
                     pm_payer_email=N?,
                     pm_payer_status=?,
                     pm_memo=N?
               WHERE pm_sn=?";
        $query = $this->HT->query($sql, array($pm_orderid, $pm_item_name, $pm_payer_email, $pm_payer_status, $pm_memo, $pm_sn));
        return $query;
    }

    public function get_paypal_msg($pm_transaction_id = '') {
        $mapsql = empty($pm_transaction_id) ? " pm_payer_status='' " : " pm_transaction_id='$pm_transaction_id' ";
        $sql = "SELECT top 1 * from paypal_msg where $mapsql order by pm_payment_date asc";
        $query = $this->HT->query($sql);
        $result = $query->result();
        return $result;
    }

    public function last_paypal_msg($filed = 'pm_payment_date') {
        $sql = "SELECT top 1 $filed ,pm_create_date from paypal_msg order by pm_payment_date desc";
        $query = $this->HT->query($sql);
        $result = $query->result();
        return $result;
    }

    public function get_mail_list($top = 30, $mail_sn_string = '', $date = 'all') {
        $mapsql = $date == 'all' ? '' : " AND M_AddTime BETWEEN '$date 00:00:00' AND '$date 23:59:59'";
        if ($mail_sn_string == '') {
            $sql = "SELECT top 360  M_SN FROM Email_AutomaticSend WHERE M_Web='paypal msg' $mapsql ORDER BY M_AddTime desc,M_SN desc";
        } else {
            $sql = "SELECT *
                    FROM Email_AutomaticSend
                         LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn
                   WHERE M_Web='paypal msg' AND M_SN in($mail_sn_string)
                   ORDER BY M_AddTime desc,M_SN desc";
        }
        $query = $this->HT->query($sql);
        return $query->result();
    }

    //根据订单号查询邮件
    public function get_search_mails($mail_o_orderno) {
        $sql = "SELECT TOP 50 *
                    FROM Email_AutomaticSend
                         LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn
                   WHERE M_Web='paypal msg' AND pm_orderid like '%$mail_o_orderno%' or M_ReplyToEmail like '%$mail_o_orderno%' or pm_transaction_id like '%$mail_o_orderno%'
                   ORDER BY M_AddTime desc,M_SN desc";
        $query = $this->HT->query($sql);
        $result = $query->result();
        return $result;
    }

    //我的收款记录
    public function get_my_order($mail_to, $mail_to_name, $cn_name) {
        $sql = "SELECT top 100 *
                from Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn
               where M_Web='paypal msg' and M_ToEmail =? AND (M_ToName=? or M_ToName=?)";
        $query = $this->HT->query($sql, array($mail_to, $mail_to_name, $cn_name));
        $result = $query->result();
        return $result;
    }

    //获取没有外联信息的邮件(超过一周的不处理)
    public function get_unsend_list($top = 30, $mail_sendstate) {
        $start_date = date('Y-m-d 00:00:00', time() - 7 * 24 * 60 * 60);
        $sql = "SELECT top $top * FROM Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn WHERE M_Web='paypal msg' AND M_State=? AND M_AddTime>'$start_date' ORDER BY M_AddTime desc,M_SN desc";
        $query = $this->HT->query($sql, array($mail_sendstate));
        return $query->result();
    }

    public function update_mail($mail_sn, $mail_to, $mail_to_name, $mail_sendstate = 0) {
        $sql = "UPDATE Email_AutomaticSend SET M_ToEmail=N?,M_ToName=N?,M_State=? WHERE M_SN =? ";
        $query = $this->HT->query($sql, array($mail_to, $mail_to_name, $mail_sendstate, $mail_sn));
        return $query;
    }

    public function save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $frominfo = 'paypal msg', $M_Web = 'paypal msg') {
        $sql = "INSERT INTO
                Email_AutomaticSend (
                    M_ReplyToName,
                    M_ReplyToEmail,
                    M_ToName,
                    M_ToEmail,
                    M_Title,
                    M_Body,
                    M_Web,
                    M_FromName,
                    M_ServiceSN,
                    M_State,
                    M_AddTime
                ) VALUES (N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) ";
        $query = $this->HT->query($sql, array($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State));
        return $query;
    }

    //获取错误信息
    public function get_all_error_order($i = "", $lastdate) {
        switch ($i) {
            case 1:
                $sql = "SELECT
    					M_SN,
    					M_ReplyToEmail,
    					pm_currency,
    					pm_payer,
    					pm_money,
    					pm_orderid,
    					M_ToEmail
                    FROM Email_AutomaticSend
                         LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn
                   WHERE pm_orderid='' AND M_Web='paypal msg' ORDER BY M_SN DESC";
                break;
            case 2:
                $sql = "SELECT
    					 M_SN,
    					M_ReplyToEmail,
    					pm_currency,
    					pm_payer,
    					pm_money,
    					pm_orderid,
    					M_ToEmail
                    FROM Email_AutomaticSend
                         LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn
                   WHERE M_ToEmail='' AND M_Web='paypal msg' ORDER BY M_SN DESC";
                break;
            default:
                $sql = "SELECT
    					M_SN,
    					M_ReplyToEmail,
    					pm_currency,
    					pm_payer,
    					pm_money,
    					pm_orderid,
    					M_ToEmail,
    					M_AddTime,
    					M_State
                    FROM paypal_msg
                         LEFT JOIN  Email_AutomaticSend ON M_ServiceSN=pm_sn
                   WHERE pm_orderid='' OR M_ToEmail='' AND M_Web='paypal msg' AND DATEDIFF(m,pm_create_date,'" . $lastdate . "')<=3 ORDER BY M_SN DESC";
        }


        $query = $this->HT->query($sql);
        $result = $query->result();
        return $result;
    }

    //订单号匹配不正确
    public function get_unmatch_list($type, $lastdate) {

        if ($type == 'BIZ') {
            $sql = "SELECT *
    				FROM (
    					SELECT COLI_ID,
    						   OPI_Email
    					FROM BIZ_ConfirmLineInfo
    					LEFT JOIN OperatorInfo
    					ON  COLI_OPI_ID = OPI_SN
    					WHERE EXISTS(
    							SELECT 1 FROM paypal_msg
    							WHERE paypal_msg .pm_orderid = BIZ_ConfirmLineInfo.COLI_ID)
    				) T,
    				(SELECT pm .pm_orderid,
                  eas.M_ToEmail ,
                  pm.pm_sn ,
                  pm.pm_create_date ,eas. M_SN
           		FROM   paypal_msg pm
                  INNER JOIN Email_AutomaticSend eas
                       ON  eas .M_ServiceSN = pm .pm_sn
                       AND eas .M_Web = 'paypal msg'
      			 )    P
               WHERE  T.COLI_ID = P.pm_orderid
       			AND T.OPI_Email <> P.M_ToEmail
    			AND  DATEDIFF(m,p.pm_create_date,'" . $lastdate . "')<=3
				ORDER BY
		       p.pm_sn DESC ";
        } else if ($type == 'tradition') {


            $sql = "SELECT *
					FROM   (

		       			SELECT  COLI_ID ,OPI_Email  from ConfirmLineInfo
		                           LEFT JOIN OperatorInfo ON COLI_OPI_ID =OPI_SN
		           		WHERE  EXISTS(
		                      SELECT 1
		                      FROM   paypal_msg
		                      WHERE  paypal_msg .pm_orderid = ConfirmLineInfo.COLI_ID
		                  )
		       )     T ,
		       (
		           SELECT pm .pm_orderid,
		                  eas.M_ToEmail ,
		                  pm.pm_sn ,
		                  pm.pm_create_date ,eas. M_SN
		           FROM   paypal_msg pm
		                  INNER JOIN Email_AutomaticSend eas
		                       ON  eas .M_ServiceSN = pm .pm_sn
		                       AND eas .M_Web = 'paypal msg'
		       )     P
				WHERE  t .COLI_ID = P .pm_orderid
		       AND t .OPI_Email <> p .M_ToEmail
    		   AND  DATEDIFF(m,p.pm_create_date,'" . $lastdate . "')<=3
				ORDER BY
		       p.pm_sn DESC ";
        }
        $result = $this->HT->query($sql);

        $result1 = $result->result();

        return $result1;
    }

    /*!
     * 调用数据库函数,生成实收金额
     * @author LYT <lyt@hainatravel.com>
     * @date   2017-11-03
     * @param  decimal(18,3)  $amount
     * @param  varchar(6)     $currency
     */
    public function get_ssje($amount, $pay_type='15002', $currency='USD')
    {
      $sql    = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje";
      $query  = $this->HT->query($sql,array($pay_type, $currency, $amount));
      $result = $query->result();
      if ( ! empty($result)) {
        return $result[0]->ssje;
      }
      return 0;
    }
    /*!
     * 更新订单主表付款方式,防止没访问thankyou-train.asp
     * @author LYT <lyt@hainatravel.com>
     * @date   2017-11-27
     */
    public function update_paymanner($COLI_SN, $paymanner = '15010')
    {
      $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner = ? WHERE COLI_SN=? ";
      $query = $this->HT->query($sql, array($paymanner, $COLI_SN));
      return $query;
    }
    //根据交易号获取收款记录(传统订单)
    public function get_money_t($pn_invoice) {
        $sql = "SELECT GroupAccountInfo.*
                from GroupAccountInfo
                where DeleteFlag=0 and GAI_AccreditNo=?
                ";
        $query = $this->HT->query($sql, array($pn_invoice));
        $result = $query->result();
        return $result;
    }
    //根据交易号获取收款记录(商务订单)
    public function get_money_b($pn_invoice) {
        $sql = "SELECT BIZ_GroupAccountInfo.*
                from BIZ_GroupAccountInfo
                where DeleteFlag=0 and ( GAI_AccreditNo=? or GAI_Memo=? )
                ";
        $query = $this->HT->query($sql, array($pn_invoice, $pn_invoice));
        $result = $query->result();
        return $result;
    }
    /** 删除收款记录 */
    public function delete_money_t($deadId)
    {
      $sql = "UPDATE GroupAccountInfo SET DeleteFlag=1 WHERE GAI_AccreditNo=?";
      $query = $this->HT->query($sql, array($deadId));
      return $query;
    }
    public function delete_money_b($deadId)
    {
      $sql = "UPDATE BIZ_GroupAccountInfo SET DeleteFlag=1 WHERE GAI_AccreditNo=?";
      $query = $this->HT->query($sql, array($deadId));
      return $query;
    }

    /** JJH: 添加订单收款记录之后执行 */
    public function exec_addToTask($GAI_SN)
    {
      $sql = " if not exists (
                  select top 1 1 from Sysautotask
                  where SAT_Type=1 and SAT_SourceSN=$GAI_SN
                ) exec SP_AddToSystask 1," . $GAI_SN;
      $query = $this->HT->query($sql);
      return $query;
    }

    /** 写入商务订单操作记录 */
    public function insert_biz_order_log($coli_sn, $log_info)
    {
        $db_column = array(
            "BOL_COLI_SN" => $coli_sn
            ,"BOL_OPI_SN" => 0
            ,"BOL_OPType" => $log_info
            ,"BOL_OPTime" => date('Y-m-d H:i:s')
            ,"BOL_Creator" => 0
            ,"BOL_CreateTime" => date('Y-m-d H:i:s')
        );
        return $this->HT->insert("BIZ_OrderOperationLog", $db_column);
    }

    public function get_trippest_order($tp_order='', $real_orderid='')
    {
        $sql = "SELECT top 1 * from BIZ_ConfirmLineInfo
                WHERE 1=1 ";
        $tp_order ? $sql.=" and COLI_PriceMemo like '%" . $this->HT->escape_str($tp_order) . "%' " : "";
        $real_orderid ? $sql.=" and COLI_ID='$real_orderid' " : "";
        return $this->HT->query($sql)->row();
    }

    public function get_advisor_detail($COLI_SN, $OPI_SN, $lgc=1)
    {
        $advisor_signature = $this->get_advisor_signature($COLI_SN);
        if (empty($advisor_signature)) {
            $sql = "SELECT OPI_SN, '+86-'+OPI_MoveTelephone mobile,'+86-773-'+OPI_Telephone tel,OPI_Email email,OPI2_Name fullname,OPI2_FirstName,OPI2_LastName
                      FROM [Tourmanager].[dbo].[V_Operator_Info]
                      where OPI_SN=? and LGC_LGC=? ";
            $advisor_signature = $this->HT->query($sql, array($OPI_SN, $lgc))->row();
        }
        return $advisor_signature;
    }
    public function get_advisor_signature($COLI_SN)
    {
        $sql = "SELECT top 1 dbo.agenter_user.Name fullname, dbo.agenter_user.tel,
                    dbo.agenter_user.Email email, dbo.agenter_user.mobile, OPI_DEI_SN, COLI_OPI_ID
                FROM dbo.BIZ_ConfirmLineInfo
                INNER JOIN dbo.agenter_user ON  dbo.BIZ_ConfirmLineInfo.COLI_OPI_ID = dbo.agenter_user.AU_OPI_SN
                    AND
                    (dbo.BIZ_ConfirmLineInfo.COLI_WebCode = dbo.agenter_user.agenter
                        OR (COLI_WebCode in ('EXPCH','MESENLLA','traba','wayaway','guias') and agenter='VAC')
                    )
                LEFT JOIN OperatorInfo on COLI_OPI_ID = OPI_SN
                WHERE (dbo.BIZ_ConfirmLineInfo.COLI_SN = ?)";
        return $this->HT->query($sql, array($COLI_SN))->row();
    }

    public function get_customer_detail($COLI_SN, $ordertype)
    {
        if ($ordertype === 'T') {
            $sql = "SELECT mei.MEI_FirstName+' '+isnull(mei.MEI_MiddleName,'')+' '+isnull(mei.MEI_LastName,'') fullname,
                        mei.MEI_MailList email
                    FROM MEmberInfo mei
                    INNER JOIN CUstomerList cul on mei.MEI_SN=cul.CUL_CUI_SN -- and cul.CUL_IsLinkMan=1
                    WHERE CUL_COLI_SN=?
                        and isnull(mei.MEI_MailList,'')<>''
                    order by cul.CUL_IsLinkMan desc";
            return $this->HT->query($sql, $COLI_SN)->row();
        } else {
            $sql = "SELECT GUT_FirstName+' '+GUT_LastName fullname,GUT_Email email from BIZ_GUEST g
                    INNER JOIN BIZ_ConfirmLineInfo coli on coli.COLI_GUT_SN=g.GUT_SN
                    WHERE COLI_SN=? ";
            return $this->HT->query($sql, $COLI_SN)->row();
        }
    }

    /*!
     * 调用数据库函数,转换为美金
     */
    public function get_USD($amount, $currency='RMB')
    {
      $sql    = "SELECT dbo.ConvertCurrencyToCurrency(?,?,?,?) as ssje";
      $query  = $this->HT->query($sql, array(1, mb_strtolower($currency), 'usd', $amount));
      $result = $query->result();
      if ( ! empty($result)) {
        return $result[0]->ssje;
      }
      return 0;
    }

    /*!
     * 查询财务系统中是否已导入该团的账单数据
     * @date   2019-05-14
     */
    public function if_finance_exists($gri_sn)
    {
        $sql = "SELECT top 1 1
                from financedata.dbo.CW_GroupZD gz
                inner join Tourmanager.dbo.CK_GroupInfo cgi on gz.GZD_CGI_SN=cgi.CGI_SN
                where ISNULL(GZD_DeleteFlag,0)=0 and isnull(DelFlag,0)=0
                and cgi.CGI_GRI_SN=? ";
        return $this->HT->query($sql, $gri_sn)->num_rows() > 0;
    }
    public function if_finance_done($gri_sn, $late_date)
    {
        $sql = "SELECT top 1 1
                from groupinfo gri
                where GRI_SN=?
                and GRI_EntranceDate < ?
        ";
        // 商务订单没有生成团信息
        if ($this->HT->query($sql, array($gri_sn,$late_date))->num_rows() === 0) {
            $sql = "SELECT top 1 1
            from BIZ_ConfirmLineInfo coli
            inner join BIZ_ConfirmLineDetail cold on COLD_COLI_SN=COLI_SN and isnull(cold.DeleteFlag,0)=0
            where COLI_GRI_SN=?
            and COLD_StartDate<?";
        }
        return $this->HT->query($sql, array($gri_sn,$late_date))->num_rows() > 0;
        // return false;
    }
}
