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

class Online_payment_note_model extends CI_Model {

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

    public function if_note_exists($transaction_id, $raw_id=null)
    {
        if ($transaction_id === null) {
            return null;
        }
        $order_sql = $raw_id===null ? " " : " AND OPN_rawOrderId='" . $raw_id . "'";
        $ret = "SELECT TOP 1 * FROM OnlinePaymentNote WHERE OPN_transactionId=? $order_sql ORDER BY OPN_SN DESC ";
        return $this->info->query($ret, array($transaction_id))->num_rows() > 0;
    }

    public function if_refund_exists($refund_id)
    {
        if ($refund_id === null) {
            return null;
        }
        $ret = "SELECT TOP 1 * FROM OnlinePaymentNote WHERE OPN_rawOrderId=? ORDER BY OPN_SN DESC ";
        return $this->info->query($ret, array($refund_id))->num_rows() > 0;
    }

    public function insert_note($column)
    {
        if ($column === null) {
            return false;
        }
        $this->info->insert('OnlinePaymentNote', $column);
        $ret = "SELECT TOP 1 * FROM OnlinePaymentNote WHERE OPN_transactionId=? ORDER BY OPN_SN DESC ";
        return $this->info->query($ret, array($column['OPN_transactionId']))->row();
    }

    public function update_note($where, $column)
    {
        $update_str = $this->info->update_string('OnlinePaymentNote', $column, $where);
        $this->info->query($update_str);
        return TRUE;
    }

    public function update_send($id, $transactionId, $send)
    {
        $column = array("OPN_noticeSendStatus" => $send, "OPN_noticeSendTime" => date('Y-m-d H:i:s'));
        $where = " OPN_transactionId = '$transactionId' AND OPN_SN=" . $id;
        return $this->update_note($where, $column);
    }

    //设置订单号
    public function set_invoice($id, $pn_invoice)
    {
        $column = array("OPN_orderId" => $pn_invoice);
        $where = " OPN_SN=" . $id;
        return $this->update_note($where, $column);
    }

    public function unsend_note($num=2, $method=null)
    {
        $this->init_query();
        $this->topnum = $num;
        // $this->send = " AND (OPN_noticeSendStatus='unsend' OR OPN_noticeSendStatus='' OR OPN_noticeSendStatus IS NULL) ";
        $this->search = $method===null ? "" : " AND OPN_accountMethod=$method ";

        $this->send = " AND ISNULL(OPN_noticeSendStatus,'') in ('', 'unsend') ";
        return $this->query_note();
    }

    public function closed_note($date, $num=2, $method=null)
    {
        $this->init_query();
        $this->topnum = $num;
        $this->send = " AND (OPN_noticeSendStatus) = 'closed' ";
        $this->search = $method===null ? "" : " AND OPN_accountMethod=$method ";
        $this->search .= " AND OPN_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' ";
        return $this->query_note();
    }

    public function sendfail_note($num=2, $method=null)
    {
        $this->init_query();
        $this->topnum = $num;
        $this->search = $method===null ? "" : " AND OPN_accountMethod=$method ";
        // 1小时前
        $date = date("Y-m-d H:i:s", time() - 3600);
        $this->search .= $num !== false ? " AND OPN_noticeSendTime < '$date' " : '';
        $this->send = " AND OPN_noticeSendStatus='sendfail'  ";
        return $this->query_note();
    }


    public $topnum         = false;
    public $orderby        = false;
    public $send           = false;
    public $search         = false;
    public $transactionId  = false;
    public $payment_status = false;
    // public $payment_method = false;

    public function init_query() {
        $this->topnum         = false;
        $this->send           = false;
        $this->search         = false;
        $this->payment_status = false;
        $this->transactionId  = false;
        // if ($GLOBALS['__PAYMENT_METHOD_CODE__']) {
        //     $this->payment_method = ' AND opn.OPN_accountMethod = ' . $GLOBALS['__PAYMENT_METHOD_CODE__'] . ' ';
        // }
        $this->orderby = ' ORDER BY OPN_SN DESC ';
    }

    public function query_note()
    {
        $top_sql = $this->topnum ? (" TOP " . $this->topnum) : "";
        $sql = "SELECT $top_sql opn.*
                 FROM [InfoManager].[dbo].[OnlinePaymentNote] opn
                 WHERE 1=1 ";
        // $this->payment_method ? $sql.=$this->payment_method : false;
        $this->send ? $sql.=$this->send : false;
        $this->search ? $sql.=$this->search : false;
        $this->transactionId ? $sql.=$this->transactionId : false;
        $this->orderby ? $sql.=$this->orderby : false;

        // log_message('error', PHP_EOL . $sql);

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

    public function get_note($opn_id)
    {
        $this->init_query();
        $this->topnum=1;
        $this->search = " AND opn.OPN_SN=" . $this->info->escape($opn_id);
        return $this->query_note();
    }

    public function search_key($keyword)
    {
        $this->init_query();
        $this->topnum = 300;
        $keyword = trim($keyword);
        $search_sql = "";
        if ( ! empty($keyword)) {
            $search_sql.=" AND ( OPN_transactionId = '$keyword'
                                    OR OPN_orderId like '%$keyword%'
                                    OR OPN_rawOrderId like '%$keyword%' )";
        }
        $this->search = $search_sql;
        return $this->query_note();
    }

