<?php

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

class IPayLinks_model extends CI_Model {

    private $HT;

    function __construct() {
        parent::__construct();
        $this->HT = $this->load->database('HT', 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_SN,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,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 COLI_ID like '%$COLI_ID' ";
            $query = $this->HT->query($sql);
            $result = $query->result();
        }

        //查传统订单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_money_list($GAI_COLI_ID, $GAI_SQJE, $GAI_SQJECurrency) {
        $sql = "SELECT GAI_SN,GAI_CusEmail,GAI_Memo
                FROM BIZ_GroupAccountInfo bgai
               WHERE bgai.GAI_COLI_ID = ? and GAI_SQJE=? and GAI_SQJECurrency=?
               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_AccreditNo = ?  OR  GAI_Memo LIKE '%$GAI_AccreditNo%')  and DeleteFlag=0 and GAI_Type=15018
               )
            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 (?,?,15018,?,?,?,?,?,?,?,N?,N?,?,?,0,0)";
        $query = $this->HT->query($sql, array($GAI_AccreditNo, $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
                    ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,N?,N?,?,?,0,0)";
        $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
                    ) VALUES (?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)";
        $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 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;
    }

    /*!
     * 调用数据库函数,生成实收金额
     * @author LYT <lyt@hainatravel.com>
     * @date   2017-11-03
     * @param  decimal(18,3)  $amount
     * @param  varchar(6)     $currency
     */
    public function get_ssje($amount, $currency='USD', $code='15018')
    {
      $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 0;
    }

    /*!
     * 更新订单主表付款方式,防止没访问thankyou-train.asp
     * @author LYT <lyt@hainatravel.com>
     * @date   2017-11-20
     */
    public function update_paymanner($COLI_SN)
    {
      $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner = '15018' WHERE COLI_SN=? ";
      $query = $this->HT->query($sql, array($COLI_SN));
      return $query;
    }

    //根据交易号获取收款记录(传统订单)
    public function get_money_t($pn_invoice) {
        $like = $this->HT->escape_like_str($pn_invoice);
        $sql = "SELECT COLI_ID,GroupAccountInfo.*
                from GroupAccountInfo
                inner join ConfirmLineInfo coli on COLI_SN=GAI_COLI_SN
                where GAI_Type='15018' and GroupAccountInfo.DeleteFlag=0 and (GAI_AccreditNo=? or GAI_Memo like '%$like%')
                ";
        $query = $this->HT->query($sql, array($pn_invoice));
        $result = $query->result();
        return $result;
    }
    //根据交易号获取收款记录(商务订单)
    public function get_money_b($pn_invoice) {
        $like = $this->HT->escape_like_str($pn_invoice);
        $sql = "SELECT COLI_ID,BIZ_GroupAccountInfo.*
                from BIZ_GroupAccountInfo
                inner join BIZ_ConfirmLineInfo on COLI_SN=GAI_COLI_SN
                where GAI_Type='15018' and BIZ_GroupAccountInfo.DeleteFlag=0 and (GAI_AccreditNo=? or GAI_Memo like '%$like%')
                ";
        $query = $this->HT->query($sql, array($pn_invoice));
        $result = $query->result();
        return $result;
    }
    // 根据对账单更新实收金额(传统订单)
    public function update_money_t($entry_sum_RMB, $pn_invoice)
    {
      $sql = "UPDATE GroupAccountInfo SET GAI_SSJE=? WHERE GAI_Type='15018' and GAI_AccreditNo=?";
      $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice));
      return $query;
    }
    // 根据对账单更新实收金额(商务订单)
    public function update_money_b($entry_sum_RMB, $pn_invoice) {
      $sql = "UPDATE BIZ_GroupAccountInfo SET GAI_SSJE=? WHERE GAI_Type='15018' and GAI_AccreditNo=?";
      $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice));
      return $query;
    }
    /** 删除收款记录 */
    public function delete_money_t($deadId)
    {
      $sql = "UPDATE GroupAccountInfo SET DeleteFlag=1 WHERE GAI_Type='15018' and 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_Type='15018' and 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_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 if_APP_order($order_id)
    {
        $sql = "SELECT top 1  1
                from BIZ_ConfirmLineInfo coli
                where COLI_ID=?
                and exists (
                    select 1 from OperatorInfo where OPI_SN=COLI_OPI_ID and OPI_DEI_SN=16
                )";
        return $this->HT->query($sql, array($order_id))->num_rows() > 0;
    }

    /*!
     * 调用数据库函数,转换为美金
     */
    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;
    }
}
