<?php
include_once __DIR__."/config.php";
/*
上证指数：000001.SH
深证成指：399001.SZ
中小板指: 399005.SZ
创业板指：399006.SZ
*/
function getIndexData($ts_code,$day_st,$day_end){
$mysqli = get_mysqli_connection();

$sql = "select trade_date, close from index_hist_pro where ts_code = ? and trade_date >= ?";
$params = [$ts_code, $day_st];
if($day_end) {
    $sql .= " and trade_date <= ?";
    $params[] = $day_end;
}
$sql .= " order by trade_date asc";
$result = db_query($mysqli, $sql, $params);

$tDate=$idx=$data=array();

if($result && $result->num_rows>0) {
    #$data = $result->fetch_all();
    while($row=$result->fetch_assoc()){
        $trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
        $trade_date1=strtotime($row['trade_date']);
        array_push($tDate,$trade_date);
        array_push($idx,$row['close']);
        array_push($data,array("value"=>array($trade_date,round($row['close'],2))));
    }
}
#Free result and close connection.

$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}
/*
#LX:    序号 1-6,分别代表基金，QFII, 社保，券商，保险，信托
#share: vposition 市值 f10, sahreHDnum 股数 f9
*/
function getIhData($lx,$share,$day_st,$day_end){
    $mysqli = get_mysqli_connection();
    if($share=='ShareHDNum' ) $shareSel="sum(f9)/100000000"; //持股数
    elseif($share=='vPosition') $shareSel="sum(f10)/100000000"; //持股额
    elseif($share=='VSRatio') $shareSel='f10/f9'; //每股价格
    $sql = "select ih_date,$shareSel as ttl from ih_by_ts_code_ext where tp = ? and ih_date >= ?";
    $params = [$lx, $day_st];
    if($day_end) {
        $sql .= " and ih_date <= ?";
        $params[] = $day_end;
    }
    $sql .= " group by ih_date order by ih_date";
    $result = db_query($mysqli, $sql, $params);
//echo $sql;
    $tDate=$idx=$data=array();

    if($result && $result->num_rows>0) {
        #$data = $result->fetch_all();
        while($row=$result->fetch_assoc()){
            array_push($tDate,$row['ih_date']);
            array_push($idx,$row['ttl']);
            array_push($data,array("value"=>array($row['ih_date'],$row['ttl'])));
        }
    }
    #Free result and close connection.
    $result->free();
    $mysqli->close();
    return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}

function lxDefine($lx){
    switch($lx){
        case 1: return "公募基金";
        case 2: return "QFII";
        case 3: return "社保基金";
        case 4: return "券商持仓";
        case 5: return "保险持仓";
        case 6: return "信托持仓";
    }
}
/*
上证指数：000001.SH
深证成指：399001.SZ
中小板指: 399005.SZ
创业板指：399006.SZ
*/
function codetocode($code){
    switch($code){
        case 'sh':
            return '000001.SH';
        case 'sz':
            return '399001.SZ';
        case 'zx':
            return '399005.SZ';
        case 'cy':
            return '399006.SZ';
        case 'all':
            return '000002.SH';
    }
}

/**
 * @param $code
 * @return string|void
 */
function codeToName($code){
    switch($code){
        case 'sh':
            return '上证';
        case 'sz':
            return '深证';
        case 'zx':
            return '中小板';
        case 'cy':
            return '创业板';
        case 'all':
            return 'A股';
    }
}

/**
 * 名称	类型	描述
trade_date	str	交易日期
ggt_ss	float	港股通（上海）
ggt_sz	float	港股通（深圳）
hgt	float	沪股通（百万元）
sgt	float	深股通（百万元）
north_money	float	北向资金（百万元）
south_money	float	南向资金（百万元）
 * @param $code
 * @return false|string
 */
