<?php

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

class Alipay_note_model extends CI_Model {

    var $topnum         = false;
    var $orderby        = false;
    var $send           = false;
    var $search         = false;
    var $dealId         = false;
    var $payment_status = false;

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

    public function init() {
        $this->topnum         = false;
        $this->send           = false;
        $this->search         = false;
        $this->payment_status = false;
        $this->dealId         = false;
        $this->orderby        = ' ORDER BY pn.ALI_sn DESC ';
    }

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

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

    public function search_date($date) {
        $this->init();
        $search_sql = " AND pn.ALI_acquiringTime BETWEEN '$date 00:00:00' AND '$date 23:59:59'
            OR isnull(ALI_sent,'') in ('sendfail','unsend','') ";
        $this->search = $search_sql;
        $this->orderby=" ORDER BY CASE pn.ALI_sent WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.ALI_sn DESC ";
        return $this->get_list();
    }

    public function note($txn_id){
        $this->init();
        $this->topnum=1;
        $this->dealId=" AND  pn.ALI_dealId=".$this->INFO->escape($txn_id);
        return $this->get_list();
    }

    public function note_order($orderid,$notice_time)
    {
        $this->init();
        $this->topnum=1;
        $this->dealId=" AND  pn.ALI_orderId=".$this->INFO->escape($orderid)." AND pn.ALI_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 ( pn.ALI_dealId = '$search_key'
                                    OR pn.ALI_orderId like '%$search_key%' )";
        }
        $this->search = $search_sql;
        return $this->get_list();
    }

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

    /*!
     * 存储实时通知
     * @author LYT <lyt@hainatravel.com>
     * @date   2017-08-29
     */
    public function save_alipay($ALI_dealId,$ALI_orderId,$ALI_currencyCode,$ALI_orderAmount,$ALI_payAmount,$ALI_stateCode,$ALI_acquiringTime,$ALI_completeTime,$ALI_memo,$ALI_payType,$ALI_resultCode=null,$ALI_resultMsg=null,$ALI_payerName=null,$ALI_payerEmail=NULL, $check_exists=false) {
        $sql = $check_exists===false ? "" : "
            IF NOT EXISTS(
                SELECT TOP 1 1
                FROM   AlipayLog
                WHERE  ALI_dealId = '$ALI_dealId'
            )
        ";
        $sql .= "
                INSERT INTO AlipayLog
                  (
                      ALI_dealId,ALI_orderId,ALI_currencyCode,ALI_orderAmount,ALI_payAmount,ALI_stateCode,ALI_acquiringTime,ALI_completeTime,ALI_memo,ALI_sent,ALI_noticeTime,ALI_payType,ALI_resultCode,ALI_resultMsg,ALI_payerName,ALI_payerEmail
                  )
                VALUES
                  (
                    ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,?,?,?
                  )
        ";
        // echo "<br><br>".$this->INFO->compile_binds($sql,
        $query = $this->INFO->query($sql,
            array($ALI_dealId
                ,$ALI_orderId
                ,strtoupper($ALI_currencyCode)
                ,$ALI_orderAmount
                ,$ALI_payAmount
                ,$ALI_stateCode
                ,$ALI_acquiringTime
                ,$ALI_completeTime
                ,$ALI_memo
                ,$ALI_payType
                ,$ALI_resultCode
                ,$ALI_resultMsg
                ,$ALI_payerName
                ,$ALI_payerEmail
            ));
        $insertid = $this->INFO->last_id('AlipayLog');
        $ret = "SELECT TOP 1 * FROM AlipayLog WHERE ALI_dealId='$ALI_dealId' ORDER BY ALI_sn DESC ";
        return $this->set_fundsource( $this->INFO->query($ret)->row());
    }

    public function get_list() {
        $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT ";
        $sql .= "
                pn.ALI_sn
                ,pn.ALI_dealId
                ,pn.ALI_orderId
                ,pn.ALI_currencyCode
                ,pn.ALI_orderAmount
                ,pn.ALI_payAmount
                ,pn.ALI_stateCode
                ,pn.ALI_resultCode
                ,pn.ALI_resultMsg
                ,pn.ALI_acquiringTime
                ,pn.ALI_completeTime
                ,pn.ALI_memo
                ,pn.ALI_sent
                ,pn.ALI_payType
                ,pn.ALI_noticeTime
                ,pn.ALI_payerName
                ,pn.ALI_payerEmail
            FROM   AlipayLog  pn
            WHERE 1=1
                 ";
        $this->send ? $sql.=$this->send : false;
        $this->search ? $sql.=$this->search : false;
        $this->dealId ? $sql.=$this->dealId : false;
        $this->orderby ? $sql.=$this->orderby : false;
        $query = $this->INFO->query($sql);
        if ($this->topnum === 1) {
            if ($query->num_rows() > 0) {
                $row = $query->row();
                $this->set_fundsource($row);
                return $row;
            } else {
                return FALSE;
            }
        } else {
            $result = $query->result();
            array_walk($result, 'Alipay_note_model::set_fundsource');
            return $result;
        }
    }

    private $code_fundsource = array(
        "2021004129643221" => "Trippest",
        "2017092108849921" => "", // "CHT",
    );
    public function set_fundsource(&$ele)
    {
        $ele->fundsource = "";
        $raw = json_decode($ele->ALI_memo);
        $app_id = isset($raw->app_id) ? $raw->app_id : '2017092108849921';
        if ($this->code_fundsource[$app_id]) {
            $ele->fundsource = $this->code_fundsource[$app_id];
        }
    }

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

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

    public function update_query($dealId,$payer)
    {
        $sql = "
            UPDATE AlipayLog
            SET ALI_payerEmail = ?
            where ALI_dealId = ?
        ";
        return $this->INFO->query($sql, array($payer,$dealId));
    }


}
