<?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'];

$pageIndex=$_GET['page'];
//$pageIndex=2;
$pageSize=5;

$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');
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');
}


//生产工单表格列
$cols=array();

foreach ($config['parameters']['cols'] as $k=>$v) {
    $cols[]=array(
        'prop'=>$config['parameters']['colnames'][$k],
        'hide'=>!$v,
        'label'=>$k,
        'width'=>empty($config['parameters']['colwidths'][$k])?'100':$config['parameters']['colwidths'][$k]
    );
}



$sql_kpi_eff="SELECT [TargetValue]  FROM [dbo].[KPI] WHERE [dbo].[KPI].[KpiNo]='".$config['parameters']['efficient_kpi_boundary']."'";
$stmt=sqlsrv_query($conn, $sql_kpi_eff);
$kpi_eff=0;
if ($stmt) {
    $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
    $kpi_eff=$row[0];
    sqlsrv_free_stmt($stmt);
}

$total=0;
$conditions=array();
if ($is_producing_line==1) {
    $sql_tdata="SELECT count(*)  as total FROM [dbo].[ProcessWork] INNER JOIN [dbo].[ProduceFormM] ON [dbo].[ProcessWork].[PFormMId] = [dbo].[ProduceFormM].[PFormMId] ";
    $sql_tdata.=" LEFT JOIN [dbo].[Department] ON [dbo].[Department].[DepId]=[dbo].[ProcessWork].[DepId] WHERE  ( ";
 
    foreach ($producingLines as $depid=>$wc) {
        if (isset($wc['checked']) && $wc['checked']==1) {
            $conditions[]=" ([dbo].[ProcessWork].[DepId]={$depid} AND [dbo].[ProcessWork].[CenterId]={$wc['CenterId']} )  ";
        }
    }

    $sql_tdata.= implode(' OR ', $conditions);

    $sql_tdata.=" ) AND (";
    //制令单未完工、未关闭
    $sql_tdata.=" ([dbo].[ProduceFormM].[Completed]<>3 AND [dbo].[ProduceFormM].[Closed]<>3 AND (([dbo].[ProcessWork].[PStartTime]<='{$endtime}' AND [dbo].[ProcessWork].[Completed]<>3) OR (datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0 ))) ";
    //制令单今日指定完工
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[FEndTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Completed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    //制令单今日指定结束
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[CloseTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Closed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    $sql_tdata.=") AND [dbo].[ProcessWork].[Status]=2  AND [dbo].[ProduceFormM].[Issued]=3 ";
} else {
    $sql_tdata="SELECT count(*)   as total FROM [dbo].[ProcessWork] INNER JOIN [dbo].[ProduceFormM] ON [dbo].[ProcessWork].[PFormMId] = [dbo].[ProduceFormM].[PFormMId]   WHERE  ";
    if ($departmentid==0) {
        $t_workcenters=implode(",", $workcenters);
        $sql_tdata.=" [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
    } else {
        foreach ($workcenters as $wc) {
            $conditions[]=" ([dbo].[ProcessWork].[DepId]={$departmentid} AND [dbo].[ProcessWork].[CenterId]={$wc} )  ";
        }
        
        $sql_tdata.= " (".implode(' OR ', $conditions).") ";
    }

    
    $sql_tdata.=" AND (";
    //制令单未完工、未关闭
    $sql_tdata.=" ([dbo].[ProduceFormM].[Completed]<>3 AND [dbo].[ProduceFormM].[Closed]<>3 AND (([dbo].[ProcessWork].[PStartTime]<='{$endtime}' AND [dbo].[ProcessWork].[Completed]<>3) OR (datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0 ))) ";
    //制令单今日指定完工
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[FEndTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Completed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    //制令单今日指定结束
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[CloseTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Closed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    $sql_tdata.=") AND [dbo].[ProcessWork].[Status]=2  AND [dbo].[ProduceFormM].[Issued]=3 ";
}


$stmt_tdata=sqlsrv_query($conn, $sql_tdata);
$tdata=array();
if ($stmt_tdata) {
    $row=sqlsrv_fetch_array($stmt_tdata, SQLSRV_FETCH_NUMERIC);
    $total=$row[0];
}

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

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


//'制单号','品号','品名','规格','预开工','实际开工','计划量','完工量','在制量','完工率','效率','状态'
//状态值：下达 完工 超期未开工 超期未完工
if ($is_producing_line==1) {
    $sql_tdata="SELECT TOP ".$pageSize." * FROM (SELECT ROW_NUMBER() over (Order by case when [dbo].[ProcessWork].[FStartTime]='1900-01-01' then dateadd(day,100,getdate()) else [dbo].[ProcessWork].[FStartTime] end ASC ,[dbo].[ProcessWork].[PStartTime] ASC ) as rownum,[dbo].[Department].[DepName],[dbo].fn_getInTransitNum([dbo].[ProcessWork].[PFormMId]) as InTransitNum,[dbo].[ProduceFormM].[PFormMNo] as PFormMNo,[dbo].[ProcessWork].[ProNo] as ProNo,";
    $sql_tdata.="[dbo].[ProcessWork].[ProName] as ProName,[dbo].[ProcessWork].[ProSpec] as ProSpec,[dbo].[ProcessWork].[ProcessWorkNo] as ProcessWorkNo,";
    $sql_tdata.="case when [dbo].[ProcessWork].[PStartTime]!='1900-01-01' then  convert( varchar(255),[dbo].[ProcessWork].[PStartTime],120) else '' end as PStartTime,";
    $sql_tdata.="case when [dbo].[ProcessWork].[FStartTime]!='1900-01-01' then  convert( varchar(255),[dbo].[ProcessWork].[FStartTime],120) else '' end as FStartTime,";
    $sql_tdata.="[dbo].[ProcessWork].[InputNum] as InputNum,[dbo].[ProcessWork].[OutputNum] as OutputNum,";
    $sql_tdata.="([dbo].[ProcessWork].[InputNum] -[dbo].[ProcessWork].[OutputNum]) as UncompletedNum,[dbo].[ProcessWork].[OutputNum]/[dbo].[ProcessWork].[InputNum] AS CompletedRate,";
    $sql_tdata.="[dbo].fn_pk_eff1([dbo].[ProcessWork].[ProWorkId]) as Eff,";
    $sql_tdata.="   case when [dbo].[ProduceFormM].[Completed]=3 then '制令完工' ";
    $sql_tdata.="   else ";
    $sql_tdata.="       case when [dbo].[ProduceFormM].[Closed]=3 then '制令中止' ";
    $sql_tdata.="       else ";
    $sql_tdata.="           case when [dbo].[ProcessWork].[Completed]=3 then '完工' ";
    $sql_tdata.="           else ";
    $sql_tdata.="               case when [dbo].[ProcessWork].[FStartTime]!='1900-01-01' then ";
    $sql_tdata.="                   case when   [dbo].[ProcessWork].[PEndTime]!='1900-01-01'  and [dbo].[ProcessWork].[PEndTime] is not null  and  datediff(second,[dbo].[ProcessWork].[PEndTime],GETDATE())>0  then '超期未完工' ";
    $sql_tdata.="                   else ";
    $sql_tdata.="                       case when   [dbo].[ProcessWork].[PStartTime]!='1900-01-01' and [dbo].[ProcessWork].[PStartTime] is not null and  datediff(second,[dbo].[ProcessWork].[PStartTime],[dbo].[ProcessWork].[FStartTime])>0  then '开工延期' else '正常' end ";
    $sql_tdata.="                   end ";
    $sql_tdata.="               else ";
    $sql_tdata.="                    case when   [dbo].[ProcessWork].[PStartTime]!='1900-01-01' and [dbo].[ProcessWork].[PStartTime] is not null and  datediff(second,[dbo].[ProcessWork].[PStartTime],GETDATE())>0  then '开工延期' else '正常' end ";
    $sql_tdata.="               end ";
    $sql_tdata.="           end ";
    $sql_tdata.="       end ";
    $sql_tdata.="   end ";
    $sql_tdata.="  as State,";
    $sql_tdata.=" convert(varchar(120),[dbo].[ProcessWork].[PEndTime],120) as PEndTime ,[dbo].[ProcessWork].[Completed] as Completed FROM [dbo].[ProcessWork] INNER JOIN [dbo].[ProduceFormM] ON [dbo].[ProcessWork].[PFormMId] = [dbo].[ProduceFormM].[PFormMId] ";
    $sql_tdata.=" LEFT JOIN [dbo].[Department] ON [dbo].[Department].[DepId]=[dbo].[ProcessWork].[DepId]  WHERE  ( ";
    $conditions=array();

    foreach ($producingLines as $depid=>$wc) {
        if (isset($wc['checked']) && $wc['checked']==1) {
            $conditions[]=" ([dbo].[ProcessWork].[DepId]={$depid} AND [dbo].[ProcessWork].[CenterId]={$wc['CenterId']} )  ";
        }
    }

    $sql_tdata.= implode(' OR ', $conditions);
    $sql_tdata.=" ) AND (";
    //制令单未完工、未关闭
    $sql_tdata.=" ([dbo].[ProduceFormM].[Completed]<>3 AND [dbo].[ProduceFormM].[Closed]<>3 AND (([dbo].[ProcessWork].[PStartTime]<='{$endtime}' AND [dbo].[ProcessWork].[Completed]<>3) OR (datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0 ))) ";
    //制令单今日指定完工
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[FEndTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Completed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    //制令单今日指定结束
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[CloseTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Closed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    $sql_tdata.=") AND [dbo].[ProcessWork].[Status]=2  AND [dbo].[ProduceFormM].[Issued]=3 ";
  
    $sql_tdata.="  )  as t where rownum>".($pageIndex-1)*$pageSize;
} else {
    $t_workcenters=implode(",", $workcenters);
    $sql_tdata="SELECT TOP ".$pageSize." * FROM (SELECT ROW_NUMBER() over (Order by case when [dbo].[ProcessWork].[FStartTime]='1900-01-01' then dateadd(day,100,getdate()) else [dbo].[ProcessWork].[FStartTime] end ASC ,[dbo].[ProcessWork].[PStartTime] ASC ) as rownum, [dbo].[Department].[DepName], [dbo].fn_getInTransitNum([dbo].[ProcessWork].[PFormMId]) as InTransitNum,[dbo].[ProduceFormM].[PFormMNo] as PFormMNo,[dbo].[ProcessWork].[ProNo] as ProNo,";
    $sql_tdata.="[dbo].[ProcessWork].[ProName] as ProName,[dbo].[ProcessWork].[ProSpec] as ProSpec,[dbo].[ProcessWork].[ProcessWorkNo] as ProcessWorkNo,";
    $sql_tdata.="case when [dbo].[ProcessWork].[PStartTime]!='1900-01-01' then  convert( varchar(255),[dbo].[ProcessWork].[PStartTime],120) else '' end as PStartTime,";
    $sql_tdata.="case when [dbo].[ProcessWork].[FStartTime]!='1900-01-01' then  convert( varchar(255),[dbo].[ProcessWork].[FStartTime],120) else '' end as FStartTime,";
    $sql_tdata.="[dbo].[ProcessWork].[InputNum] as InputNum,[dbo].[ProcessWork].[OutputNum] as OutputNum,";
    $sql_tdata.="([dbo].[ProcessWork].[InputNum] -[dbo].[ProcessWork].[OutputNum]) as UncompletedNum,[dbo].[ProcessWork].[OutputNum]/[dbo].[ProcessWork].[InputNum] AS CompletedRate,";
    $sql_tdata.="[dbo].fn_pk_eff1([dbo].[ProcessWork].[ProWorkId]) as Eff,";
    $sql_tdata.="   case when [dbo].[ProduceFormM].[Completed]=3 then '制令完工' ";
    $sql_tdata.="   else ";
    $sql_tdata.="       case when [dbo].[ProduceFormM].[Closed]=3 then '制令中止' ";
    $sql_tdata.="       else ";
    $sql_tdata.="           case when [dbo].[ProcessWork].[Completed]=3 then '完工' ";
    $sql_tdata.="           else ";
    $sql_tdata.="               case when [dbo].[ProcessWork].[FStartTime]!='1900-01-01'  then ";
    $sql_tdata.="                   case when [dbo].[ProcessWork].[PEndTime]!='1900-01-01' and  [dbo].[ProcessWork].[PEndTime] is not null and  datediff(second,[dbo].[ProcessWork].[PEndTime],GETDATE())>0  then '超期未完工' ";
    $sql_tdata.="                   else ";
    $sql_tdata.="                       case when [dbo].[ProcessWork].[PStartTime]!='1900-01-01' and [dbo].[ProcessWork].[PStartTime] is not null and datediff(second,[dbo].[ProcessWork].[PStartTime],[dbo].[ProcessWork].[FStartTime])>0  then '开工延期' else '正常' end ";
    $sql_tdata.="                   end ";
    $sql_tdata.="               else ";
    $sql_tdata.="                    case when   [dbo].[ProcessWork].[PStartTime]!='1900-01-01' and [dbo].[ProcessWork].[PStartTime] is not null and  datediff(second,[dbo].[ProcessWork].[PStartTime],GETDATE())>0  then '开工延期' else '正常' end ";
    $sql_tdata.="               end ";
    $sql_tdata.="           end ";
    $sql_tdata.="       end ";
    $sql_tdata.="   end ";
    $sql_tdata.="  as State,";
    $sql_tdata.="convert(varchar(120),[dbo].[ProcessWork].[PEndTime],120) as PEndTime ,[dbo].[ProcessWork].[Completed] as Completed FROM [dbo].[ProcessWork] INNER JOIN [dbo].[ProduceFormM] ON [dbo].[ProcessWork].[PFormMId] = [dbo].[ProduceFormM].[PFormMId]";
    $sql_tdata.="  LEFT JOIN [dbo].[Department] ON [dbo].[Department].[DepId]=[dbo].[ProcessWork].[DepId] WHERE   ";
    $t_workcenters=implode(",", $workcenters);
    $sql_tdata.="  [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
    // if ($departmentid==0) {
    //     $t_workcenters=implode(",", $workcenters);
    //     $sql_tdata.="  [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
    // } else {
    //     foreach ($workcenters as $wc) {
    //         $conditions[]=" ([dbo].[ProcessWork].[DepId]={$departmentid} AND [dbo].[ProcessWork].[CenterId]={$wc} )  ";
    //     }
        
    //     $sql_tdata.= " (".implode(' OR ', $conditions).") ";
    // }
   
    $sql_tdata.=" AND (";
    //制令单未完工、未关闭
    $sql_tdata.=" ([dbo].[ProduceFormM].[Completed]<>3 AND [dbo].[ProduceFormM].[Closed]<>3 AND (([dbo].[ProcessWork].[PStartTime]<='{$endtime}' AND [dbo].[ProcessWork].[Completed]<>3) OR (datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0 ))) ";
    //制令单今日指定完工
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[FEndTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Completed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    //制令单今日指定结束
    $sql_tdata.=" OR ( datediff(day,[dbo].[ProduceFormM].[CloseTime],GETDATE())=0 AND [dbo].[ProduceFormM].[Closed]=3  AND ((datediff(day,[dbo].[ProcessWork].[FEndTime],GETDATE())=0  ) OR ([dbo].[ProcessWork].[FEndTime]='1900-01-01'  AND [dbo].[ProcessWork].[PStartTime]<='{$endtime}'))) ";
    $sql_tdata.=" ) AND [dbo].[ProcessWork].[Status]=2  AND [dbo].[ProduceFormM].[Issued]=3 ";
    $sql_tdata.=" ) as t where  rownum>".($pageIndex-1)*$pageSize;
}


$stmt_tdata=sqlsrv_query($conn, $sql_tdata);
$tdata=array();
if ($stmt_tdata) {
    while ($row=sqlsrv_fetch_array($stmt_tdata, SQLSRV_FETCH_ASSOC)) {
        $row['PStartTime']=$row['PStartTime']!=''?date('m-d H:i', strtotime($row['PStartTime'])):'';
        $row['FStartTime']=$row['FStartTime']!=''?date('m-d H:i', strtotime($row['FStartTime'])):'';
        $row['OutputNum']=round($row['OutputNum'], 0);
        $row['InputNum']=round($row['InputNum'], 0);
        if ($row['Eff']==0) {
            $row['LtEffKpi']=0;
        } else {
            if ($row['Eff']*100>=$kpi_eff*100) {
                $row['LtEffKpi']=0;
            } else {
                $row['LtEffKpi']=1;
            }
        }

        $row['CompletedRate']=round($row['CompletedRate']*100, 2).'%';
        // if ($row['FStartTime']=='') {
        //     $row['Eff']='*';
        // } else {
        //     $row['Eff']=round($row['Eff']*100, 2).'%';
        // }
        if ($row['Eff']==0) {
            $row['Eff']='*';
        } else {
            $row['Eff']=round($row['Eff']*100, 2).'%';
        }
        $tdata[]=$row;
    }
}

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

$tdataRowNum=count($tdata);
for ($i=$tdataRowNum+1;$i<=$pageSize;$i++) {
    $tdata[]=array(
        
    );
}

if ($total==0) {
    $pageIndex=0;
}
$response['tdata']=$tdata;
$response['code']=200;
$response['cols']=$cols;
$response['kpi_eff']=$kpi_eff==null?0:round($kpi_eff*100, 2);
$response['pageSize']=$pageSize;
$response['cur_page']=$pageIndex;
$response['total_page']=ceil($total/$pageSize);
// header('Content-Type:application/json;charset=utf-8;');
echo json_encode($response);
