<?php

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

$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'];
$equCount=0;

//计算每小时效率
$hourly_eff=array();
//计算当前所在小时

switch($config['time_seq_time_interval']){
    case '30m':
        $curTime=strtotime(date('Y-m-d H:30:00', time()));
        if ($curTime-time()>0) {
            $curTime=strtotime(date('Y-m-d H:00:00', time()));
        }
        $interval=30;
        for ($i=15;$i>=0;$i--) {
            $hourly_eff[]=array(
                'hour_s'=>date('Y-m-d H:i:00', strtotime('-'.($i*$interval).' minutes', $curTime)),
                'hour_e'=>date('Y-m-d H:i:00', strtotime('-'.(($i-1)*$interval).' minutes', $curTime)),
                'eff'=>0
            );
        }
        break;

    case '1h':
            $curTime=strtotime(date('Y-m-d H:00:00', time()));
            $interval=1;
            for ($i=15;$i>=0;$i--) {
                $hourly_eff[]=array(
                    'hour_s'=>date('Y-m-d H:i:00', strtotime('-'.($i*$interval).' hours', $curTime)),
                    'hour_e'=>date('Y-m-d H:i:00', strtotime('-'.(($i-1)*$interval).' hours', $curTime)),
                    'eff'=>0
                );
            }            
        break;
    
    case '2h':
            $curTime=strtotime(date('Y-m-d H:00:00', time()));
            $interval=2;
            for ($i=15;$i>=0;$i--) {
                $hourly_eff[]=array(
                    'hour_s'=>date('Y-m-d H:i:00', strtotime('-'.($i*$interval).' hours', $curTime)),
                    'hour_e'=>date('Y-m-d H:i:00', strtotime('-'.(($i-1)*$interval).' hours', $curTime)),
                    'eff'=>0
                );
            }   
        break;
    
    default:
        $interval=1;
        $curTime=strtotime(date('Y-m-d 00:00:00', time()));
        for ($i=15;$i>=0;$i--) {
            $hourly_eff[]=array(
                'hour_s'=>date('Y-m-d H:i:00', strtotime('-'.($i*$interval).' days', $curTime)),
                'hour_e'=>date('Y-m-d H:i:00', strtotime('-'.(($i-1)*$interval).' days', $curTime)),
                'eff'=>0
            );
        }   
}

$planCapacity=0;
if($config['time_seq_time_interval']=='1d'){
    $conditions=array();
    $sql2="select sum(WorkCenter.RatedCapacity) from WorkCenter where ";
    if ($is_producing_line==1) {
        foreach ($producingLines as $depid=>$wc) {
            if (isset($wc['checked']) && $wc['checked']==1) {
                $conditions[]=" ( [WorkCenter].[CenterId]={$wc['CenterId']} )  ";
            }
        }
        $sql2.= "  (".implode(' OR ', $conditions).") ";

    } else {
        
        $t_workcenters=implode(",", $workcenters);
        $sql2.="  [WorkCenter].[CenterId] IN  ({$t_workcenters}) ";
    }
    
    
    
    $stmt2=sqlsrv_query($conn, $sql2);
    if ($stmt2) {
        $row=sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_NUMERIC);
        $planCapacity=$row[0];
        if($planCapacity==null){
            $planCapacity=0;
        }
        $planCapacity=$planCapacity*3600;
    }
    
    
    if ($stmt2) {
        sqlsrv_free_stmt($stmt2);
    }
}

