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

$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'];
$types=isset($config['parameters']['mymsg_type'])?$config['parameters']['mymsg_type']:[];

$starttime=date('Y-m-d 0:0:0');
$endtime=date('Y-m-d H:i:s');
$todaystart=date('Y-m-d 00:00:00');
$todayend=date('Y-m-d 23:59:59');
$pageIndex=$_GET['page'];
$pageSize=5;
if(isset($config['parameters']['work_order_data_show']) && $config['parameters']['work_order_data_show']=='0'){
    $pageSize=10;
}
switch ($config['work_order']['plan_search_mode']) {
    //2:看3日计划
    case '2':
        $starttime=date('Y-m-d 00:00:00');
        $endtime=date('Y-m-d 00:00:00', strtotime('+3 day'));
        break;
    //3:查本周计划
    case '3':
        $starttime=date('Y-m-d 00:00:00', strtotime('Monday this week'));
        $endtime=date('Y-m-d 23:59:59', strtotime('Sunday this week '));
        break;
    //4:查本月计划
    case '4':
        $starttime=date('Y-m-d 00:00:00', strtotime('first day of this month'));
        $endtime=date('Y-m-d 23:59:59', strtotime('last day of this month'));
        break;
    
    //默认仅查当日
    default:
        $starttime=date('Y-m-d 00:00:00');
        $endtime=date('Y-m-d 23:59:59');
}


$total=0;
$sql=" SELECT  count(*) from [dbo].[MyMessage] ";
$sql.=' INNER JOIN [dbo].[Equipment] ON [dbo].[MyMessage].[EquId]=[dbo].[Equipment].[EquId]  ';
$conditions=array();
if(count($config['currentProdLines'])>0){
    foreach ($config['currentProdLines'] as $depid) {
        $conditions[]=" ( [dbo].[Equipment].[DepId]={$depid}  )  ";
    }
    $sql.="  AND (".implode(" OR ", $conditions).") ";
}else{
    if ($is_producing_line==1) {
        foreach ($producingLines as $depid=>$wc) {
            if (isset($wc['checked']) && $wc['checked']==1) {
                $conditions[]=" ( [dbo].[Equipment].[DepId]={$depid}  )  ";
            }
        }
    
        $sql.="  AND (".implode(" OR ", $conditions).") ";
    }
}

//  else {
//     $t_workcenters=implode(",", $workcenters);
//     $sql.=" [dbo].[ProcessWork].[CenterId] IN ({$t_workcenters})";
// }

if(count($types)>0){

    $sql.="  WHERE  [dbo].[MyMessage].[TPYE] in ('".implode("','",$types)."') AND  [dbo].[MyMessage].[EquId] IS NOT NULL  AND NOT ([dbo].[MyMessage].[StartTime]<'".date('Y-m-d', time())."' AND IsValid=0)   ";

}else{
    $sql.="  WHERE  [dbo].[MyMessage].[EquId] IS NOT NULL  AND NOT ([dbo].[MyMessage].[StartTime]<'".date('Y-m-d', time())."' AND IsValid=0)   ";

}

$stmt=sqlsrv_query($conn, $sql);
if ($stmt) {
    $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
    $total=$row[0];
    sqlsrv_free_stmt($stmt);
}


if (($pageIndex-1)*$pageSize>=$total) {
    $pageIndex=1;
}


$sql="SELECT TOP  ".$pageSize." *  FROM ( SELECT ROW_NUMBER() over (order by [dbo].[MyMessage].[StartTime] desc) as rownum,convert(varchar(255), [dbo].[MyMessage].[StartTime] ,120)  AS  [StartTime],MessageContent, convert(varchar(255), [dbo].[MyMessage].[EndTime] ,120) AS [EndTime],[dbo].[Equipment].[EquName],[dbo].[MyMessage].[TPYE],[dbo].[MyMessage].[IsValid],convert(varchar(255),GETDATE(),120) AS [NOW] from [dbo].[MyMessage] ";
$sql.=' INNER JOIN [dbo].[Equipment] ON [dbo].[MyMessage].[EquId]=[dbo].[Equipment].[EquId]  ';
$conditions=array();
if(count($config['currentProdLines'])>0){
    foreach ($config['currentProdLines'] as $depid) {
        $conditions[]=" ( [dbo].[Equipment].[DepId]={$depid}  )  ";
    }
    $sql.="  AND (".implode(" OR ", $conditions).") ";
}else{
    if ($is_producing_line==1) {
        foreach ($producingLines as $depid=>$wc) {
            if (isset($wc['checked']) && $wc['checked']==1) {
                $conditions[]=" ( [dbo].[Equipment].[DepId]={$depid}  )  ";
            }
        }
    
        $sql.="  AND (".implode(" OR ", $conditions).") ";
    }
}

if(count($types)>0){
    $sql.="   WHERE [dbo].[MyMessage].[TPYE] in ('".implode("','",$types)."') AND  [dbo].[MyMessage].[EquId] IS NOT NULL  AND NOT ([dbo].[MyMessage].[StartTime]<'".date('Y-m-d', time())."' AND IsValid=0) ) as  t ";
}else{
    $sql.="   WHERE   [dbo].[MyMessage].[EquId] IS NOT NULL  AND NOT ([dbo].[MyMessage].[StartTime]<'".date('Y-m-d', time())."' AND IsValid=0) ) as  t ";
}

$sql.=" WHERE   rownum>".($pageIndex-1)*$pageSize ;


$messages=array();
$stmt=sqlsrv_query($conn, $sql);
if ($stmt) {
    while ($row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        if ($row['IsValid']==true) {
            $row['CountTime']=(strtotime($row['NOW'])-strtotime($row['StartTime']))/60;
        } else {
            $row['CountTime']=(strtotime($row['EndTime'])-strtotime($row['StartTime']))/60;
        }
       
        $row['CountTime']=round($row['CountTime'], 0);
        $row['StartTime']=$row['StartTime']!=''?date('m-d H:i', strtotime($row['StartTime'])):'';
        $messages[]=$row;
    }
    
    sqlsrv_free_stmt($stmt);
}
$rowNum=count($messages);
for ($i=$rowNum+1;$i<=$pageSize;$i++) {
    $messages[]=array(
        
    );
}

if ($total==0) {
    $pageIndex=0;
}
$data=array();
$data['code']=200;
$data['messages']=$messages;
$data['cur_page']=$pageIndex;
$data['total_page']=ceil($total/$pageSize);
echo json_encode($data);
