<?php
include_once __DIR__."/functions.inc.php";
/**
 * 获取PE_TTM,PB,PS等历史数据
 * @param $ts_code ts code
 * @param $day_st start date
 * @param $day_end end date
 * @param $item: PE_TTM, PB,PS
 * @return array
 */
function getBasicData($ts_code,$day_st,$day_end,$item){
    $day_st=date('Ymd',strtotime($day_st));

$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and trade_date>'".$day_st."'";
if($day_end) {
    $day_end=date('Ymd',strtotime($day_end));
    $where .= " and trade_date <'".$day_end."'";
}
$sql= <<<EOF
select DATE_FORMAT(trade_date,'%Y-%m-%d') as trade_date, $item as pe_ttm from stock_his_basic_pro  where ts_code = '$ts_code' $where order by trade_date asc
EOF;
#echo $sql;
$result = $mysqli->query($sql);

$tDate=$idx=$data=$data_clean=array(); # $data_clean is an array without null 

if($result && $result->num_rows>0) {
    #$data = $result->fetch_all();
    while($row=$result->fetch_assoc()){
        $trade_date=$row['trade_date'];
        #$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['pe_ttm']);
        $data_tmp = array("value"=>array($trade_date,$row['pe_ttm']));
        array_push($data,$data_tmp);
        if($data_tmp['value'][1]>0) array_push($data_clean,$data_tmp['value'][1]);
    }
}
$data_last= round($data_clean[count($data_clean)-1],2);
$data_max= round(max($data_clean),2);
$data_min= round(min($data_clean),2);
if(count($data_clean)>0) $data_avg= round(array_sum($data_clean)/count($data_clean),2);
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 ts_code_conv($ts_code){
    $tmp = explode('.',$ts_code);
    switch($tmp[1]){
        case 'SZ':
            return $ts_code;
        case 'SH':
            return $ts_code;
        case 'sz':
            return strtoupper($ts_code);
        case 'sh':
            return strtoupper($ts_code);
        default:
            if(substr($tmp[0],0,2)=='60') return $tmp[0].'.SH';
            elseif(substr($tmp[0],0,2)=='30') return $tmp[0].'.SZ';
            elseif(substr($tmp[0],0,2)=='00') return $tmp[0].'.SZ';
            else return $ts_code;

    }
}

function getStockHist($ts_code,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and trade_date>='".$day_st."'";
if($day_end) $where .= " and trade_date <='".$day_end."'";
$sql= <<<EOF
select trade_date, close from stock_his_pro  where ts_code = '$ts_code' $where order by trade_date asc
EOF;
//echo $sql;
$result = $mysqli->query($sql);

$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,$row['trade_date']);
        array_push($idx,$row['close']);
        array_push($data,array("value"=>array($row['trade_date'],$row['close'])));
    }
}
#Free result and close connection.
$result->free();
$mysqli->close();
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}

function tscodeToName($ts_code){
    $mysqli = new mysqli('localhost','root','nancysimon','myquant');
    
    $sql= "select name from stock_all_pro where ts_code='{$ts_code}'";
    $result = $mysqli->query($sql);
    if($result && $result->num_rows >0) $row = $result->fetch_assoc();
    $result->free();
    $mysqli->close();
    return $row['name'];
}

