<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Online_payment_account_model extends CI_Model {

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

    /*!
     * 调用数据库函数,生成实收金额
     * @author LYT <lyt@hainatravel.com>
     */
    public function get_ssje($amount, $currency='USD', $code)
    {
      $sql    = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje";
      $query  = $this->HT->query($sql,array($code, $currency, $amount));
      $result = $query->result();

      if ( ! empty($result)) {
        return $result[0]->ssje;
      }
      return NULL;
    }

    //根据订单号获取外联邮箱
    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' || $ordertype == 'TP') {
            $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,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,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo
                           LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN
                   where COLI_ID like '%$COLI_ID'
                   order by CHARINDEX('$COLI_ID', COLI_ID)  ";
            $query = $this->HT->query($sql);
            $result = $query->result();
            if ($handpick === TRUE) {
              $result = empty($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,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,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,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) {
        $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 if_biz_gai_exists($GAI_AccreditNo, $is_app=false, $coli_sn=null, $je=null, $type=null)
    {
        if ($is_app===true && $coli_sn!==null) {
            $sql = " SELECT TOP 1 1
                    FROM   BIZ_GroupAccountInfo
                    WHERE  GAI_COLI_SN = ? AND GAI_SQJE=? AND DeleteFlag=0 AND GAI_Type=?";
            $result = $this->HT->query($sql, array($coli_sn, $je, $type));
            return ($result->num_rows() > 0);
        }
        $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);
    }

    //修改订单状态
    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,9,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 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);
    }

    /*!
     * 更新订单主表付款方式,防止没访问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_gai($t_id, $order=null, $amount=null, $type=null)
    {
        $ret = array("type"=> null, "data"=>null);
        $result_t = $this->get_money_t($t_id);
        $result_b = $this->get_money_b($t_id, $order, $amount, $type);
        if ( ! empty($result_t)) {
            $ret['type'] = 'T';
            $ret['data'] = $result_t[0];
        } else if ( ! empty($result_b)) {
            $ret['type'] = 'B';
            $ret['data'] = $result_b[0];
        }
        return $ret;
    }

    //根据交易号获取收款记录(传统订单)
    public function get_money_t($pn_invoice) {
        $sql = "SELECT COLI_ID orderId, g.*
                from GroupAccountInfo g
                inner join Tourmanager.dbo.ConfirmLineInfo on g.GAI_COLI_SN=COLI_SN
                where g.DeleteFlag=0 and g.GAI_AccreditNo=?
                ";
        $query = $this->HT->query($sql, array($pn_invoice));
        $result = $query->result();
        return $result;
    }
    //根据交易号获取收款记录(商务订单)
    public function get_money_b($t_id, $raw_order=null, $amount=null, $payment_type=null) {
        $sql = "SELECT COLI_ID orderId, g.*
                from BIZ_GroupAccountInfo g
                inner join Tourmanager.dbo.BIZ_ConfirmLineInfo on g.GAI_COLI_SN=COLI_SN
                where g.DeleteFlag=0 and g.GAI_AccreditNo=?
                ";
        $query = $this->HT->query($sql, array($t_id));
        $result = $query->result();
        if (empty($result)) {
            $raw_order_sql = "SELECT COLI_ID orderId, g.*
            from BIZ_GroupAccountInfo g
            inner join Tourmanager.dbo.BIZ_ConfirmLineInfo on g.GAI_COLI_SN=COLI_SN
            where g.DeleteFlag=0 and COLI_ID=? and g.GAI_SQJE=? and g.GAI_Type=?
            ";
            $query = $this->HT->query($raw_order_sql, array($raw_order, $amount, $payment_type));
            $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;
    }

    //添加收款记录(商务订单)
    public function add_account_info($GAI_COLI_SN, $payment_method, $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_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_SSJE
                       ,GAI_SSDate
                       ,GAI_AccountDate
                       ,GAI_SubmitDate
                       ,GAI_CusName
                       ,GAI_CusEmail
                       ,GAI_AccreditNo
                       ,GAI_Memo
                       ,GAI_State
                       ,DeleteFlag
                    ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0)";
        $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $payment_method, $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;
    }

    //添加收款记录(商务订单),APP会自动增加记录，所以添加前根据金额来判断是否有重复记录
    public function add_account_info_forAPP($GAI_COLI_SN, $payment_method, $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 GAI_SQJE=? AND DeleteFlag=0 AND GAI_Type=?
               )
            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
                    ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0)";
        $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $payment_method, $GAI_COLI_SN, $GAI_COLI_ID, $payment_method, $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_tour_account_info($GAI_COLI_SN, $payment_method, $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
                    ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0,0)";
        $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $payment_method, $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;
    }

    /** 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 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;
    }

    /*!
     * 查询财务系统中是否已导入该团的账单数据
     * @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, array($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;
    }

    /*!
     * 查询标记为需要发送财务的退款记录send-to-finance
     * TODO 异步通知合并
     * @date   2019-05-15
     */
    public function get_refund_imported()
    {
        $ret = array();
        $send_flag = "send-to-finance";
        $paypal_sql = "SELECT 'paypal' as payment_type,
                        pn_sn note_sn,pn_txn_id transaction_id,
                                (select DEI_DepartmentName from OperatorInfo inner join DepartmentInfo on OPI_DEI_SN=DEI_SN
                                where OPI_SN=ISNULL(table_t.COLI_OPI_ID, isnull(table_b.COLI_OPI_ID,table_app.COLI_OPI_ID))
                            ) as department,
                                case when ISNULL(table_t.COLI_GRI_SN,table_b.COLI_GRI_SN) is null
                                then isnull(table_app.COLI_GroupCode,table_app.COLI_ID)
                                else (select GRI_Name from GRoupInfo
                                        where gri_sn=ISNULL(table_t.COLI_GRI_SN,table_b.COLI_GRI_SN)
                            ) end as gri_name,
                            pn.pn_payment_date payment_date,
                            pn.pn_mc_gross amount,pn_mc_currency currency,
                            isnull(table_t.GAI_SSJE,isnull(table_b.GAI_SSJE,table_app.GAI_SSJE)) amount_CNY,
                            pn_payer payer,pn_payer_email payer_email
                        from paypal_note pn
                        left join (
                                select gai.GAI_SSJE,gai.GAI_AccreditNo ,coli.COLI_GRI_SN,coli.COLI_OPI_ID,coli.COLI_SN
                                from GroupAccountInfo gai inner join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN
                            ) as table_t on table_t.GAI_AccreditNo=pn.pn_txn_id
                        left join (
                                select bgai.GAI_AccreditNo,bgai.GAI_SSJE ,bcoli.COLI_GRI_SN,bcoli.COLI_OPI_ID,bcoli.COLI_SN
                                from BIZ_GroupAccountInfo bgai inner join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN
                            ) as table_b on table_b.GAI_AccreditNo=pn.pn_txn_id
                        left join (
                                select bgai.GAI_AccreditNo,bgai.GAI_SSJE,bgai.GAI_SQJE,bgai.GAI_SQJECurrency ,bcoli.COLI_GRI_SN,bcoli.COLI_OPI_ID,bcoli.COLI_SN ,bcoli.COLI_id ,bcoli.COLI_GroupCode
                                from BIZ_GroupAccountInfo bgai inner join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN
                            ) as table_app on table_app.COLI_ID=REPLACE ( pn_invoice , '_B' , '' )
                                and pn.pn_mc_gross=table_app.GAI_SQJE and pn.pn_mc_currency=table_app.GAI_SQJECurrency
                        where pn_send='$send_flag'
                        order by department ";
        $ret = $paypal_list = $this->HT->query($paypal_sql)->result_array();
        $ipaylinks_sql = "SELECT 'ipaylinks' as 'payment_type', IPL_sn note_sn,IPL_dealId transaction_id,
                                (select DEI_DepartmentName from OperatorInfo inner join DepartmentInfo on OPI_DEI_SN=DEI_SN
                                where OPI_SN=ISNULL(table_t.COLI_OPI_ID, isnull(table_b.COLI_OPI_ID,table_app.COLI_OPI_ID))
                            ) as department,
                                case when ISNULL(table_t.COLI_GRI_SN,table_b.COLI_GRI_SN) is null
                                then isnull(table_app.COLI_GroupCode,table_app.COLI_ID)
                                else (select GRI_Name from GRoupInfo
                                        where gri_sn=ISNULL(table_t.COLI_GRI_SN,table_b.COLI_GRI_SN)
                            ) end as gri_name,
                            pn.IPL_completeTime payment_date,
                            pn.IPL_orderAmount amount,
                            isnull(IPL_currencyCode,isnull(table_t.GAI_SQJECurrency,isnull(table_b.GAI_SQJECurrency,table_app.GAI_SQJECurrency))) currency,
                            isnull(table_t.GAI_SSJE,isnull(table_b.GAI_SSJE,table_app.GAI_SSJE)) amount_CNY,
                            isnull(IPL_payerName,isnull(table_t.GAI_CusName,isnull(table_b.GAI_CusName,table_app.GAI_CusName))) payer,
                            isnull(IPL_payerEmail,ISNULL(table_t.gai_cusEmail,isnull(table_b.gai_cusemail,table_app.gai_cusemail))) payer_email
                        from InfoManager.dbo.IPayLinksLog pn
                        left join (
                                select gai.GAI_SQJECurrency,gai.GAI_CusName,gai.gai_cusEmail, gai.GAI_SSJE,gai.GAI_AccreditNo ,coli.COLI_GRI_SN,coli.COLI_OPI_ID,coli.COLI_SN
                                from GroupAccountInfo gai inner join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN
                            ) as table_t on table_t.GAI_AccreditNo=pn.IPL_dealId
                        left join (
                                select bgai.GAI_AccreditNo,bgai.GAI_CusName,bgai.gai_cusEmail,bgai.GAI_SQJECurrency,bgai.GAI_SSJE ,bcoli.COLI_GRI_SN,bcoli.COLI_OPI_ID,bcoli.COLI_SN
                                from BIZ_GroupAccountInfo bgai inner join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN
                            ) as table_b on table_b.GAI_AccreditNo=pn.IPL_dealId
                        left join (
                                select bgai.GAI_AccreditNo,bgai.GAI_CusName,bgai.gai_cusEmail,bgai.GAI_SSJE,bgai.GAI_SQJE,bgai.GAI_SQJECurrency ,bcoli.COLI_GRI_SN,bcoli.COLI_OPI_ID,bcoli.COLI_SN ,bcoli.COLI_id ,bcoli.COLI_GroupCode
                                from BIZ_GroupAccountInfo bgai inner join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN
                            ) as table_app on table_app.COLI_ID=REPLACE ( IPL_orderId , '_B' , '' )
                                and pn.IPL_orderAmount=table_app.GAI_SQJE and pn.IPL_currencyCode=table_app.GAI_SQJECurrency
                        where IPL_sent='$send_flag'
                        order by department ";
        $ipaylinks_list = $this->HT->query($ipaylinks_sql)->result_array();
        empty($ipaylinks_list) ? $ipaylinks_list=array() : false;
        $alipay_sql = "SELECT 'alipay' as 'payment_type', ALI_sn note_sn,ALI_dealId transaction_id,
                            (select DEI_DepartmentName from OperatorInfo inner join DepartmentInfo on OPI_DEI_SN=DEI_SN
                            where OPI_SN=ISNULL(table_t.COLI_OPI_ID, isnull(table_b.COLI_OPI_ID,table_app.COLI_OPI_ID))
                        ) as department,
                            case when ISNULL(table_t.COLI_GRI_SN,table_b.COLI_GRI_SN) is null
                            then isnull(table_app.COLI_GroupCode,table_app.COLI_ID)
                            else (select GRI_Name from GRoupInfo
                                    where gri_sn=ISNULL(table_t.COLI_GRI_SN,table_b.COLI_GRI_SN)
                        ) end as gri_name,
                        pn.ALI_completeTime payment_date,
                        pn.ALI_orderAmount amount,
                        isnull(ALI_currencyCode,isnull(table_t.GAI_SQJECurrency,isnull(table_b.GAI_SQJECurrency,table_app.GAI_SQJECurrency))) currency,
                        isnull(table_t.GAI_SSJE,isnull(table_b.GAI_SSJE,table_app.GAI_SSJE)) amount_CNY,
                        isnull(ALI_payerName,isnull(table_t.GAI_CusName,isnull(table_b.GAI_CusName,table_app.GAI_CusName))) payer,
                        isnull(ALI_payerEmail,ISNULL(table_t.gai_cusEmail,isnull(table_b.gai_cusemail,table_app.gai_cusemail))) payer_email
                    from InfoManager.dbo.AlipayLog pn
                    left join (
                            select gai.GAI_SQJECurrency,gai.GAI_CusName,gai.gai_cusEmail, gai.GAI_SSJE,gai.GAI_AccreditNo ,coli.COLI_GRI_SN,coli.COLI_OPI_ID,coli.COLI_SN
                            from GroupAccountInfo gai inner join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN
                        ) as table_t on table_t.GAI_AccreditNo=SUBSTRING( pn.ALI_dealId,0,31)
                    left join (
                            select bgai.GAI_AccreditNo,bgai.GAI_CusName,bgai.gai_cusEmail,bgai.GAI_SQJECurrency,bgai.GAI_SSJE ,bcoli.COLI_GRI_SN,bcoli.COLI_OPI_ID,bcoli.COLI_SN
                            from BIZ_GroupAccountInfo bgai inner join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN
                        ) as table_b on table_b.GAI_AccreditNo=SUBSTRING( pn.ALI_dealId,0,31)
                    left join (
                            select bgai.GAI_AccreditNo,bgai.GAI_CusName,bgai.gai_cusEmail,bgai.GAI_SSJE,bgai.GAI_SQJE,bgai.GAI_SQJECurrency ,bcoli.COLI_GRI_SN,bcoli.COLI_OPI_ID,bcoli.COLI_SN ,bcoli.COLI_id ,bcoli.COLI_GroupCode
                            from BIZ_GroupAccountInfo bgai inner join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN
                        ) as table_app on table_app.COLI_ID=REPLACE ( REPLACE ( ALI_orderId , '_A' , '' )  , '_B' , '' )
                            and pn.ALI_orderAmount=table_app.GAI_SQJE --and pn.ALI_currencyCode=table_app.GAI_SQJECurrency
                    where ALI_sent ='$send_flag'
                    order by department  ";
        $alipay_list = $this->HT->query($alipay_sql)->result_array();
        empty($alipay_list) ? $alipay_list=array() : false;
        $ret = array_merge($paypal_list, $ipaylinks_list, $alipay_list);
        return $ret;
    }

    public function update_send_fiance($note_sn, $payment_type)
    {
        $sql = "";
        switch ($payment_type) {
            case 'paypal':
                $sql = " UPDATE Tourmanager.dbo.paypal_note SET pn_send = 'send-finance' WHERE pn_sn = ? ";
                break;
            case 'ipaylinks':
                $sql = " UPDATE InfoManager.dbo.IPayLinksLog SET IPL_sent = 'send-finance' WHERE IPL_sn = ? ";
                break;
            case 'alipay':
                $sql = " UPDATE InfoManager.dbo.AlipayLog SET ALI_sent = 'send-finance' WHERE ALI_sn = ? ";
                break;

            default:
                # code...
                break;
        }
        if ($sql==="") {return false;}
        return $this->HT->query($sql, $note_sn);
    }

    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();
        }
    }

}