    public function search_date($date, $method=null)
    {
        $this->init_query();
        $this->search = $method===null ? "" : " AND OPN_accountMethod=$method ";
        $this->search .= " AND OPN_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' ";
        $this->send = " AND isnull(OPN_noticeSendStatus,'') NOT IN ('', 'sendfail', 'unsend', 'closed' )";
        return $this->query_note();
    }

    /*!
     * 导出记录
     * @date   2019-04-28
     * @param  integer    $sn [description]
     */
    public function list_export_record($sn=0)
    {
        $search_sql = $sn===0 ? "" : " and TEL_SN=$sn ";
        $sql = "SELECT TOP 10 *
                FROM [InfoManager].[dbo].[Transaction_Export_Log]
                WHERE 1=1
                $search_sql
                order by TEL_SN desc";
        return $this->info->query($sql)->result();
    }

    public function query_ipalinkslog_memo($memo)
    {
        $sql = "SELECT *
        from IPayLinksLog
        where CHARINDEX(?,IPL_memo)>0";
        return $this->info->query($sql, array($memo))->row();
    }

    public function query_ipalinkslog_dealid($id)
    {
        $sql = "SELECT *
        from IPayLinksLog
        where IPL_dealId=?";
        return $this->info->query($sql, array($id))->row();
    }

    public function query_related($related_id)
    {
        $this->init_query();
        $this->search = " AND OPN_transactionId='$related_id' and OPN_accountType is not null ";
        return $this->query_note();
    }

