<?php

include_once('../common/base.php');
$kpis=$config['parameters']['month_outputs_kpi_boundary'];
$kpis=explode("#",$kpis);
$respone=array();
$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'];

//计算每个月的产量
$month_outputs=array();
//计算当前所在小时
$curTime=strtotime(date('Y-m-1 00:00:00', time()));

for($i=5;$i>=0;$i--){
    $month_outputs[]=array(
        'month_s'=>date('Y-m-d 00:00:00', strtotime('-'.($i).' month', $curTime)),
        'month_e'=>date('Y-m-d 00:00:00', strtotime('-'.(($i-1)).' month', $curTime)),
        'value'=>0

    );
}

$conditions=array();
$outputs=array();
$timeline=array();
$kpiValues=array();
foreach ($month_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['month_s']}' AND [dbo].[WorkRecord].[ReportTime]<'{$v['month_e']}'  AND [dbo].[WorkRecord].[RecordState]=2 ";

    $timeline[]=date('m', strtotime($month_outputs[$k]['month_s']));

    $kpiIndex=date('n',strtotime($month_outputs[$k]['month_s']));
    $kpiIndex--;
    $kpiValues[]=floatval($kpis[$kpiIndex]);
  
    $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);