function hsgtConv($code){
    switch ($code){
        case 'ggt_ss':
            return '港股通（上海）';
        case 'ggt_sz':
            return '港股通（深圳）';
        case 'hgt':
            return '沪股通';
        case 'sgt':
            return '深股通';
        case 'north_money':
            return '北向资金';
        case 'south_money':
            return '南向资金';
        default:
            return false;
    }
}

function hkholdConv($code){
    switch ($code){
        case 'ratio':
            return '持股比例(%)';
        case 'vol':
            return '持股数(万)';
        default:
            return false;
    }
}

/*
#item:  f9:持股数 f10:持股额 f11:占总股本比例 f12:占流通股比例  
#LX:    tp字段: 序号 1-6,分别代表基金，QFII, 社保，券商，保险，信托
*/
function getIhDataByStock($ts_code,$item,$lx,$day_st,$day_end){
    $mysqli = get_mysqli_connection();
    switch(strtoupper($item)){
        case 'F9':
            $item_sel = 'sum(f9)/10000';
            break;
        case 'F10':
            $item_sel = 'sum(f10)/10000';
            break;
        case 'F11':
        case 'F12':
            $item_sel = "sum($item)";
            break;
    }
    $sql = "select ts_code,ih_date,$item_sel as ttl from ih_by_ts_code_ext where ts_code = ? and ih_date > ?";
    $params = [$ts_code, $day_st];
    if($day_end) {
        $sql .= " and ih_date < ?";
        $params[] = $day_end;
    }
    if($lx) {
        $sql .= " and tp = ?";
        $params[] = $lx;
    }
    $sql .= " group by ih_date order by ih_date asc";
    $result = db_query($mysqli, $sql, $params);
#echo $sql;
    $tDate=$idx=$data=array();

    if($result && $result->num_rows>0) {
        #$data = $result->fetch_all();
        while($row=$result->fetch_assoc()){
            array_push($tDate,$row['ih_date']);
            array_push($idx,$row['ttl']);
            array_push($data,array("value"=>array($row['ih_date'],$row['ttl'])));
        }
    }
    $data_last= round($idx[count($idx)-1],1);
    $data_max= round(max($idx),1);
    $data_min= round(min($idx),1);
    if(count($idx)>0) $data_avg= round(array_sum($idx)/count($idx),1);
    else $data_avg=null;
    #Free result and close connection.
    $result->free();
    $mysqli->close();
    return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}

function getMoneyFlowData($itm, $day_st,$day_end, $stacked){
    $mysqli = get_mysqli_connection();

    $allowed_cols = ['ggt_ss','ggt_sz','hgt','sgt','north_money','south_money'];
    if(!in_array($itm, $allowed_cols)) return array('tDate'=>[],'data'=>[],'data_max'=>0,'data_min'=>0,'data_avg'=>0,'data_last'=>0);

    if($stacked==1) $tb = 'moneyflow_hsgt_pro_ext';
    else $tb = 'moneyflow_hsgt_pro';
    $sql = "select trade_date, $itm as itm from $tb where trade_date >= ?";
    $params = [$day_st];
    if($day_end) {
        $sql .= " and trade_date <= ?";
        $params[] = $day_end;
    }
    $sql .= " order by trade_date asc";
    $result = db_query($mysqli, $sql, $params);

    $tDate=$data=array();

    if($result && $result->num_rows>0) {
        while($row=$result->fetch_assoc()){
            $trade_date=date('Y-m-d',strtotime($row['trade_date']));
            array_push($tDate,$row['itm']/100);
            array_push($data,array("value"=>array($trade_date,round($row['itm']/100,2))));
        }
    }
#Free result and close connection.
    $result->free();
    $mysqli->close();
    $data_last= round($tDate[count($tDate)-1],2);
    $data_max= round(max($tDate),2);
    $data_min= round(min($tDate),2);
    if(count($tDate)>0) $data_avg= round(array_sum($tDate)/count($tDate),2);
    return array('tDate'=>$tDate,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
?>