<?php

include_once('../common/base.php');

$respone=array();
if(isset($config['parameters']['today_target_kpi_boundary'])){
    $kpi=$config['parameters']['today_target_kpi_boundary'];
}else{
    $kpi='';
}

$kpiValue=0;

//查询KPI的值
$sqlKpi="SELECT [TargetValue]  FROM [dbo].[KPI] WHERE [dbo].[KPI].[KpiNo]='".$kpi."'";
$stmt=sqlsrv_query($conn, $sqlKpi);



if ($stmt) {
    $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
    $kpiValue=$row[0];
    sqlsrv_free_stmt($stmt);
}

$departmentid=$config['work_order']['producing_department'];
$workcenters=$config['work_order']['workcenters'];
$producingLines=$config['work_order']['producing_lines'];
$is_producing_line=$config['work_order']['is_producing_line'];

//计算每天产量
$day_outputs=array();
//计算当前所在小时
$curTime=strtotime(date('Y-m-d 00:00:00', time()));


for ($i=5;$i>=0;$i--) {
    $day_outputs[]=array(
        'day_s'=>date('Y-m-d 00:00:00', strtotime('-'.$i.' days', $curTime)),
        'day_e'=>date('Y-m-d 00:00:00', strtotime('-'.($i-1).' days', $curTime)),
        'value'=>0,
        'kpiValue'=>$kpiValue
    );
}

$conditions=array();
$outputs=array();
$kpiValues=array();
$timeline=array(); 
foreach ($day_outputs as $k=>$v) {


    $sql=" SELECT sum(GenuineNum+DefectNum+ScrapNum) as [TNum],sum(GenuineNum) as [TQNum] FROM [dbo].[WorkRecord]  WHERE ";
    if ($is_producing_line==1) {

        foreach ($producingLines as $depid=>$wc) {
            if (isset($wc['checked']) && $wc['checked']==1) {
                $conditions[]=" (  [dbo].[WorkRecord].[DepId]={$depid} AND [dbo].[WorkRecord].[CenterId]={$wc['CenterId']} )  ";
            }
        }
        $sql.= " (".implode(' OR ', $conditions).") ";
    } else {
        $t_workcenters=implode(",", $workcenters);
        $sql.=" [dbo].[WorkRecord].[CenterId] IN  ({$t_workcenters}) ";
        // if ($departmentid==0) {
        //     $t_workcenters=implode(",", $workcenters);
        //     $sql.=" [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
        // } else {
        //     foreach ($workcenters as $wcid) {
        //         $conditions[]=" ([dbo].[ProcessWork].[DepId]={$departmentid} AND [dbo].[ProcessWork].[CenterId]={$wcid} )  ";
        //     }
        //     $sql.= " (".implode(' OR ', $conditions).") ";
        // }        
    }

    $sql.=" AND [dbo].[WorkRecord].[ReportTime]>='{$v['day_s']}' AND [dbo].[WorkRecord].[ReportTime]<'{$v['day_e']}'  AND [dbo].[WorkRecord].[RecordState]=2 ";

    $timeline[]=date('md', strtotime($day_outputs[$k]['day_s']));
    $kpiValues[]=$kpiValue;
    $stmt=sqlsrv_query($conn, $sql);

    if ($stmt) {
        $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
        $outputs[]=$row[0];
        sqlsrv_free_stmt($stmt);
    }


}


$response['code']=200;
$response['outputs']=$outputs;
$response['kpiValues']=$kpiValues;
$response['timeline']=$timeline;
// header('Content-Type:application/json;charset=utf-8;');
echo json_encode($response);
