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

$range=$_GET['range'];
$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'];



$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 00:00:00', strtotime('next day'));
// 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 00:00:00', strtotime('Monday next week '));
//         break;
//     //4:查本月计划
//     case '4':
//         $starttime=date('Y-m-d 00:00:00', strtotime('first day of this month'));
//         $endtime=date('Y-m-d 00:00:00', strtotime('first day of next month'));
//         break;
    
//     //默认仅查当日
//     default:
//         $starttime=date('Y-m-d 00:00:00');
//         $endtime=date('Y-m-d 00:00:00', strtotime('next day'));
// }

switch ($range) {
    //2:查本周计划
    case '周':
        $starttime=date('Y-m-d 00:00:00', strtotime('Monday this week'));
        $endtime=date('Y-m-d 00:00:00', strtotime('Monday next week '));
		$mode="本周";
        break;
    //3:查本月计划
    case '月':
        $starttime=date('Y-m-01 00:00:00', strtotime('first day of this month'));
        $endtime=date('Y-m-01 00:00:00', strtotime('first day of next month'));
		$mode="本月";
        break;
    //3:查本年计划
    case '年':
        $starttime=date('Y-01-01 00:00:00', strtotime('first day of this year'));
        $endtime=date('Y-01-01 00:00:00', strtotime('first day of next year'));
		$mode="本年";
        break;    
    //默认仅查当日
    default:
        $starttime=date('Y-m-d 00:00:00');
        $endtime=date('Y-m-d 00:00:00', strtotime('next day'));
}


//指定期间的产量和合格数
$conditions=array();
$sql1=" 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']} )  ";
        }
    }
    $sql1.= " (".implode(' OR ', $conditions).") ";
} else {
    $t_workcenters=implode(",", $workcenters);
    $sql1.=" [dbo].[WorkRecord].[CenterId] IN  ({$t_workcenters}) ";
}

$sql1.=" AND [dbo].[WorkRecord].[ReportTime]>='{$starttime}' AND [dbo].[WorkRecord].[ReportTime]<'{$endtime}'  AND [dbo].[WorkRecord].[RecordState]=2";


$stmt=sqlsrv_query($conn, $sql1);
$quality_num=0;
$total_num=0;
if ($stmt) {
    $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
    $total_num=$row[0];
    $quality_num=$row[1];
    sqlsrv_free_stmt($stmt);
}

//计算总良率
$qualified_rate=0;
if ($total_num!=0) {
    $qualified_rate=$quality_num/$total_num;
}



