<?php

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

class Alipay_call
{
    protected $ci;

    public function __construct()
    {
        $this->ci =& get_instance();
        $this->ci->load->helper('payment');
        $this->ci->config->load('alipay', true);
        $this->ci->load->model('Online_payment_note_model', 'note_model');
        $this->ci->load->model('Online_payment_account_model', 'account_model');
    }
    /**
     */
    public function read_settlement_excel($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','total row' . PHP_EOL . var_export($allRow, 1));
        $col_titles = $this->settlement_excel_title();
        /**从第二行开始输出，因为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;
                }
                if ($currentColumn==='D' && !in_array(trim($val), array('交易', '交易退款'))) {
                    $row_tmp = array();
                    break;
                }
                $col_mean = $col_titles[$currentColumn];
                $row_tmp[$col_mean] = trim($val)==='-' ? '' : str_replace('`','',$val);
                $columnNum++;
            }
            if ( ! empty($row_tmp)) {
                $tarr1[] = $row_tmp;
            }
        }
        return $tarr1;
    }
    public function save_settlement_excel($excel_data)
    {
        $settle_cnt = 0;
        foreach ($excel_data as $settle) {
            $save_column = array();
            $save_column['OPN_accountMethod'] = $this->ci->config->item('method_code', 'alipay');
            $save_column['OPN_noticeType'] = trim($settle['trade_type']) === '交易' ? 'pay' : 'refund';
            $save_column['OPN_fundSource'] = 'cht';

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

            $save_column['OPN_orderAmount'] = bcsub(floatval($settle['trade_amount']),floatval($settle['refund_amount']));
            $save_column['OPN_orderId'] = $settle['orderid'];
            $note_exists = $this->ci->note_model->if_note_exists($settle['transaction_id']);
            // test:
            if (true === $note_exists) {
                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_subject'] = $settle['item_name'];
            $save_column['OPN_payAmount'] = $save_column['OPN_orderAmount'];
            $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'] = 'CNY'; // $settle['trade_currency'];
            $save_column['OPN_acquiringTime'] = $settle['complete_date'];
            $save_column['OPN_completeTime'] = $settle['complete_date'];
            $save_column['OPN_remark'] = $settle['remark'];
            $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;
    }
    /**
     * 入账时间	支付宝交易号	商户订单号	账务类型	收入（+元）	支出（-元）	商品名称	备注
     */
    private function settlement_excel_title()
    {
        return array(
            "A" => "complete_date",
            "B" => "transaction_id",
            "C" => "orderid",
            "D" => "trade_type",
            "E" => "trade_amount",
            "F" => "refund_amount",
            "G" => "item_name",
            "H" => "remark"
        );
    }


}

/* End of file Alipay_call.php */
