<?php

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

class Ipaylinks_call
{
    protected $ci;

    public function __construct()
    {
        $this->ci = &get_instance();
        $this->ci->load->helper('payment');
        $this->ci->config->load('ipaylinks', true);
        $this->ci->load->model('Online_payment_note_model', 'note_model');
        $this->ci->load->model('Online_payment_account_model', 'account_model');
    }

    public function save_excel_old($excel_data)
    {
        $settle_cnt = 0;
        foreach ($excel_data as $key => $settle) {
            // test:
            $note_exists = $this->ci->note_model->if_note_exists($settle['transaction_id'], $settle['orderid']);
            if (true === $note_exists) {
                continue;
            }
            $save_column = array();
            $save_column['OPN_accountMethod'] = $this->ci->config->item('method_code', 'ipaylinks');
            $save_column['OPN_invoiceId'] = $settle['orderid'];
            $save_column['OPN_orderId'] = $settle['orderid'];
            $save_column['OPN_orderAmount'] = $settle['order_amount'];
            if ($settle['data_type'] == '已清算退款' || $settle['data_type'] == '未清算退款') {
                // 退款
                // $ssje = $this->account_model->get_ssje($row['settlement_refund_fee'], str_replace("CNY", "RMB", strtoupper($row['currency_type'])), $save_column['OPN_accountMethod']);
                // $save_column['OPN_resultCode'] = $row['refund_status'];
                // $save_column['OPN_resultMsg'] = $row['refund_status'];
                // $save_column['OPN_entryAmountCNY'] = floatval("-" . $ssje);
                $save_column['OPN_noticeType'] = 'refund';
                $save_column['OPN_relatedId'] = $settle['transaction_id'];
                $save_column['OPN_transactionId'] = '';
                if (true === $this->ci->note_model->if_refund_exists($settle['orderid'])) {
                    continue;
                }
                $query_from_ipalinkslog = $this->ci->note_model->query_ipalinkslog_memo($settle['orderid']);
                if ( ! empty($query_from_ipalinkslog)) {
                    $save_column['OPN_transactionId'] = $query_from_ipalinkslog->IPL_dealId;
                    $save_column['OPN_invoiceId'] = $query_from_ipalinkslog->IPL_orderId;
                    $save_column['OPN_orderId'] = $query_from_ipalinkslog->IPL_orderId;
                }
                $related = $this->ci->note_model->query_related($save_column['OPN_relatedId']);
                if ( ! empty($related)) {
                    $save_column['OPN_orderId'] = $related[0]->OPN_orderId;
                    $save_column['OPN_accountType'] = $related[0]->OPN_accountType;
                }
            } elseif ($settle['data_type'] == '清算') {
                // 收款
                $save_column['OPN_noticeType'] = 'pay';
                $save_column['OPN_transactionId'] = $settle['transaction_id'];

                $note_exists = $this->ci->note_model->if_note_exists($settle['transaction_id'], $settle['orderid']);
                if (true === $note_exists) {
                    continue; // test:
                }
            } else {
                continue;
            }
            if ($save_column['OPN_transactionId']==='') {
                continue;
            }
            // test: 月账单太长
            if ($settle_cnt > 999) {
                break;
            }
            $order_info = $this->ci->account_model
                            ->get_gai(
                                $save_column['OPN_transactionId'],
                                $save_column['OPN_orderId'],
                                $save_column['OPN_orderAmount'],
                                $save_column['OPN_accountMethod']
                            );
            if ($order_info['data'] !== null) {
                $save_column['OPN_orderId'] = $order_info['data']->orderId;
                $save_column['OPN_accountType'] = $order_info['type'];
                $save_column['OPN_accountStatus'] = 'recorded';
            }
            $save_column['OPN_payAmount'] = $settle['order_amount'];
            $save_column['OPN_noticeSendStatus'] = 'closed';
            $save_column['OPN_transactionResult'] = 'completed';
            $save_column['OPN_rawOrderId'] = $settle['orderid'];
            $save_column['OPN_currency'] = $settle['currency'];
            $save_column['OPN_acquiringTime'] = date('Y-m-d H:i:s',strtotime($settle['complete_date']));
            $save_column['OPN_completeTime'] = date('Y-m-d H:i:s',strtotime($settle['complete_date']));
            $save_column['OPN_remark'] = $settle['mark_memo'];
            $save_column['OPN_fundSource'] = 'cht';
            $save_column['OPN_rawContent'] = json_encode($settle, JSON_UNESCAPED_UNICODE);
            $save_column['OPN_noticeTime'] = date('Y-m-d H:i:s');

            $note_exists = $this->ci->note_model->if_note_exists($settle['transaction_id'], $settle['orderid']);
            if (true === $note_exists) {
                continue; // test:
                // update
                $update_where = " OPN_transactionId='" . $settle['transaction_id'] . "' AND OPN_rawOrderId='" . $settle['orderid'] . "' ";
                $this->ci->note_model->update_note($update_where, $save_column) ;
                $settle_cnt++;
            } elseif (false === $note_exists) {
                // insert
                $this->ci->note_model->insert_note($save_column) ;
                $settle_cnt++;
            }
        }
        return $settle_cnt;
    }
    public function read_excel_old($filePath, $sheetIndex=0)
    {
        $tarr1=array();
        $this->ci->load->library('PHPExcel');
        $PHPExcel = new PHPExcel();
        /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)){
                echo 'no Excel';
                return ;
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet($sheetIndex);

        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();

        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
        log_message('error','all row ' . $allRow);
        $realRow = 0;
        $col_titles = $this->excel_title_old();
        /**从第二行开始输出，因为excel表中第一行为列名*/
        for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
            $row_tmp = array();
            /**从第A列开始输出*/
            for($currentColumn= 'A';$currentColumn<= "N"; $currentColumn++){
                /**ord()将字符转为十进制数*/
                $val = trim($currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue());
                $col_mean = $col_titles[$currentColumn];
                if($col_mean == 'data_type' && in_array($val, $this->no_store_deal_type()) )
                {
                    break;
                }
                if ($col_mean == 'orderid' && strcasecmp('-', $val) === 0) {
                    break;
                }
                $row_tmp[$col_mean] = $val;
            }
            if (isset($row_tmp['settlement_amount'])) {
                $tarr1[] = $row_tmp;
                $realRow++;
            }
        }
        log_message('error','real row ' . $realRow);
        return $tarr1;
    }
    private function no_store_deal_type()
    {
        return array(
            "归还保证金"
            // ,"记账"
            ,"冻结"
            ,"解冻"
            ,"提现"
            ,"提现手续费"
            ,"单笔处理费"
            ,"退款手续费"
        );
    }
    private function excel_title_old()
    {
        return array(
            "A" => "complete_date",
            "B" => "transaction_id",
            "C" => "orderid",
            "D" => "data_type",
            "E" => "currency",
            "F" => "order_amount",
            "G" => "settlement_rate",
            "H" => "settlement_amount",
            "I" => "service_fee",
            "J" => "transaction_fee",
            "K" => "mark_memo",
            "L" => "entry_currency",
            "M" => "entry_security",
            "N" => "entry_basic"
        );
    }

    public function save_excel_new($excel_data)
    {
        $settle_cnt = 0;
        foreach ($excel_data as $settle) {
            $save_column = array();
            $save_column['OPN_accountMethod'] = $this->ci->config->item('method_code', 'ipaylinks');
            $save_column['OPN_noticeType'] = trim($settle['trade_type']) === '消费' ? 'pay' : 'refund';
            $save_column['OPN_fundSource'] = trim($settle['site_id']) === 'www.chinahighlights.com' ? 'cht' : 'app';

            $save_column['OPN_transactionId'] = $settle['transaction_id'];
            $save_column['OPN_relatedId'] = str_ireplace("-", '', $settle['related_id']);

            $save_column['OPN_orderAmount'] = $settle['trade_amount'];
            $save_column['OPN_orderId'] = $settle['orderid'];
            $note_exists = $this->ci->note_model->if_note_exists($settle['transaction_id'], $settle['orderid']);
            if (true === $note_exists) {
                continue; // test:
            }
            // test: 月账单太长
            if ($settle_cnt > 999) {
                break;
            }
            $order_info = $this->ci->account_model
                            ->get_gai(
                                $save_column['OPN_transactionId'],
                                $save_column['OPN_orderId'],
                                $save_column['OPN_orderAmount'],
                                $save_column['OPN_accountMethod']
                            );
            if ($order_info['data'] !== null) {
                $save_column['OPN_orderId'] = $order_info['data']->orderId;
                $save_column['OPN_accountType'] = $order_info['type'];
                $save_column['OPN_accountStatus'] = 'recorded';
            }
            $save_column['OPN_payAmount'] = $settle['trade_amount'];
            $save_column['OPN_noticeSendStatus'] = 'closed';
            $save_column['OPN_transactionResult'] = 'completed';
            $save_column['OPN_rawOrderId'] = $settle['orderid'];
            $save_column['OPN_invoiceId'] = $settle['orderid'];
            $save_column['OPN_currency'] = $settle['trade_currency'];
            $save_column['OPN_acquiringTime'] = date('Y-m-d H:i:s',strtotime($settle['complete_date']));
            $save_column['OPN_completeTime'] = date('Y-m-d H:i:s',strtotime($settle['complete_date']));
            $save_column['OPN_remark'] = str_ireplace("-", '', $settle['apply_pay_type']) . "_" . str_ireplace("-", '', $settle['trade_region']) . "_" . str_ireplace("-", '', $settle['card_issuers']) . "_" . str_ireplace("-", '', $settle['card_bin_country']) . "_" . str_ireplace("-", '', $settle['card_type']);
            $save_column['OPN_rawContent'] = json_encode($settle, JSON_UNESCAPED_UNICODE);
            $save_column['OPN_noticeTime'] = date('Y-m-d H:i:s');

            $note_exists = $this->ci->note_model->if_note_exists($settle['transaction_id'], $settle['orderid']);
            if (true === $note_exists) {
                // update
                $update_where = " OPN_transactionId='" . $settle['transaction_id'] . "' AND OPN_rawOrderId='" . $settle['orderid'] . "' ";
                $this->ci->note_model->update_note($update_where, $save_column) ;
                $settle_cnt++;
            } elseif (false === $note_exists) {
                // insert
                $this->ci->note_model->insert_note($save_column) ;
                $settle_cnt++;
            }
        }
        return $settle_cnt;
    }

    public function read_excel_new($filePath, $sheetIndex=0)
    {
        $tarr1=array();
        $this->ci->load->library('PHPExcel');
        $PHPExcel = new PHPExcel();
        /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)){
                echo 'no Excel';
                return ;
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet($sheetIndex);

        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();
        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();

        log_message('error','all row ' . $allRow);

        $col_titles = $this->excel_title_new();
        /**从第二行开始输出，因为excel表中第一行为列名*/
        for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
            $row_tmp = array();
            /**从第A列开始输出*/
            $columnNum = 0;
            // for($currentColumn= 'A';$currentColumn<= "AD"; $currentColumn++){
            // 列标题Z之后的不能直接用逻辑运算
            for($currentColumn= 'A';str_pad($currentColumn, 2, "0", STR_PAD_LEFT)<= $allColumn; $currentColumn++){
                /**ord()将字符转为十进制数*/
                // $val = trim($currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue());
                // 列标题Z之后不能直接用ord计算ASCII码,因ord仅返回第一个字符的结果导致列AA的值读取到列A
                $val = trim($currentSheet->getCellByColumnAndRow($columnNum,$currentRow)->getValue());
                if ( ! isset($col_titles[$currentColumn])) {
                    continue;
                }
                $col_mean = $col_titles[$currentColumn];
                $row_tmp[$col_mean] = trim($val)==='-' ? '' : $val;
                $columnNum++;
            }
            $tarr1[] = $row_tmp;
        }
        return $tarr1;
    }
    private function excel_title_new()
    {
        return array(
            "A" => "complete_date",
            "B" => "transaction_id",
            "C" => "related_id",
            "D" => "orderid",
            "E" => "site_id",
            "F" => "local_channel",
            "G" => "apply_pay_type",
            "H" => "trade_region",
            "I" => "card_issuers",
            "J" => "card_bin_country",
            "K" => "card_type",
            "L" => "trade_type",
            "M" => "trade_currency",
            "N" => "trade_amount",
            "O" => "settlement_currency",
            "P" => "settlement_amount",
            "Q" => "service_fee",
            "R" => "trade_fee",
            "S" => "chargeback_fee",
            "T" => "security_amount",
            "U" => "system_fee",
            "V" => "refund_fee",
            "W" => "3d_fee",
            "X" => "extra_info1",
            "Y" => "extra_info2",
            "Z" => "extra_info3",
            "AA" => "extra_info4",
            "AB" => "extra_info5",
            "AC" => "basic_account_entry_amount",
            "AD" => "security_account_entry_amount"
        );
    }
}

/* End of file Ipaylinks_call.php */
