<?php
include_once('../common/base.php');
include_once('../common/func.php');

$mode=$config['data_from_scada'];

if ($mode=='true') {
    $mode="SCADA";
} else {
    $mode="NORMAL";
}

$starttime=null;
//    $sql='select  top 1 * from TimeSchedule order by CONVERT(VARCHAR(255),AttStartTime,108)  asc';
//    $stmt=sqlsrv_query($conn, $sql);
//    if ($stmt) {
//        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
//        $starttime=$row['AttStartTime']->format('H:i');
//        sqlsrv_free_stmt($stmt);
//    }
//    $starttime=date('Y-m-d '.$starttime, time());
$starttime=date('Y-m-d 00:00', time());
$endtime=date('Y-m-d 23:59', time());

//$starttime='2021-03-16 00:00:00';
//$endtime='2021-03-16 23:59:59';
// if (isset($_GET['starttime'])) {
//     $starttime=date('Y-m-d H:i', $_GET['starttime']);
// }

// if (isset($_GET['endtime'])) {
//     $endtime=date('Y-m-d H:i', $_GET['endtime']);
// }


$equNo=$_GET['equNo'];

$data=array();
$timeBase=strtotime(date('Y-m-d', time()));
$data['curTime']=time()-$timeBase;


if(isset($config['curdev_dataget_period'])){
    if(empty($config['curdev_dataget_period'])){
        $hCount=8;
    }else{
        $hCount=intval($config['curdev_dataget_period']);
    }
    
}else{
    $hCount=8;
}


