<?php

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

class Note_model extends CI_Model {

    var $topnum         = null;
    var $orderby        = null;
    var $send           = null;
    var $search         = null;
    var $date           = null;
    var $dealId         = null;
    var $payment_status = null;

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

    public function init() {
        $this->topnum         = null;
        $this->send           = null;
        $this->search         = null;
        $this->date           = null;
        $this->payment_status = null;
        $this->dealId         = null;
        $this->orderby        = ' ORDER BY IPL_sent DESC ,IPL_sn DESC ';
    }

    public function unsend($topnum = 2) {
        $this->init();
        $this->topnum = $topnum;
        $this->send = " AND (IPL_sent='unsend' OR IPL_sent='' OR IPL_sent IS NULL) ";
        return $this->get_list();
    }

    public function failnote($topnum = 2) {
        $this->init();
        $this->topnum = $topnum;
        $this->send = " AND IPL_sent='sendfail' ";
        return $this->get_list();
    }

    public function search_date($date) {
        $this->init();
        $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' ) ";
        $this->search = $search_sql;
        $this->send = " AND (IPL_sent<>'closeRecord') ";
        $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC ";
        return $this->get_list();
    }
    public function search_date2($date) {
        $this->init();
        $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' ) ";
        $this->date = $search_sql;
        $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC ";
        return $this->get_list_with_order();
    }

    public function note($txn_id, $pn_id=null){
        $this->init();
        $this->topnum=1;
        $this->dealId=" AND  IPL_dealId=".$this->INFO->escape($txn_id);
        $this->dealId .= ($pn_id===null) ? " " : "  AND IPL_sn=" . $pn_id;
        return $this->get_list();
    }

    public function note_order($orderid,$notice_time)
    {
        $this->init();
        $this->topnum=1;
        $this->dealId=" AND  IPL_orderId=".$this->INFO->escape($orderid)." AND IPL_noticeTime=".$this->INFO->escape($notice_time);
        return $this->get_list();
    }