    /**
     *
     * @param [type] $pay_method
     *
     * 选择日期:
     * @param [type] $from_date
     * @param [type] $to_date
     *
     * 环比日期:
     * @param [type] $from_date_fomer
     * @param [type] $to_date_former
     *
     * 上年同期:
     * @param [type] $from_date_year
     * @param [type] $to_date_year
     *
     * 本年度开始日期: {Year}-01-01
     * @param [type] $at_year
     */
    public function total_by_method($pay_method,
        $from_date, $to_date,
        $from_date_fomer, $to_date_former,
        $from_date_year, $to_date_year,
        $at_year
    )
    {
        $sql = " SET NOCOUNT ON;
        DECLARE @type varchar(10)='$pay_method'

        declare @this_year date='$at_year'
        declare @from_date date='$from_date'
        declare @to_date date='$to_date'

        declare @from_date_former date='$from_date_fomer'
        declare @to_date_former date='$to_date_former'

        declare @from_date_last_year date='$from_date_year'
        declare @to_date_last_year date='$to_date_year'

        declare @unique_opn table (
            id bigint IDENTITY(1,1) primary key,
            --opn_sn bigint,
            OPN_transactionId varchar(512),
            OPN_accountMethod varchar(100),
            OPN_noticeType varchar(100),
            OPN_currency varchar(100),
            OPN_orderAmount varchar(512),
            OPN_entryAmountCNY varchar(512),
            OPN_completeTime date
        )

        insert into @unique_opn (
            --opn_sn ,
            OPN_transactionId ,
            OPN_accountMethod ,
            OPN_noticeType ,
            OPN_currency ,
            OPN_orderAmount ,
            OPN_entryAmountCNY ,
            OPN_completeTime
        )
        select
            --opn_sn ,
            OPN_transactionId ,
            OPN_accountMethod ,
            OPN_noticeType ,
            OPN_currency ,
            OPN_orderAmount ,
            OPN_entryAmountCNY ,
            OPN_completeTime
        from InfoManager.dbo.OnlinePaymentNote
        where OPN_completeTime>@from_date_last_year
        group by
            --opn_sn ,
            OPN_transactionId ,
            OPN_accountMethod ,
            OPN_noticeType ,
            OPN_currency ,
            OPN_orderAmount ,
            OPN_entryAmountCNY ,
            OPN_completeTime

        SELECT  isnull(cal.select_date_method,ISNULL(cal.last_method,ISNULL(cal.year_method, cal.this_year_method ))) as OPN_accountMethod
                ,method_total_income,method_total_income_cmp
                ,isnull(year_method_total_income,0) year_method_total_income
                ,this_year_method_total_income
               --,REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, method_total_income), 1), '.00', '') method_total_income
               --,REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, method_total_income_cmp), 1), '.00', '') method_total_income_cmp
               ,case when ISNULL( method_total_income_cmp,0)=0 then 100 else CONVERT(decimal(10,2),
                        round( (method_total_income-method_total_income_cmp)/method_total_income_cmp*100 ,2 )
                ) end AS quarter_rate
               --,REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, isnull(year_method_total_income,0)), 1), '.00', '') year_method_total_income

               ,case when ISNULL( year_method_total_income,0)=0 then 100 else CONVERT(decimal(10,2),
                            round( (method_total_income-year_method_total_income)/year_method_total_income*100 ,2 )
                ) end AS year_rate
               --,REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, this_year_method_total_income), 1), '.00', '') this_year_method_total_income
        FROM
        (
            SELECT  *
            FROM
            (
                SELECT  OPN_accountMethod,OPN_accountMethod select_date_method
                       ,SUM(
                            ISNULL( CONVERT(decimal(10,2),OPN_entryAmountCNY),
                                    Tourmanager.dbo.GetSSJEFromSQJE(
                                        OPN_accountMethod,
                                        REPLACE(OPN_currency, 'CNY', 'RMB'),
                                        CONVERT(decimal(10,2),OPN_orderAmount)
                                    )
                                )
                            ) AS method_total_income
                FROM @unique_opn
                WHERE OPN_completeTime BETWEEN @from_date AND @to_date
                    and OPN_noticeType=@type
                GROUP BY  OPN_accountMethod
            ) AS method
            full join (
                SELECT  OPN_accountMethod last_method
                       ,SUM(
                            [Tourmanager].[dbo].ZeroToOne(
                            ISNULL( CONVERT(decimal(10,2),OPN_entryAmountCNY),
                                        Tourmanager.dbo.GetSSJEFromSQJE(
                                            OPN_accountMethod,
                                        REPLACE(OPN_currency, 'CNY', 'RMB'),
                                            CONVERT(decimal(10,2),OPN_orderAmount)
                                        )

                                )
                            )
                        ) AS method_total_income_cmp
                FROM @unique_opn
                WHERE OPN_completeTime BETWEEN @from_date_former AND @to_date_former
                    and OPN_noticeType=@type
                GROUP BY  OPN_accountMethod
            ) as cmp on method.OPN_accountMethod=cmp.last_method
            full join (
                SELECT  OPN_accountMethod year_method
                       ,SUM(
                            [Tourmanager].[dbo].ZeroToOne(
                            ISNULL( CONVERT(decimal(10,2),OPN_entryAmountCNY),
                                        Tourmanager.dbo.GetSSJEFromSQJE(
                                            OPN_accountMethod,
                                        REPLACE(OPN_currency, 'CNY', 'RMB'),
                                            CONVERT(decimal(10,2),OPN_orderAmount)
                                        )

                                )
                            )
                        ) AS year_method_total_income
                FROM @unique_opn
                WHERE OPN_completeTime BETWEEN @from_date_last_year AND @to_date_last_year
                    and OPN_noticeType=@type
                GROUP BY  OPN_accountMethod
            ) as year_cmp on isnull(method.OPN_accountMethod,cmp.last_method)=year_cmp.year_method
            full join (
                SELECT  OPN_accountMethod this_year_method
                       ,SUM(
                            [Tourmanager].[dbo].ZeroToOne(
                            ISNULL( CONVERT(decimal(10,2),OPN_entryAmountCNY),
                                        Tourmanager.dbo.GetSSJEFromSQJE(
                                            OPN_accountMethod,
                                        REPLACE(OPN_currency, 'CNY', 'RMB'),
                                            CONVERT(decimal(10,2),OPN_orderAmount)
                                        )

                                )
                            )
                        ) AS this_year_method_total_income
                FROM @unique_opn
                WHERE OPN_completeTime BETWEEN @this_year AND @to_date
                    and OPN_noticeType=@type
                GROUP BY  OPN_accountMethod
            ) as this_year_cmp on isnull(method.OPN_accountMethod,cmp.last_method)=this_year_cmp.this_year_method
        ) AS cal
        ";
        // var_dump($this->info->query($sql)); // 无法输出结果集
            include('c:/database_conn.php');
            $connection = array(
                'UID' => $db['HT']['username'],
                'PWD' => $db['HT']['password'],
                'Database' => 'tourmanager',
                'ConnectionPooling' => 1,
                'CharacterSet' => 'utf-8',
                'ReturnDatesAsStrings' => 1
            );
            $conn = sqlsrv_connect($db['HT']['hostname'], $connection);
            $stmt = sqlsrv_query($conn, $sql);
            //每一个select都会产生一个结果集，取某个结果集就需要从第一个移动到需要的那个结果集
            //如果结果集为空就移到下一个
            while (sqlsrv_has_rows($stmt) !== TRUE) {
                sqlsrv_next_result($stmt);
            }
            $result_object = array();
            while ($row = sqlsrv_fetch_object($stmt)) {
                $result_object[] = $row;
            }
            sqlsrv_free_stmt($stmt);
            sqlsrv_close($conn);
        return $result_object;
    }


}