// $sql="select Capacity from Equipment where EquNo='{$equNo}' ";
// $stmt=sqlsrv_query($conn, $sql);
// $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
// $data['Capacity']=$row['Capacity'];
// sqlsrv_free_stmt($stmt);
switch ($mode) {
    case 'SCADA':
        $sql="select *,case when Alltime<>0 then cast(Runtime as float)/cast(Alltime as float) else 0 end as RunRate from EquWorkScada where EquNo='{$equNo}' ";
        $stmt=sqlsrv_query($conn, $sql);
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        if ($row!=null) {
            //$data['runRate']=empty($row['RunRate'])?0:$row['RunRate'];
            $data['autoRun']=empty($row['RunTime'])?0:$row['RunTime'];
            $data['autoStop']=empty($row['StopTime'])?0:$row['StopTime'];
            $data['warnTime']=empty($row['ErrTime'])?0:$row['ErrTime'];
            $data['totalNum']=empty($row['EquNum'])?0:$row['EquNum'];
            $data['prepareTime']=empty($row['UndoTime'])?0:$row['UndoTime'];
            $data['allTime']=empty($row['AllTime'])?0:$row['AllTime'];
            $data['closeTime']=time()-strtotime(date('Y-m-d', time()))-$data['allTime'];
        } else {
            $data['runRate']=0;
            $data['autoRun']=0;
            $data['autoStop']=0;
            $data['warnTime']=0;
            $data['totalNum']=0;
            $data['prepareTime']=0;
            $data['allTime']=0;
            $data['closeTime']=0;
        }

        $sql="select status from  EquWorkScada where EquNo='{$equNo}'" ;
        $stmt=myQuery($conn,$sql);
        $row=sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC);
        $data['devStatus']=$row['status'];
        //计算每小时效率
        $hours=array();
        //计算当前所在小时
        $curTime=strtotime(date('Y-m-d H:00:00', time()));
        $time1=strtotime(date('Y-m-d H:00:00', time()));
        $time2=time();
        
        if ($time2-$time1>60*30) {
            $curTime=strtotime(date('Y-m-d H:00:00', time()+3600));
        }
        
        
        for ($i=$hCount-1;$i>=0;$i--) {
            $hours[]=array(
                'hour_s'=>date('Y-m-d H:i:00', strtotime('-'.($i*60).' minutes', $curTime)),
                'hour_e'=>date('Y-m-d H:i:00', strtotime('-'.(($i-1)*60).' minutes', $curTime)),
            );
        }
        $data['timeline']=array();
        $data['outputs']=array();
        $data['runrates']=array();
        foreach ($hours as $k=>$hour) {
            // $sql='select cast((Max(RunTime)-Min(RunTime)) as float)/3600 as RunRate, (Max(EquNum)-Min(EquNum)) as OutputNum from View_AutoWorkWithDelta where ';
            // $sql.="  View_AutoWorkWithDelta.WorkTime>='".$hour['hour_s']."' AND View_AutoWorkWithDelta.WorkTime<'".$hour['hour_e']."' and EquNo='{$equNo}' ";
            
            $sql='select cast(sum(dRunTime) as float)/3600 as RunRate, sum(dEquNum) as OutputNum from AutoWork where ';
            $sql.="  AutoWork.WorkTime>='".$hour['hour_s']."' AND AutoWork.WorkTime<'".$hour['hour_e']."' and EquNo='{$equNo}' ";            
            $stmt=sqlsrv_query($conn, $sql);
            $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
            $data['timeline'][]=date('H时', strtotime($hour['hour_s']));
            $data['outputs'][]=$row['OutputNum'];
            $data['runrates'][]=$row['RunRate'];
            //$hours[$k]=array_merge($hour, $row);
            sqlsrv_free_stmt($stmt);
        }

        break;

    case 'NORMAL':
        $sql="select sum(datediff(second,ElecProWorkNum.CreateTime,ElecProWorkNum.ReportTime))/3600 as RunRate ,sum(datediff(second,ElecProWorkNum.CreateTime,ElecProWorkNum.ReportTime)) as AutoRun from ElecProWorkNum where RecordNum<>0 ";
        $sql.=" and ElecProWorkNum.ReportTime>='{$starttime}' AND ElecProWorkNum.ReportTime<'{$endtime}' and EquNo='{$equNo}' ";
        $stmt=sqlsrv_query($conn, $sql);
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        //$data['runRate']=empty($row['RunRate'])?0:$row['RunRate'];
        $data['autoRun']=empty($row['AutoRun'])?0:$row['AutoRun'];
        sqlsrv_free_stmt($stmt);
        
        $sql=" select sum(ElecProWorkNum.RecordNum) as TotalNum from ElecProWorkNum inner join ProcessWork on ElecProWorkNum.ProWorkId=ProcessWork.ProWorkId ";
        $sql.=" inner join WorkRecord on ProcessWork.ProWorkId=WorkRecord.ProWorkId ";
        $sql.=" where ElecProWorkNum.EquNo='{$equNo}'  and ElecProWorkNum.ReportTime>='{$starttime}' AND ElecProWorkNum.ReportTime<'{$endtime}' " ;
        $stmt=sqlsrv_query($conn, $sql);
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        $data['totalNum']=empty($row['TotalNum'])?0:$row['TotalNum'];
        sqlsrv_free_stmt($stmt);
        
        $sql="select sum(datediff(second,ElecProWorkNum.CreateTime,ElecProWorkNum.ReportTime)) as PrepareTime from ElecProWorkNum where RecordNum=0 ";
        $sql.=" and ElecProWorkNum.ReportTime>='{$starttime}' AND ElecProWorkNum.ReportTime<'{$endtime}' and EquNo='{$equNo}' ";
        $stmt=sqlsrv_query($conn, $sql);
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        $data['prepareTime']=empty($row['PrepareTime'])?0:$row['PrepareTime'];
        sqlsrv_free_stmt($stmt);
        
        $data['autoStop']=$data['curTime']-$data['prepareTime']-$data['autoRun'];
        
        // $sql="select sum(datediff(second,MyMessage.StartTime,MyMessage.EndTime)) as WarnTime from MyMessage";
        // $sql.="  where MyMessage.CreateTime>='{$starttime}' AND MyMessage.CreateTime<'{$endtime}'  ";
        // $stmt=sqlsrv_query($conn, $sql);
        // $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        // $data['WarnTime']=empty($row['WarnTime'])?0:$row['WarnTime'];
        $data['warnTime']=0;
        // sqlsrv_free_stmt($stmt);
        
        $data['closeTime']=0;
        
        //计算每小时效率
        $hours=array();
        //计算当前所在小时
        $curTime=strtotime(date('Y-m-d H:00:00', time()));
        $time1=strtotime(date('Y-m-d H:00:00', time()));
        $time2=time();
        
        if ($time2-$time1>60*30) {
            $curTime=strtotime(date('Y-m-d H:00:00', time()+3600));
        }
        
        
        for ($i=$hCount-1;$i>=0;$i--) {
            $hours[]=array(
                'hour_s'=>date('Y-m-d H:i:00', strtotime('-'.($i*60).' minutes', $curTime)),
                'hour_e'=>date('Y-m-d H:i:00', strtotime('-'.(($i-1)*60).' minutes', $curTime)),
            );
        }
        $data['devStatus']=0;
        $data['timeline']=array();
        $data['outputs']=array();
        $data['runrates']=array();
        foreach ($hours as $k=>$hour) {
            $sql='select cast(sum(datediff(second,ElecProWorkNum.CreateTime,ElecProWorkNum.ReportTime)) as float)/3600 as RunRate, sum(RecordNum) as OutputNum from ElecProWorkNum where RecordNum<>0';
            $sql.=" and ElecProWorkNum.ReportTime>='".$hour['hour_s']."' AND ElecProWorkNum.ReportTime<'".$hour['hour_e']."' and EquNo='{$equNo}' ";
            $stmt=sqlsrv_query($conn, $sql);
            $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
            $data['timeline'][]=date('H时', strtotime($hour['hour_s']));
            $data['outputs'][]=$row['OutputNum'];
            $data['runrates'][]=$row['RunRate'];
            //$hours[$k]=array_merge($hour, $row);
            sqlsrv_free_stmt($stmt);
        }
        
        break;
}


// $data['outputs']=array(1,2,3,4,5,6,7,8);
// $data['runrates']=array(3,4,5,6,7,9,10,11);


$data['mode']=$mode;
$data['closeTime2']=(!empty($data['curTime'])?(round($data['closeTime']/$data['curTime'], 4)*100):0).'%';
$data['closeTime']=timeToHMS($data['closeTime']);
$data['warnTime2']=(!empty($data['curTime'])?(round($data['warnTime']/$data['curTime'], 4)*100):0).'%';
$data['warnTime']=timeToHMS($data['warnTime']);
$data['prepare2']=(!empty($data['curTime'])?(round($data['prepareTime']/$data['curTime'], 4)*100):0).'%';
$data['prepare']=timeToHMS($data['prepareTime']);
$data['autoStop2']=(!empty($data['curTime'])?(round($data['autoStop']/$data['curTime'], 4)*100):0).'%';
$data['autoStop']=timeToHMS($data['autoStop']);
$data['autoRun2']=(!empty($data['curTime'])?(round($data['autoRun']/$data['curTime'], 4)*100):0).'%';
$data['autoRun']=timeToHMS($data['autoRun']);

echo json_encode($data);
