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


$starttime=date('Y-m-d 0:0:0');
$endtime=date('Y-m-d H:i:s');
$mode="今日";
//缺陷情况
switch ($config['work_order']['defect_search_mode']) {
    //2:查本周计划
    case '2':
        $starttime=date('Y-m-d 00:00:00', strtotime('Monday this week'));
        $endtime=date('Y-m-d 23:59:59', strtotime('Sunday this week '));
		$mode="本周";
        break;
    //3:查本月计划
    case '3':
        $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'));
		$mode="本月";
        break;
    
    //默认仅查当日
    default:
        $starttime=date('Y-m-d 00:00:00');
        $endtime=date('Y-m-d 23:59:59');
}



$sql=' SELECT TOP 5  [InspDetail].[DefName],[InspDetail].[DefCode],cast(sum([InspDetail].[InspNum]) as int) as [InspNumSum]  FROM  [dbo].[InspRecord] INNER 

JOIN [dbo].[InspDetail] ON [dbo].[InspRecord].[InspId]=[dbo].[InspDetail].[InspId] ';
$sql.=' INNER JOIN [dbo].[ProcessWork]  ON [dbo].[ProcessWork].[ProcessWorkNo]=[dbo].[InspRecord].[ProcessWorkNo] WHERE ';
$conditions=array();
if ($is_producing_line==1) {
    foreach ($producingLines as $depid=>$wc) {
        if (isset($wc['checked']) && $wc['checked']==1) {
            $conditions[]=$depid;
        }
    }
    $t_pdls=implode(",", $conditions);
    $sql.=" [dbo].[ProcessWork].[DepId] IN  ({$t_pdls}) ";
} else {
    $t_workcenters=implode(",", $workcenters);
    $sql.=" [dbo].[InspRecord].[CenterId] IN  ({$t_workcenters}) ";
}


$sql.=" AND  [dbo].[InspRecord].[Status]=2   AND [dbo].[InspRecord].[TestTime]>='{$starttime}' AND [dbo].[InspRecord].[TestTime]<'{$endtime}' Group By 

[InspDetail].[DefCode],[InspDetail].[DefName] Order By InspNumSum Desc";


$stmt=sqlsrv_query($conn, $sql);
$insp=array();
$insp['items']=array();
$insp['data']=array();
$total=0;
if ($stmt) {
    while ($row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
        $insp['items'][]=$row[0];
        $total+=$row[2];
        $insp['data'][]=array('name'=>$row[0],'value'=>round($row[2], 0));
    }
}

if ($stmt) {
    sqlsrv_free_stmt($stmt);
}
$insp['data2']=array();
foreach ($insp['data'] as $k=>$v) {
    if ($total!=0) {
        $insp['data2'][$k]['value']=round($insp['data'][$k]['value']/$total*100, 2);
    } else {
        $insp['data2'][$k]['value']=0;
    }
}
$response['code']=200;
$response['insp']=$insp;
$response['mode']=$mode;
echo json_encode($response);