    public function search_key($search_key) {
        $this->init();
        $this->topnum = 300; //限制最大数量，防止查询单词过短
        $search_sql = '';
        $search_key = trim($search_key);
        if (!empty($search_key)) {
            $search_sql.=" AND ( IPL_dealId = '$search_key'
                                    OR IPL_orderId like '%$search_key%'
                                    OR IPL_memo like '%$search_key%' )";
        }
        $this->search = $search_sql;
        return $this->get_list();
    }
    public function search_key2($search_key) {
        $this->init();
        $this->topnum = 300; //限制最大数量，防止查询单词过短
        $search_sql = '';
        $search_key = trim($search_key);
        if (!empty($search_key)) {
            $search_sql.=" AND ( IPL_dealId = '$search_key'
                                    OR IPL_orderId like '%$search_key%'
                                    OR IPL_memo like '%$search_key%' )";
        }
        $this->search = $search_sql;
        return $this->get_list_with_order();
    }

    public function note_exists($dealId)
    {
        $this->init();
        $this->topnum = 1;
        $this->search = " AND IPL_dealId = '".$dealId."' ";
        return $this->get_list();
    }

    /*!
     * 存储IPayLinks的实时通知
     * @author LYT <lyt@hainatravel.com>
     * @date   2017-08-29
     */
    public function save_ipl($IPL_dealId,$IPL_orderId,$IPL_currencyCode,$IPL_orderAmount,$IPL_payAmount,$IPL_stateCode,$IPL_acquiringTime,$IPL_completeTime,$IPL_memo,$IPL_payType,$IPL_resultCode=null,$IPL_resultMsg=null,$IPL_payerName=null,$IPL_payerEmail=NULL) {
        $sql = "
                INSERT INTO IPayLinksLog
                  (
                      IPL_dealId,IPL_orderId,IPL_currencyCode,IPL_orderAmount,IPL_payAmount,IPL_stateCode,IPL_acquiringTime,IPL_completeTime,IPL_memo,IPL_sent,IPL_noticeTime,IPL_payType,IPL_resultCode,IPL_resultMsg,IPL_payerName,IPL_payerEmail
                  )
                VALUES
                  (
                    ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,N?,N?,N?
                  )
        ";
        $query = $this->INFO->query($sql,
            array($IPL_dealId
                ,$IPL_orderId
                ,strtoupper($IPL_currencyCode)
                ,$IPL_orderAmount
                ,$IPL_payAmount
                ,$IPL_stateCode
                ,$IPL_acquiringTime
                ,$IPL_completeTime
                ,$IPL_memo
                ,$IPL_payType
                ,$IPL_resultCode
                ,$IPL_resultMsg
                ,$IPL_payerName
                ,$IPL_payerEmail
            ));
        $insertid = $this->INFO->last_id('IPayLinksLog');
        return $query;
    }

    public function get_list() {
        // $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT ";
        $this->topnum ? $top_sql = " TOP " . $this->topnum : $top_sql = " ";
        $sql = "SELECT $top_sql
                pn.*
            FROM   IPayLinksLog  pn
            WHERE 1=1
                and pn.IPL_payType='pay'
                and (pn.IPL_resultCode='0000')
                $this->send
                $this->search
                $this->dealId
                UNION ALL
                select $top_sql * from InfoManager.dbo.IPayLinksLog ipl2
                where 1=1
                and ipl2.IPL_payType='refund'
                and ipl2.IPL_stateCode=2
                $this->send
                $this->search
                $this->dealId
            $this->orderby
                ";

        $query = $this->INFO->query($sql);
        if ($this->topnum === 1) {
            if ($query->num_rows() > 0) {
                $row = $query->row();
                return $row;
            } else {
                return FALSE;
            }
        } else {
            return $query->result();
        }
    }

    /*!
     * 查询异步通知记录
     * isRecord
     * * 9999 已录入到订单收款记录表GAI;
     * * 99999 APP组的收款记录, 由他们手动处理
     * * 10000 已忽略的退款记录; 关闭检测是否记录[已忽略]
     * * 1 未录入到订单GAI
     * @date   2018-07-27
     * @return [type]     [description]
     */
    public function get_list_with_order()
    {
        $sql = "SELECT
                    -- gai.GAI_SN,
                    -- gaib.GAI_SN,
                    -- COLI.COLI_ID,IPL_payType='pay' and
                    -- when IPL_payType<>'pay' then 10000
                    case
                        when (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999
                        when IPL_payType='pay' and coli.COLI_ID is not null then 99999
                        when IPL_sent='closeRecord' then 10000
                        else 1
                    end isRecord,
                    ipl.*
                from InfoManager.dbo.IPayLinksLog ipl
                left join Tourmanager.dbo.BIZ_ConfirmLineInfo coli on coli.COLI_ID=ipl.IPL_orderId and coli.COLI_Department=16
                left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 --and ipl.IPL_payType='pay'
                left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 --and ipl.IPL_payType='pay'
                where 1=1
                    and ( (ipl.IPL_stateCode=2 and ipl.IPL_payType<>'pay') or (ipl.IPL_resultCode='0000' and ipl.IPL_payType='pay') )
                    $this->send
                    $this->search
                    $this->dealId
                    and (
                        1=1
                        $this->date
                        -- AND (IPL_noticeTime BETWEEN '2018-07-27 00:00:00' AND '2018-07-27 23:59:59' or IPL_sent<>'send')
                        or (
                            (
                                (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))=0 and COLI.COLI_ID is null
                                and IPL_sent not in ('send','closeRecord')
                            )
                            or ISNULL(IPL_sent,'') in ('sendfail','unsend','')
                        )
                    )
                order by isRecord asc,ipl.IPL_sent desc,IPL_sn desc";
        $query = $this->INFO->query($sql);
        if ($this->topnum === 1) {
            if ($query->num_rows() > 0) {
                $row = $query->row();
                return $row;
            } else {
                return FALSE;
            }
        } else {
            return $query->result();
        }
    }

    public function update_send($pn_txn_id, $pn_send) {
        $sql = "
            UPDATE IPayLinksLog
            SET    IPL_sent       = ?
            WHERE  IPL_dealId     = ?
      ";
        return $this->INFO->query($sql, array($pn_send, $pn_txn_id));
    }

    //设置订单号
    public function set_invoice($pn_txn_id, $pn_invoice) {
        $sql = "
            UPDATE IPayLinksLog
            SET    IPL_orderId = ?
            WHERE  IPL_dealId  = ?
      ";
        return $this->INFO->query($sql, array($pn_invoice, $pn_txn_id));
    }

    public function update_query($dealId,$stateCode,$payAmount)
    {
        $sql = "
            UPDATE IPayLinksLog
            SET IPL_stateCode = ?,
                IPL_payAmount  = ?
            where IPL_dealId = ?
        ";
        return $this->INFO->query($sql, array($stateCode,$payAmount,$dealId));
    }

    public function save_refund($dealId, $orderId, $refundAmount, $refundTime, $completeTime, $stateCode, $resultcode, $memo, $paytype)
    {
        $sql = "IF NOT EXISTS(
                    SELECT TOP 1 1
                    FROM   IPayLinksLog
                    WHERE  IPL_dealId = ? AND IPL_payType='refund'
                )
                INSERT INTO IPayLinksLog
                  (
                     IPL_dealId
                    ,IPL_orderId
                    ,IPL_orderAmount
                    ,IPL_stateCode
                    ,IPL_acquiringTime
                    ,IPL_completeTime
                    ,IPL_memo
                    ,IPL_sent
                    ,IPL_noticeTime
                    ,IPL_payType
                    ,IPL_resultCode
                  )
                VALUES
                  (
                    ?,?,?,?,?,?,?,'unsend',?,?,?
                  )
                ";
        $query = $this->INFO->query($sql,
            array($dealId
                ,$dealId
                ,$orderId
                ,$refundAmount
                ,$stateCode
                ,$refundTime
                ,$completeTime
                ,$memo
                ,$completeTime
                ,$paytype
                ,$resultcode
            ));
        return $query;
    }

    /** 插入实收金额更改记录日志 */
    public function new_warrant($warrant_arr = array())
    {
        $sql = "INSERT INTO PayWarrantLog
                    (PW_GAI_AccreditNo
                    ,PW_GAI_Type
                    ,PW_orderType
                    ,PW_COLI_SN
                    ,PW_GAI_SQJECurrency_pre
                    ,PW_GAI_SSJE_pre
                    ,PW_entry_currency
                    ,PW_entry_amount
                    ,PW_GAI_SSJE_new
                    ,PW_time)
                VALUES
                    (?
                    ,?
                    ,?
                    ,?
                    ,?
                    ,?
                    ,?
                    ,?
                    ,?
                    ,GETDATE()
                )";
        $query = $this->INFO->query($sql,array(
            $warrant_arr['PW_GAI_AccreditNo'],
            $warrant_arr['PW_GAI_Type'],
            $warrant_arr['PW_orderType'],
            $warrant_arr['PW_COLI_SN'],
            $warrant_arr['PW_GAI_SQJECurrency_pre'],
            $warrant_arr['PW_GAI_SSJE_pre'],
            $warrant_arr['PW_entry_currency'],
            $warrant_arr['PW_entry_amount'],
            $warrant_arr['PW_GAI_SSJE_new']
        ));
        return $query;
    }

    public function date_range($from, $to, $currency=NULL)
    {
        $this->init();
        $search_sql = " AND IPL_resultCode='0000' ";
        $search_sql .= " AND IPL_acquiringTime BETWEEN '$from 00:00:00' AND '$to 23:59:59' ";
        if ( ! empty($currency)) {
            $search_sql .= " AND IPL_currencyCode = '$currency' ";
        }
        $this->search  = $search_sql;
        $this->orderby = "";
        return $this->get_list();
    }

    public function test()
    {
        $sql = " ";
        $this->INFO->query($sql);
        return;
    }

}