$dataSource=$config['parameters']['time_seq_chart_source'];
//计算总效率
$conditions=array();
if($dataSource==2){
    $sql3="select sum(AutoWork.dEquNum*ProProcess.UnitHour),sum(AutoWork.dRuntime+AutoWork.dStopTime+AutoWork.dUndoTime) from AutoWork inner join ProcessWork on AutoWork.ProWorkId=ProcessWork.ProWorkId inner join ProProcess on ProcessWork.ProProcessId=ProProcess.ProProcessId inner join Equipment on AutoWork.EquNo=Equipment.EquNo  where ";
    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']} )  ";
            }
        }
        $sql3.= " (".implode(' OR ', $conditions).") ";
    } else {
    
        $t_workcenters=implode(",", $workcenters);
        $sql3.=" [Equipment].[CenterId] IN  ({$t_workcenters}) ";
        // if ($departmentid==0) {
        //     $t_workcenters=implode(",", $workcenters);
        //     $sql3.=" [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
        // } else {
        //     foreach ($workcenters as $wc) {
        //         $conditions[]=" ([dbo].[ProcessWork].[DepId]={$departmentid} AND [dbo].[ProcessWork].[CenterId]={$wc} )  ";
        //     }
    
        //     $sql3.= " (".implode(' OR ', $conditions).") ";
        // }
    }
    $sql3.=" AND [AutoWork].[WorkTime]>='{$starttime}' AND [AutoWork].[WorkTime]<'{$endtime}'  ";

}else{
    $sql3="select sum([dbo].[ElecProWorkNum].[RecordNum]*[dbo].[ProProcess].[UnitHour]),sum(datediff(SECOND,[dbo].[ElecProWorkNum].[CreateTime],[dbo].[ElecProWorkNum].[ReportTime]))  from [dbo].[ProcessWork] INNER JOIN [dbo].[ElecProWorkNum] ON [dbo].[ProcessWork].[ProWorkId]=[dbo].[ElecProWorkNum].[ProWorkId] INNER JOIN [dbo].[ProProcess] ON [dbo].[ProProcess].[PFormMId]=[dbo].[ProcessWork].[PFormMId] AND [dbo].[ProcessWork].[ProProcessId]=[dbo].[ProProcess].[ProProcessId] where ";
    if ($is_producing_line==1) {
        foreach ($producingLines as $depid=>$wc) {
            if (isset($wc['checked']) && $wc['checked']==1) {
                $conditions[]=" ([dbo].[ProcessWork].[DepId]={$depid} AND [dbo].[ProcessWork].[CenterId]={$wc['CenterId']} )  ";
            }
        }
        $sql3.= " (".implode(' OR ', $conditions).") ";
    } else {
    
        $t_workcenters=implode(",", $workcenters);
        $sql3.=" [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
        // if ($departmentid==0) {
        //     $t_workcenters=implode(",", $workcenters);
        //     $sql3.=" [dbo].[ProcessWork].[CenterId] IN  ({$t_workcenters}) ";
        // } else {
        //     foreach ($workcenters as $wc) {
        //         $conditions[]=" ([dbo].[ProcessWork].[DepId]={$departmentid} AND [dbo].[ProcessWork].[CenterId]={$wc} )  ";
        //     }
    
        //     $sql3.= " (".implode(' OR ', $conditions).") ";
        // }
    }
    $sql3.=" AND [dbo].[ElecProWorkNum].[ReportTime]>='{$starttime}' AND [dbo].[ElecProWorkNum].[ReportTime]<'{$endtime}'  ";
}


$stmt=sqlsrv_query($conn, $sql3);
$eff_rate=0;
$plan_total_time=0;
$real_total_time=0;
if ($stmt) {
    $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
    $plan_total_time=$row[1]==null?0:$row[1];
    $real_total_time=$row[0]==null?0:$row[0];
    sqlsrv_free_stmt($stmt);
}

if ($plan_total_time!=0) {
    $eff_rate=$real_total_time/$plan_total_time;
}



//计算总完工率
//'制单号','品号','品名','规格','预开工','实际开工','计划量','完工量','在制量','完工率','效率','状态'
//状态值：下达 完工 超期未开工 超期未完工
$conditions=array();
if ($is_producing_line==1) {
    $sql_tdata="SELECT   sum([dbo].[ProcessWork].[OutputNum]) as TotalOutputNum ,  sum([dbo].[ProcessWork].[InputNum]) as TotalInputNum,count(*) as TotalWoNum ";
    $sql_tdata.="  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   sum([dbo].[ProcessWork].[OutputNum]) as TotalOutputNum ,  sum([dbo].[ProcessWork].[InputNum]) as TotalInputNum ,count(*) as TotalWoNum";
    $sql_tdata.=" 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 ";
}

$stmt=sqlsrv_query($conn, $sql_tdata);
$today_output_num=0;
$today_input_num=0;
$wo_num=0;


if ($stmt) {
    $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC);
    $today_output_num=$row[0]==null?0:$row[0];
    $today_input_num=$row[1]==null?0:$row[1];
	$wo_num=$row[2]==null?0:$row[2];
    sqlsrv_free_stmt($stmt);
}

$completed_rate=0;
if ($today_input_num!=0) {
    $completed_rate=$today_output_num/$today_input_num;
}







$response['code']=200;
$response['qualified_rate']=$qualified_rate;
$response['eff_rate']=$eff_rate;
$response['completed_rate']=$completed_rate;

// header('Content-Type:application/json;charset=utf-8;');
echo json_encode($response);