function getBasicExtData($ts_code,$item,$day_st,$day_end){
$mysqli = new mysqli('localhost','root','nancysimon','myquant');
$where = " and trade_date>'".$day_st."' ";
if($item=='total_mv_all' or $item=='circ_mv_all') {
    $where .= "and vol/10000/10000 > 1";
    $ts_code='all';
    $item=substr($item,0,-4);
}
if($day_end) $where .= " and trade_date <'".$day_end."'";
$sql= <<<EOF
select * from stock_basic_ext where code = '$ts_code' and item='$item' $where order by trade_date asc
EOF;
//echo $sql;
$result = $mysqli->query($sql);

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

if($result && $result->num_rows>0) {
    #$data = $result->fetch_all();
    while($row=$result->fetch_assoc()){
        if($item=='total_mv' or $item=='circ_mv') {
            $row['vol']=$row['vol']/10000/10000;  #单位：亿
        }
        $trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
        #$trade_date=substr($row['trade_date'],0,4).'-'.substr($row['trade_date'],4,2).'-'.substr($row['trade_date'],6,2);
        $trade_date=substr($row['trade_date'],0,10);
        array_push($tDate,$trade_date);
        array_push($idx,$row['vol']);
        array_push($data,array("value"=>array($trade_date,round($row['vol'],2))));
    }
}
#Free result and close connection.
$result->free();
$mysqli->close();
    $data_last= round($idx[count($idx)-1],2);
    $data_max= round(max($idx),2);
    $data_min= round(min($idx),2);
    if(count($idx)>0) $data_avg= round(array_sum($idx)/count($idx),2);
return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data,'data_max'=>$data_max,'data_min'=>$data_min,'data_avg'=>$data_avg,'data_last'=>$data_last);
}
/*
f2: date
f9: share num
f10: share money
f11: share ratio 流动比例
f12: share ratio 总股本比例
*/
/*
function temporary disabled.
TODO: delete if useless confirm.
function getStockIhHist($ts_code,$day_st,$day_end,$item){
    
    $ts_code = ts_code_conv($ts_code);
    $mysqli = new mysqli('localhost','root','nancysimon','myquant');

    $where = " and f2>'".$day_st."'";
    if($day_end) $where .= " and f2<'".$day_end."'";   // F2: date
    $sql = <<<EOF
    select f2, sum(f9) f9,round(sum(f10),2) sumf10,round(sum(f11),2) sumf11 from ih_by_ts_code 
    where f0 = '$ts_code' $where group by f2 order by f2 asc
EOF;
//EOF必须在行首,且后面不能有空格
    $result = $mysqli->query($sql);

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

    if($result && $result->num_rows>0) {
        #$data = $result->fetch_all();
        while($row=$result->fetch_assoc()){
            array_push($tDate,$row['f2']);
            array_push($idx,$row['vol']); //$item can choose f9,f10,f11,f12
            array_push($data,array("value"=>array($trade_date,$row['vol'])));
        }
    }
    #Free result and close connection.
    $result->free();
    $mysqli->close();
    return array('tDate'=>$tDate,'idx'=>$idx,'data'=>$data);
}
*/

/**
 * @param $date : given a date (yyyy-mm-dd)
 * @param $gap : days +/- n(int)
 * @return false|string
 */
function dateGap($date,$gap){
    $str="$date $gap day";
    return date('Y-m-d',strtotime($str));//日期天数相加函数

}

/**
 * @param string $email: default null
 * @return bool  true
 */
function tradeStocksList($email=null){
    global $mysqli;
    if($_REQUEST['t_vendor']=='方正证券'){
    $sql= <<< EOF
        select distinct(ts_code) ts_code,ts_name from trade_record
        where tprice>0 and (ts_code not like '7%' and ts_code not like '1%')  and length(trade_id)=5 order by ts_code
EOF;
}elseif($_REQUEST['t_vendor']=='长江证券'){
        //length(0+ts_name)!=length(ts_name) 判断ts_name 不能为纯数字
    $sql= <<< EOF
    select distinct(ts_code) ts_code,ts_name from trade_record_cj
where tprice>0  and ts_code not like '7%' and length(0+ts_name)!=length(ts_name) order by ts_code
EOF;
}
    $result = $mysqli->query($sql);
    $data = $result->fetch_all(MYSQLI_ASSOC);
    $option='';
    foreach ( $data as $item){
        $option .= "<option label='{$item['ts_name']}' value='{$item['ts_code']}'></option>\n";
    }
    $html = <<< EOF
<input id="ts_code" name= "ts_code" list="codeList" autocomplete="off"/> 
<datalist id="codeList">
$option
</datalist>
<script>
$("#ts_code").val('{$_REQUEST['ts_code']}');
</script>

EOF;
    echo $html;
    return true;
}

function vendorList($id='t_vendor'){
    $html = <<<EOF
<select id="{$id}" name= "{$id}"  autocomplete="off" > 
<option value="方正证券">方正证券</option>
<option value="长江证券">长江证券</option>
</select>
<script>
$("#{$id}").val('{$_REQUEST[$id]}');
</script>
EOF;
echo $html;
return true;
}

/**
 * 根据年份区间，获取财报日期清单
 * @param $yst
 * @param $yed
 */
