<?php
ini_set("display_errors","0");
include_once __DIR__."/config.php";
include_once __DIR__."/getEstate.inc.php";
$mysqli = get_mysqli_connection();

//ajax:  get stock list for select
if($_REQUEST['t']=='stockList'){
    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 = db_query($mysqli, $sql);
    $data = $result->fetch_all(MYSQLI_ASSOC);
    jsonResponse(['stocks' => $data, 'company' => $_REQUEST['t_vendor']]);
}

/**
 * AJAX get finance Data from getFianceData class
 */
if($_REQUEST['t']=='financeData'){
    include_once __DIR__."/getFinanceData.class.php";
    include_once __DIR__."/getBasic.inc.php";
    $years=yearList($_REQUEST['yst'],$_REQUEST['yed']);

    $fina = new getFinance();
    $fina->ts_code=$_REQUEST['ts_code'];
    $dataAll=array();
    foreach($years as $year){
        $fina->finDate=$year;
        $dataAll[] =$fina->getFinanceData();
    }

    for($i=0;$i<count($dataAll);$i++){
        $n=0;
        foreach ($dataAll[$i] as $key=>$val){
            $n++;
            if(strlen($n)<2) $n='0'.$n;
            if($key=='ts_code') {
                $key=$n.'.股票代码';
                $val=tscodeToName($val);
                $n--;
                continue;  //不显示股票代码
            }elseif($key=='period') {
                $key=$n.'.报告期';
                $val=yearToname($val);
                $n--;
                continue; //不显示报告期
            }else $key=$n.'.'.$key;
            if($i==0) $data[$n][]=$key;  //首列加
            $data[$n][]=$val;
        }
    }

    //strip key from array $data
    //dataTable must NOT have any key of json
    $data=array_values($data);
    jsonResponse($data);
}

/*
*esfTBD: 二手房Trade By Day
*/
if($_REQUEST['t']=='esfTBD'){
    $dataTrade=esfTradeDaily();
    $dataList=esfListDaily();
    jsonResponse(['dataTrade' => $dataTrade, 'dataList' => $dataList]);
}

/*
*esfListDaily: 二手房每日挂牌数量
*/
if($_REQUEST['t']=='esfListDaily'){
    $data=esfListDaily();

    jsonResponse(['datas' => $data]);
}
/*
*newTBD: 新房Trade By Day
*/
if($_REQUEST['t']=='newTBD'){
    $district = $_REQUEST['district'];
    $t_start = $_REQUEST['t_start'];
    $t_end = $_REQUEST['t_end'];
    if($_REQUEST['dm']=='Daily'){
        $sql = "SELECT distinct(ej.uuid) uid, date_format(tdate,'%Y-%m-%d') td, eje.val district, eje1.val qty, eje2.val area
            FROM estate_json ej
            left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val = ?
            left join estate_json_ext eje1 on eje1.id=eje.id+3
            left join estate_json_ext eje2 on eje2.id=eje.id+4
            where ej.data_type='1' and ej.tdate >= ? and ej.tdate <= ?
            order by date_format(tdate,'%Y-%m-%d') asc";
        $params = [$district, $t_start, $t_end];
    }
    if($_REQUEST['dm']=='Monthly'){
        $sql = "SELECT distinct(ej.uuid) uid, date_format(tdate,'%Y-%m') td, eje.val district, sum(eje1.val) qty, sum(eje2.val) area
            FROM estate_json ej
            left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val = ?
            left join estate_json_ext eje1 on eje1.id=eje.id+3
            left join estate_json_ext eje2 on eje2.id=eje.id+4
            where ej.data_type='1'";
        $params = [$district];
        if($t_start) { $sql .= " and ej.tdate >= ?"; $params[] = $t_start . '-01'; }
        if($t_end) {
            $endDate = new DateTime($t_end);
            $endDate->modify('last day of this month');
            $sql .= " and ej.tdate <= ?";
            $params[] = $endDate->format('Y-m-d');
        }
        $sql .= " group by date_format(tdate,'%Y-%m') order by date_format(tdate,'%Y-%m') asc";
    }

    $result = db_query($mysqli, $sql, $params);
    $data = $result->fetch_all(MYSQLI_ASSOC);
    if($_REQUEST['dm']=='Daily'){
        $sql2 = "SELECT distinct(ej.uuid) uid, date_format(tdate,'%Y-%m-%d') td, eje.val district, eje1.val area, eje2.val qty
            FROM estate_json ej
            left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val = ?
            left join estate_json_ext eje1 on eje1.id=eje.id+3
            left join estate_json_ext eje2 on eje2.id=eje.id+4
            where ej.data_type='4' and ej.tdate >= ? and ej.tdate <= ?
            order by date_format(tdate,'%Y-%m-%d') asc";
        $params2 = [$district, $t_start, $t_end];
    }
    if($_REQUEST['dm']=='Monthly'){
        $sql2 = "SELECT distinct(ej.uuid) uid, date_format(tdate,'%Y-%m-%d') td, eje.val district, max(eje1.val) area, max(eje2.val) qty
            FROM estate_json ej
            left join estate_json_ext eje on ej.uuid=eje.uuid and eje.val = ?
            left join estate_json_ext eje1 on eje1.id=eje.id+3
            left join estate_json_ext eje2 on eje2.id=eje.id+4
            where ej.data_type='4'";
        $params2 = [$district];
        if($t_start) { $sql2 .= " and ej.tdate >= ?"; $params2[] = $t_start . '-01'; }
        if($t_end) {
            $endDate = new DateTime($t_end);
            $endDate->modify('last day of this month');
            $sql2 .= " and ej.tdate <= ?";
            $params2[] = $endDate->format('Y-m-d');
        }
        $sql2 .= " group by date_format(tdate,'%Y-%m') order by date_format(tdate,'%Y-%m') asc";
    }
    $result = db_query($mysqli, $sql2, $params2);
    $data2 = $result->fetch_all(MYSQLI_ASSOC);
    jsonResponse(['datas' => $data, 'dataExt' => $data2]);
}

/*
* moneyflowData: 资金流向数据
*/
if($_REQUEST['t']=='moneyflowData'){
    include_once __DIR__."/getData.inc.php";
    include_once __DIR__."/getBasic.inc.php";
    $code = $_REQUEST['code'] ?? 'sh';
    $hsgt = $_REQUEST['hsgt'] ?? 'north_money';
    $stacked = $_REQUEST['stacked'] ?? '1';
    $t_start = $_REQUEST['t_start'] ?? '2015-06-01';
    $t_end = $_REQUEST['t_end'] ?? date('Y-m-d');
    $indexData = getIndexData(codetocode($code), date('Ymd',strtotime($t_start)), date('Ymd',strtotime($t_end)));
    $flowData = getMoneyFlowData($hsgt, date('Ymd',strtotime($t_start)), date('Ymd',strtotime($t_end)), $stacked);
    jsonResponse([
        'indexData' => $indexData['data'],
        'flowData' => $flowData['data'],
        'data_max' => $flowData['data_max'],
        'data_min' => $flowData['data_min'],
        'data_avg' => $flowData['data_avg'],
        'data_last' => $flowData['data_last'],
    ]);
}

/*
* estateData: 房地产挂牌数据
*/
if($_REQUEST['t']=='estateData'){
    include_once __DIR__."/getEstate.inc.php";
    $city = $_REQUEST['city'] ?? '宁波';
    $t_start = $_REQUEST['t_start'] ?? '2023-06-20';
    $t_end = $_REQUEST['t_end'] ?? date('Y-m-d');
    $data = getEstateData($city, $t_start, $t_end);
    jsonResponse($data);
}
