<?php
declare(strict_types=1);
require_once __DIR__.'/contract.php';
function n6Proof(PDO $db,array $case,int $pageSize,bool $statusFlag=false):array{
    $p=$case['params'];$kind=$case['kind'];$sets=['actor'=>n6Actor($db)];$body=null;
    if($kind==='read'){
        $rows=n6Rows($db,'equipment','id=?',[$p['id']]);if(count($rows)!==1){throw new RuntimeException('Selected device disappeared');}$row=$rows[0];if((int)$row['del_flag']!==0||(int)$row['type']===11){throw new RuntimeException('Read device scope');}$sets['equipment']=$rows;$sets['restaurant']=smRows($db,'SELECT id,uuid,name FROM ydy_restaurants WHERE id=?',[$row['restaurant_id']]);
        $row['type_cn']=\app\common\enum\EquipmentType::getName($row['type']);$row['status_cn']=[1=>'在线',2=>'离线'][$row['status']]??'';$body=['code'=>0,'message'=>'','data'=>$row];
    }elseif($kind==='push'){
        $where='del_flag=0 AND type=? AND restaurant_id=?';$args=[$p['type'],$p['restaurant_id']];if(!in_array((int)$p['type'],N6_TYPES,true)){throw new RuntimeException('Weigh enum scope');}$all=n6Rows($db,'equipment',$where,$args,'id DESC');$sets['equipment']=$all;$rows=array_slice($all,((int)$p['page']-1)*5,5);$dishUuids=[];foreach($rows as $r){foreach(['left_dishes_uuid','right_dishes_uuid'] as $f){if(!empty($r[$f])){$dishUuids[]=$r[$f];}}}$dishUuids=array_values(array_unique($dishUuids));$dishRows=$dishUuids?smRows($db,'SELECT uuid,name FROM ydy_dishes WHERE uuid IN ('.implode(',',array_fill(0,count($dishUuids),'?')).')',$dishUuids):[];$sets['dishes']=$dishRows;$dishMap=array_column($dishRows,null,'uuid');
        foreach($rows as &$row){$row['type_cn']=\app\common\enum\EquipmentType::getName($row['type']);$row['status_cn']=[1=>'在线',2=>'离线'][$row['status']]??'';$row['dishes']=['left_dishes'=>$dishMap[$row['left_dishes_uuid']]??[],'right_dishes'=>$dishMap[$row['right_dishes_uuid']]??[]];}unset($row);$body=['code'=>0,'message'=>'查询成功','data'=>['rows'=>$rows,'total'=>count($all)]];
    }elseif($kind==='code'){
        if(getenv('SM7_LANE')==='C'&&(int)$p['type']===2147483646){$mysql=smLoad('mysql-columns-private.json');$native=smLoad('metadata-private.json');$sourceType=null;$targetType=null;foreach($mysql['equipment_version'] as $col){if($col['column_name']==='type'){$sourceType=$col;}}foreach($native['equipment_version'] as $col){if(strtolower($col['column_name'])==='type'){$targetType=$col;}}if(!$sourceType||$sourceType['data_type']!=='tinyint'||strpos($sourceType['column_type'],'unsigned')!==false||!$targetType||strtolower($targetType['data_type'])!=='tinyint'){throw new RuntimeException('Signed TINYINT no-match proof changed');}$versions=[];$sets['type_domain_no_match']=['source'=>$sourceType,'target'=>$targetType,'value'=>2147483646];}
        else{$versions=n6Rows($db,'equipment_version','type=?',[$p['type']],'code DESC');}$sets['versions']=$versions;$value=empty($versions)?1:$versions[0]['code']+1;$body=['code'=>0,'message'=>'获取成功','data'=>$value];
    }elseif($kind==='weigh'){
        $equipment=n6Rows($db,'equipment','code=? AND del_flag=0 AND type IN (2,3,4,7,10)',[$p['code']]);if(count($equipment)!==1){throw new RuntimeException('Weigh source no longer unique');}$sets['equipment']=$equipment;$r=$equipment[0];$uuids=array_values(array_unique(array_filter([$r['left_dishes_uuid'],$r['right_dishes_uuid']])));if(!$uuids){throw new RuntimeException('Weigh source empty');}$dishes=smRows($db,'SELECT uuid,name,category_one,file_path FROM ydy_dishes WHERE uuid IN ('.implode(',',array_fill(0,count($uuids),'?')).')',$uuids);$categories=n6Rows($db,'dishes_cate','pid=0',[],'id');$oss=n6Oss($db);$sets['dishes']=$dishes;$sets['categories']=$categories;$sets['url_config']=$oss['rows'];$dm=array_column($dishes,null,'uuid');$cm=array_column($categories,null,'id');$list=[];
        foreach(['left_dishes_uuid','right_dishes_uuid'] as $i=>$f){$d=$dm[$r[$f]]??[];if($d){$category=$cm[$d['category_one']]??[];$list[]=['position'=>$i+1,'dishinfo'=>['uuid'=>$d['uuid'],'name'=>$d['name'],'file_path'=>n6Url($d['file_path'],$oss['prefix']),'category'=>$category['ori_id']??0,'category_name'=>$category['name']??'主食']];}}$body=['code'=>0,'message'=>'查询成功','data'=>['dishes'=>$list]];
    }elseif($kind==='recipe'){
        if(!empty($sets['actor'][0]['staff_uuid'])){throw new RuntimeException('Actor staff routing changed');}$sql='SELECT '.n6Fields('recipes','a').','.n6Fields('dishes','b').' FROM ydy_recipes a JOIN ydy_dishes b ON a.dishes_uuid=b.uuid WHERE a.menu_date=? AND a.meal_times=? AND a.type=? AND a.restaurant_id=? ORDER BY a.id DESC';$rows=smRows($db,$sql,[$p['menu_date'],$p['meal_times'],$p['type'],$p['restaurant_id']]);if(count($rows)>100){throw new RuntimeException('Recipe source >100');}$rows=n6SourceDate('dishes',n6SourceDate('recipes',n6SourceDecimal('dishes',n6SourceDecimal('recipes',$rows))));$sets['recipe_join']=$rows;$oss=n6Oss($db);$sets['url_config']=$oss['rows'];foreach($rows as &$r){$r['file_path']=n6Url($r['file_path'],$oss['prefix']);$r['source_file_path']=n6Url($r['source_file_path'],$oss['prefix']);}unset($r);$body=['code'=>0,'message'=>'获取成功','data'=>$rows];
    }elseif($kind==='dining'){
        $rel=n6Rows($db,'staff_department','department_uuid=?',[$p['department_uuid']],'id');$sets['department_relations']=$rel;$children=n6Rows($db,'department','department_path LIKE ? AND status=1 AND is_show=1',['%'.$p['department_uuid'].'%'],'id');$sets['department_children']=$children;$uuids=array_values(array_unique(array_column($rel,'staff_uuid')));$staff=[];
        if($uuids){$sql='SELECT uuid,name,sex FROM ydy_staff WHERE uuid IN ('.implode(',',array_fill(0,count($uuids),'?')).') AND is_show=1 AND name LIKE ?';$args=array_merge($uuids,['%'.$p['name'].'%']);if($statusFlag){$sql.=' AND status IN (0,1)';}$sql.=' ORDER BY name ASC';$staff=smRows($db,$sql,$args);}if(count($staff)>20){throw new RuntimeException('Dining source staff >20');}$sets['visible_staff']=$staff;$menus=[];$departments=[];$data=[];
        foreach($staff as $s){$m=n6Rows($db,'date_menu','staff_uuid=? AND menu_date>=? AND menu_date<=?',[$s['uuid'],$p['start_time'],$p['end_time']],'create_time DESC,menu_date');$menus[$s['uuid']]=$m;$byMeal=[];foreach($m as $r){if(!array_key_exists($r['meal_times'],$byMeal)){$byMeal[$r['meal_times']]=$r['create_time'];}}$relations=n6Rows($db,'staff_department','staff_uuid=?',[$s['uuid']],'id');$departments[$s['uuid']]['relations']=$relations;$depIds=array_values(array_unique(array_column($relations,'department_uuid')));$names=$depIds?smRows($db,'SELECT DISTINCT name FROM ydy_department WHERE uuid IN ('.implode(',',array_fill(0,count($depIds),'?')).')',$depIds):[];$departments[$s['uuid']]['names']=$names;
            if($p['dining']==='1'&&!array_key_exists(1,$byMeal)){continue;}$n=count($byMeal);$row=$s+['menu_date'=>$p['start_time'],'flag'=>$n===3?0:($n===2?1:($n===1?2:3)),'meal_times'=>$byMeal];$data[]=$row;
        }$sets['menus']=$menus;$sets['staff_departments']=$departments;
        if($data){$flags=array_column($data,'flag');array_multisort($flags,SORT_ASC,$data);}$total=count($data);$data=array_slice($data,0,$pageSize);
        foreach($data as &$row){$times=$row['meal_times'];$row['meal_msg']=[1=>isset($times[1])?substr($times[1],11,5):0,2=>isset($times[2])?substr($times[2],11,5):0,3=>isset($times[3])?substr($times[3],11,5):0];$row['meal_info']=count($times);$row['department_name']=implode(',',array_column($departments[$row['uuid']]['names'],'name'));}unset($row);$body=['code'=>0,'message'=>'查询组织人员成功','data'=>['rows'=>$data,'total'=>$total]];
    }else{throw new RuntimeException('Unknown case kind');}
    // Match the original ThinkPHP Json serializer: FLOAT 0.0 encodes as JSON 0.
    return ['body'=>json_decode(json_encode($body,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR)),'source_sets'=>$sets,'source_digest'=>hash('sha256',serialize($sets))];
}
