<?php
require_once "vendor/autoload.php";
include_once __DIR__."/config.php";
use PhpOffice\PhpSpreadsheet\Reader\Csv;

/**
 * Read an excel file and return an array of excel cell data.
 * @param $file: excel file to read.
 * @return array
 */
function readMyExcel($file): array
{
    //$inputFileName = dirname(__FILE__) . '/xls/fz20180501-20190101.xls';
    //$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
    $reader = new Csv();
    $reader->setInputEncoding("CP936");
    //$reader->setCodepage("CP936");
    $excel = $reader->load($file);
    return $excel->getActiveSheet()->toArray(null,true,true,false);
}

/**
 * Upload excel data to mysql table trade_record
 * @param $data: array which get from excel file.
 * @param $company: 证券公司名
 * @return array: msg
 */
function dbOp($data,$company)
{
    $mysqli = get_mysqli_connection();
    $maxrow = count($data);
    $maxcol = count($data[0]);
    $msg = array();
    for ($row = 0; $row < $maxrow; $row++) {
        if ($row == 0) {
            //检查文件与证券公司是否匹配
            if(($data[$row][4]=='买卖标志' and $company=='方正证券') or ($data[$row][4]=='操作' and $company=='长江证券'))
                continue; //skip 1st row;
            else{
                echo json_encode(array(
                    "status" => "-1",
                    "row1"=> $data[$row],
                    'company'=> $company,
                    "msg" => "文件格式不正确或与证券公司不匹配，请重试！",
                ));
                return false;
            }
        }

        //处理时间字段, 方正证券格式: hhmmss需要特别处理， 长江证券时间格式正常: hh:mm:ss
        $tm = $data[$row][1]; //format $time
        if ($tm == 0) $data[$row][1] = '00:00:00';
        elseif($company=='方正证券') $data[$row][1] = substr($tm, 0, -4) . ':' . substr($tm, -4, 2) . ':' . substr($tm, -2);

        //处理长江证券的改动：去掉item 9，15，重置键名
        if($company=='长江证券'){
            unset($data[$row][9]);
            unset($data[$row][15]);
            $data[$row]=array_values($data[$row]);
            $maxcol = count($data[$row]); //重置 maxcol
        }
        /**
         *  addslashes处理
         * 方正证券14 其他费用，15：备注（需要处理）
         * 长江证券14备注（需要处理），15：交易市场
         */
        $data[$row][14] = addslashes($data[$row][14]); // add slash avoid sql clash
        $data[$row][15] = addslashes($data[$row][15]); // add slash avoid sql clash

        // duplicate check for each row
        if (recordDupCheck($data[$row], $mysqli,$company)) {
            $msg[] = addslashes("Row <span style='color:#ff0000'> $row </span> exist. Skip!<br />");
            continue;
        }
        //else var_dump($data[$row]);

        $values = ''; //initial $values;
        for ($col = 0; $col < $maxcol; $col++) {
            $values .= "'" . $data[$row][$col] . "',";
        }

        $values = rtrim($values, ','); //如果需要，此行去除末尾逗号(,)
        if($company=='方正证券') {
            $sql = <<<EOF
            insert into 
            trade_record(
                         `tdate`,`ttime`, `ts_code`, `ts_name`, `flg`, `tprice`, `tvol`, 
                         `trade_id`, `entrust_id`, `holder_code`, `tamount`, `commission`, 
                         `tax1`, `tax2`, `tax3`, `note`, `t_vendor`)
            values(
                   $values,
                   '$company'
            )
EOF;
        }elseif($company=='长江证券'){
            $sql = <<< EOF
            insert into 
            trade_record_cj(
                            `tdate`, `ttime`, `ts_code`, `ts_name`, `flg`, `tvol`, `tprice`,
                            `tamount`, `entrust_id`, `trade_id`, `tax1`, `tax2`, `tax3`, 
                            `ttl_amount`, `note`, `trade_mkt`, `uaccount`, `t_vendor`)
            values(
                   $values,
                   '$company'
            )
EOF;
        }
        $mysqli->query($sql) or die("Data upload failure: " . $sql);
        unset($values); //release $values;
        $msg[] = addslashes("Row <span style='color:#ff0000'> $row </span> uploaded.<br />");
    }
    $msg[] = addslashes("All data uploaded!<p />");
    $mysqli->close();
    return $msg;
}
/**
 * Duplicate check of each row by given $row
 * @param $row: data of 1 row
 * @param $mysqli: mysqli handle
 * @return bool return true if record exist
 */
function recordDupCheck($row,$mysqli,$company): bool
{
    if($company=='方正证券') {
        $sql = <<< EOF
            select * 
            from trade_record 
            where 
                  tdate = '$row[0]' 
              and ttime = '$row[1]' 
              and ts_code = '$row[2]'
              and note = '$row[15]'
EOF;
    }elseif($company=='长江证券') {
        $sql = <<< EOF
            select * 
            from trade_record_cj 
            where 
                  tdate = '$row[0]' 
              and ttime = '$row[1]' 
              and ts_code = '$row[2]'
              and note = '$row[14]'
EOF;
    }

    $result=$mysqli->query($sql) or die($sql."<br />\n");
    $r = $result->num_rows;
    $result->free();
    if($r > 0) return true;
    else return false;
}
