<?php

/**
 * @param $ts_code: stock code
 * @param $where: add select condition you need.
 * @return array: return stock trade recode history data;
 */
function trade_rec($ts_code, $day_st, $day_end, $extra_where = ''): array
{
    global $mysqli;
    $tmp=explode('.',$ts_code);
    $ts_code = $tmp[0];
    $day_end = ($day_end)?$day_end:date('Y-m-d');
    $vendor = $_REQUEST['t_vendor'] ?? '方正证券';
    if($vendor == '方正证券') {
        $sql = "select * from trade_record where ts_code = ? and tdate >= ? and tdate <= ? and tprice>0 $extra_where and length(trade_id)=5 order by tdate asc,ttime asc";
    } elseif($vendor == '长江证券') {
        $sql = "select * from trade_record_cj where ts_code = ? and tdate >= ? and tdate <= ? and tprice>0 $extra_where order by tdate asc,ttime asc";
    }
    $result = db_query($mysqli, $sql, [$ts_code, $day_st, $day_end]);
    return $result->fetch_all(MYSQLI_ASSOC);
}

/**
 * @param $data : data get from db
 * @param $flgType : 2 of flg type: 买入,卖出，
 * @return array
 */
function recDataSort($data,$flgType):array {
    $dataNum=count($data);

    $rtData=$note=$rtVol=$rtPrice=array();
    for($i=0;$i<$dataNum;$i++){
        if($flgType !='' and $data[$i]['flg']!=$flgType) continue;  //$flgType is null means all data matches
        $rtData[]   = array("value"=>array($data[$i]['tdate'],$data[$i]['tprice']));
        $rtDataVol[]   = array("value"=>array($data[$i]['tdate'],abs($data[$i]['tvol'])));
        $rtVol[]    = $data[$i]['tvol'];
        $rtPrice[]  = $data[$i]['tprice'];
        $note[]     = "{$data[$i]['tprice']} {$data[$i]['flg']} {$data[$i]['ts_name']} {$data[$i]['tvol']} 股，成交金额 {$data[$i]['tamount']}";
    }
    return array('data'=>$rtData, 'data2'=>$rtDataVol,'note'=>$note, 'tvol'=>$rtVol, 'tprice'=>$rtPrice);
}

/**
 * @param $vol : trade volume array
 * @param $price : trade price array
 * @return array|false
 */
function avePrice($vol,$price){
    $numVol     = count($vol);
    $numPrice   = count($price);
    if($numPrice!=$numVol or $numVol==0) return false;

    $ttlVol=array_sum($vol);
    $ttlAmt=0; //total amount
    for($i=0;$i<$numVol;$i++){
        $ttlAmt += $vol[$i]*$price[$i];
    }
    $aveprice=round($ttlAmt/$ttlVol,2);
    return array('avePrice'=>$aveprice,'ttlVol'=>$ttlVol,);

}