$conditions=array();
foreach ($hourly_eff as $k=>$v) {

    if(!isset($config['parameters']['time_seq_chart_source']) || $config['parameters']['time_seq_chart_source']==1){
        $sql="select  sum([ElecProWorkNum].[RecordNum]*[ProProcess].[UnitHour]) as  realworktime,sum(datediff(second,[ElecProWorkNum].[CreateTime],[ElecProWorkNum].[ReportTime])) as planworktime  from [ElecProWorkNum] INNER JOIN [ProcessWork] ON  [ElecProWorkNum].[ProWorkId]=[ProcessWork].[ProWorkId]  AND ";
        if ($is_producing_line==1) {
            foreach ($producingLines as $depid=>$wc) {
                if (isset($wc['checked']) && $wc['checked']==1) {
                    $conditions[]=" ([ProcessWork].[DepId]={$depid} AND [ProcessWork].[CenterId]={$wc['CenterId']} )  ";
                }
            }
            $sql.= " (".implode(' OR ', $conditions).") ";
        } else {
            $t_workcenters=implode(",", $workcenters);
            $sql.=" [ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
            // if ($departmentid==0) {
            //     $t_workcenters=implode(",", $workcenters);
            //     $sql.=" [ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
            // } else {
            //     foreach ($workcenters as $wcid) {
            //         $conditions[]=" ([ProcessWork].[DepId]={$departmentid} AND [ProcessWork].[CenterId]={$wcid} )  ";
            //     }
            //     $sql.= " (".implode(' OR ', $conditions).") ";
            // }
        }
      
        $sql.=" INNER JOIN [ProProcess] ON [ProcessWork].[ProProcessId]=[ProProcess].[ProProcessId] where [ElecProWorkNum].[ReportTime]>='{$v['hour_s']}' and [ElecProWorkNum].[ReportTime]<'{$v['hour_e']}' ";
    
    
    }else if(!isset($config['parameters']['time_seq_chart_source']) || $config['parameters']['time_seq_chart_source']==2){

        $sql="select sum(AutoWork.dEquNum*ProProcess.UnitHour),sum(cast(AutoWork.dRunTime as decimal(18,4))+cast(AutoWork.dStopTime as decimal(18,4)) +cast(AutoWork.dUndoTime as decimal(18,4))) from AutoWork inner join ProcessWork on AutoWork.ProWorkId<>'' and  AutoWork.ProWorkId is not null and AutoWork.ProWorkId=ProcessWork.ProWorkId ";
        $sql.=" inner join  ProProcess on ProcessWork.ProProcessId=ProProcess.ProProcessId  inner join Equipment on Equipment.EquNo=AutoWork.EquNo ";
        $sql.=" where AutoWork.WorkTime>='{$v['hour_s']}' and AutoWork.WorkTime<'{$v['hour_e']}' ";
        if ($is_producing_line==1) {
            foreach ($producingLines as $depid=>$wc) {
                if (isset($wc['checked']) && $wc['checked']==1) {
                    $conditions[]=" ([Equipment].[DepId]={$depid} AND [Equipment].[CenterId]={$wc['CenterId']} )  ";
                }
            }
            $sql.= " (".implode(' OR ', $conditions).") ";
        } else {
            $t_workcenters=implode(",", $workcenters);
            $sql.="  And [Equipment].[CenterId] IN  ({$t_workcenters}) ";
            // if ($departmentid==0) {
            //     $t_workcenters=implode(",", $workcenters);
            //     $sql.=" [ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
            // } else {
            //     foreach ($workcenters as $wcid) {
            //         $conditions[]=" ([ProcessWork].[DepId]={$departmentid} AND [ProcessWork].[CenterId]={$wcid} )  ";
            //     }
            //     $sql.= " (".implode(' OR ', $conditions).") ";
            // }
        }

        if(count($conditions)>0){
            $sql.=" And ";
            $sql.= " (".implode(' OR ', $conditions).") ";
        }
    }else{

        $sql="select distinct EquNo from WorkRecord INNER JOIN [ProProcess] ON [WorkRecord].[ProProcessId]=[ProProcess].[ProProcessId] ";       
        $sql.="  where [WorkRecord].[ReportTime]>='{$v['hour_s']}' and [WorkRecord].[ReportTime]<'{$v['hour_e']}' ";
        if ($is_producing_line==1) {

            foreach ($producingLines as $depid=>$wc) {
                if (isset($wc['checked']) && $wc['checked']==1) {
                    $conditions[]=" ([WorkRecord].[DepId]={$depid} AND [WorkRecord].[CenterId]={$wc['CenterId']} )  ";
                }
            }
            $sql.= "And  (".implode(' OR ', $conditions).") ";

        } else {

            $t_workcenters=implode(",", $workcenters);
            $sql.=" And [WorkRecord].[CenterId] IN  ({$t_workcenters}) ";

        }

        $sql="select count(*) from (".$sql.") as t ";
        $stmt=sqlsrv_query($conn, $sql);
        if($stmt) {
            $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
            $equCount=$row[0];
            sqlsrv_free_stmt($stmt);
 
        }


        $sql="select  sum((WorkRecord.GenuineNum+WorkRecord.DefectNum+WorkRecord.ScrapNum)*[ProProcess].[UnitHour]) as  realworktime,datediff(second,'{$v['hour_s']}','{$v['hour_e']}' )  as planworktime  from [WorkRecord] INNER JOIN [ProProcess] ON [WorkRecord].[ProProcessId]=[ProProcess].[ProProcessId]  ";
   
        $sql.="  where [WorkRecord].[ReportTime]>='{$v['hour_s']}' and [WorkRecord].[ReportTime]<'{$v['hour_e']}' ";
        if ($is_producing_line==1) {
            foreach ($producingLines as $depid=>$wc) {
                if (isset($wc['checked']) && $wc['checked']==1) {
                    $conditions[]=" ([WorkRecord].[DepId]={$depid} AND [WorkRecord].[CenterId]={$wc['CenterId']} )  ";
                }
            }
            $sql.= "And  (".implode(' OR ', $conditions).") ";
        } else {
            $t_workcenters=implode(",", $workcenters);
            $sql.=" And [WorkRecord].[CenterId] IN  ({$t_workcenters}) ";
        }
      
        
       
    }


    $stmt=sqlsrv_query($conn, $sql);
    
    if ($stmt) {
        $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
        
        if($config['time_seq_time_interval']=='1d'){
         
            if($row[0]!=null && $planCapacity!=0) {
                $hourly_eff[$k]['eff']=round($row[0]/$planCapacity, 4);
            } else {
                $hourly_eff[$k]['eff']=0;
            }
        }else{
            if ($row[0]!=null && $row[1]!=null && $row[1]!=0) {
                $hourly_eff[$k]['eff']=round($row[0]/$row[1], 4);
                if(!isset($config['parameters']['time_seq_chart_source']) || $config['parameters']['time_seq_chart_source']==3 && $equCount>0){
                    $hourly_eff[$k]['eff']=round($row[0]/($row[1]*$equCount), 4);
                }
            } else {
                $hourly_eff[$k]['eff']=0;
            }
        }

    }


    if ($stmt) {
        sqlsrv_free_stmt($stmt);
    }
}




$eff=array();
$timeline=array();
foreach ($hourly_eff as $k => $v) {
    $eff[]=$hourly_eff[$k]['eff'];
    switch($config['time_seq_time_interval']){
        case '30m':
            $timeline[]=date('H时i分', strtotime($hourly_eff[$k]['hour_s']));
            break;
        case '1h':
            $timeline[]=date('H时', strtotime($hourly_eff[$k]['hour_s']));
            break;
        case '2h':
            $timeline[]=date('H时', strtotime($hourly_eff[$k]['hour_s']));
            break;

        case '1d':
            $timeline[]=date('m月d日', strtotime($hourly_eff[$k]['hour_s']));
            break;
    }
    
}


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