function yearList($yst,$yed){
    $n = $yed-$yst+1;
    $thisYear=date('Y');    //yyyy,eg.2022
    $thisMonDay=date('md'); //mmdd,eg.0331
    $years=array();
    for($i=0;$i<$n;$i++){
        if(($yst+$i)<($thisYear-1) ) $years[]=($yst+$i)."1231";  //前年及以前

        //去年
        if(($yst+$i)==($thisYear-1)and $thisMonDay<='0430')  $years[]=($yst+$i)."0930";
        if(($yst+$i)==($thisYear-1)and $thisMonDay >'0430')  $years[]=($yst+$i)."1231";
        //今年
        if(($yst+$i)==$thisYear){
            switch ($thisMonDay){
                case $thisMonDay<='0430':
                    //一季报未公布do nothing
                    break;
                case $thisMonDay>'0430'  && $thisMonDay<= '0831':
                    //公布一季报
                    $years[]=($yst+$i)."0331";
                    break;
                case $thisMonDay>'0831'  && $thisMonDay<= '1031':
                //公布一季报
                    $years[]=($yst+$i)."0630";
                    break;
                case $thisMonDay>'1031':
                    //公布一季报
                    $years[]=($yst+$i)."0930";
                    break;
                default: break;
            }
        }
    }
    return $years;
}

/**
 * $year 20201231 转为2020年报
 * @param $year
 */
function yearToname($year){
    switch (substr($year,4,4)){
        case '1231':
            return substr($year,0,4).'年报';
        case '0930':
            return substr($year,0,4).'三季';
        case '0630':
            return substr($year,0,4).'半年';
        case '0331':
            return substr($year,0,4).'一季';
        default:
            return substr($year,4,4);
    }
}


// 函数一：获取股票代码ts_code对应的历史pe_ttm、pb或ps
function getStockHistoryDataByTS($ts_code, $day_st, $day_end = null, $item){
    //global $token;

    // 参数校验
    if (empty($ts_code) || empty($day_st) || !in_array(strtolower($item), ['pe_ttm', 'pb', 'ps'])) {
        return "参数错误：股票代码、起始日期不能为空，查询项目必须为pe_ttm、pb或ps。";
    }

    // 处理日期参数
    $params = [
        "ts_code" => $ts_code,
        "start_date" => $day_st,
        "end_date" => $day_end ?? date("Y-m-d") // 如果为空，默认为今天
    ];

    // 调用TuShare API获取数据
    $data = callTushareApi('daily_basic', $params);
    return true ;
    if (empty($data)) {
        return "未获取到数据，请检查参数或网络连接。";
    }

    // 提取指定项目的数据
    $result = [];
    $tDate = [];
    $itemValues = [];
    foreach ($data as $row) {
        $tDate[] = $row['trade_date'];
        $itemValues[] = $row[$item];
    }

    // 按日期排序（从远到近，默认已经是按日期排序的）
    $tDate = array_reverse($tDate); // 默认TuShare按日期顺序是近到远，所以反转得到远到近
    $itemValues = array_reverse($itemValues);

    // 计算统计值
    $dataMax = max($itemValues);
    $dataMin = min($itemValues);
    $dataAvg = array_sum($itemValues) / count($itemValues);
    $dataLast = end($itemValues);

    // 返回结果
    return [
        'tDate' => $tDate,
        'data' => $itemValues,
        'data_max' => $dataMax,
        'data_min' => $dataMin,
        'data_avg' => $dataAvg,
        'data_last' => $dataLast
    ];
}

// 函数二：获取指数趋势历史数据
function getIndexHistoryDataByTS($ts_code, $day_st, $day_end = null)
{
    global $token;

    // 参数校验
    if (empty($ts_code) || empty($day_st)) {
        return "参数错误：股票代码和起始日期不能为空。";
    }

    // 处理日期参数
    $params = [
        "ts_code" => $ts_code,
        "start_date" => $day_st,
        "end_date" => $day_end ?? date("Y-m-d") // 如果为空，默认为今天
    ];

    // 调用TuShare API获取数据
    $data = callTushareApi('index_dailybasic', $params);
    return true ;
    if (empty($data)) {
        return "未获取到数据，请检查参数或网络连接。";
    }

    // 提取指数点数值
    $tDate = [];
    $closeValues = [];
    foreach ($data as $row) {
        $tDate[] = $row['trade_date'];
        $closeValues[] = $row['close']; // 假设close字段是指数点数值
    }

    // 按日期排序
    $tDate = array_reverse($tDate);
    $closeValues = array_reverse($closeValues);

    // 返回结果
    return [
        'tDate' => $tDate,
        'data' => $closeValues
    ];
}
?>