function tradeSummary($dataBuy,$dataSell,$dataAll):array{
    $buyNum  = count($dataBuy);
    $sellNum = count($dataSell);
    $allNum  = count($dataAll);
    $dataBuyReverse = array_reverse($dataBuy,false); //反向重排数组，key值不保留


    $sellVol  =  $sellAmt = $sellTaxAll =0;
    $buyVol  =  $buyAmt = $buyTaxAll =  0;
    $buyVolRev = $buyAmtRev = $buyAmtRevFix = $buyPriceRevFix = 0;
    for($i=0;$i<$sellNum;$i++){
        $sellVol += $dataSell[$i]['tvol'];
        $sellAmt += $dataSell[$i]['tamount'];
        if($_REQUEST['t_vendor']=='方正证券')
            $sellTaxAll += $dataSell[$i]['commission'];
        $sellTaxAll += $dataSell[$i]['tax1'];
        $sellTaxAll += $dataSell[$i]['tax2'];
        $sellTaxAll += $dataSell[$i]['tax3'];
    }
    for($i=0;$i<$buyNum;$i++){
        $buyVol += $dataBuy[$i]['tvol'];
        $buyAmt += $dataBuy[$i]['tamount'];
        if($_REQUEST['t_vendor']=='方正证券')
            $buyTaxAll += $dataSell[$i]['commission'];
        $buyTaxAll += $dataBuy[$i]['tax2'];
        $buyTaxAll += $dataBuy[$i]['tax3'];
        $buyTaxAll += $dataBuy[$i]['tax1'];
        if($buyVolRev<abs($sellVol)) {
            $buyVolRev += $dataBuyReverse[$i]['tvol'];
            $buyAmtRev += $dataBuyReverse[$i]['tamount'];
        }
    }
    if($buyVolRev >= $sellVol) {
        $buyAmtRevFix = $buyAmtRev;
        $netTAmt = $sellAmt - $buyAmtRevFix;
        //按价格验算净收入
        if($buyVolRev) $buyPriceRevFix = $buyAmtRev/$buyVolRev;
        else $buyPriceRevFix = 0;
        $netTAmtCal = $sellAmt-abs($buyPriceRevFix*min(abs($sellVol),$buyVolRev));
        $buyPriceRevFix = round($buyPriceRevFix,2);
        $netTAmtCal = round($netTAmtCal,0);
        //差价>100表示$buyVolRev 与$sellVol差异较大
        if(abs($netTAmtCal-$netTAmt)>100)
            $netTAmtArr = array("T买成本" => $buyPriceRevFix, "T买股数" => $buyVolRev,"T近似收益" => $netTAmtCal);
        else
            $netTAmtArr = array("T买成本" => $buyPriceRevFix, "T买股数" => $buyVolRev,"做T收益" => round($netTAmt,0));
    }


    $buyAvePrice = round($buyAmt/$buyVol,2);
    if($sellVol) $sellAvePrice = abs(round($sellAmt/$sellVol,2));
    else $sellAvePrice = 0;
    $netBuyVol = $buyVol + $sellVol;
    $netBuyAmt = $buyAmt - $sellAmt;

    $recentPrice = recentPrice($_REQUEST['ts_code']); //最新价格，前一天收盘价
    $stockCost =($netBuyVol>0)?round(($netBuyAmt+$sellTaxAll+$buyTaxAll)/$netBuyVol,2):'--'; //持股成本
    $currentProfit =($netBuyVol>0)?round(($recentPrice['close'] - $stockCost) * $netBuyVol,2):'--'; //当前浮动盈亏；

    $netTAmtArr = array_merge($netTAmtArr, array("最新价格"=>$recentPrice['close'],"浮动盈亏" => $currentProfit));

     $rtArr =array("买入次数"=>$buyNum,"买入股数"=>$buyVol,"买入金额"=>$buyAmt,"买入均价"=>$buyAvePrice,"买入税费"=>$buyTaxAll,
        "卖出次数"=>$sellNum,"卖出股数"=>abs($sellVol),"卖出金额"=>$sellAmt,"卖出均价"=>$sellAvePrice,"卖出税费"=>$sellTaxAll,
        "当前股数"=>$netBuyVol,"持股金额"=>$netBuyAmt, "持股成本"=>$stockCost);
     return array_merge($rtArr,$netTAmtArr);
}

function recentPrice($ts_code){
    global $mysqli;
    $sql = "SELECT close FROM stock_his_pro where ts_code = ? and trade_date=(select max(trade_date) from stock_his_pro)";
    $result = db_query($mysqli, $sql, [ts_code_conv($ts_code)]);
    $rt = $result->fetch_all(MYSQLI_ASSOC);
    return $rt[0];
}

/**
 * reform date to yyyymmdd
 * @param $date
 * @return false|string
 */
function reformDate($date){
    return  date('Ymd',strtotime($date));
}

