<?php

namespace App\Http\Controllers\API\His;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CheckItemController extends Controller
{
    public function UpdateItemClass()
    {
        $data = [
            'consTypeId' => 'EXAMSHEETTYPE'
        ];
        $His = new HisController();
        $res = $His::Get("查询所有检查项目分类", $data);
        $success_count=0;
        if ($res['code'] == 200) {
            $res_data = $res['data'];
            foreach ($res_data as $data_k => $data_v) {
                $type= DB::table('s_check_item_class')->where(['consInfoCode' => $data_v['consInfoCode']])->first();
                $data=[
                    'item_class_name'=> $data_v['consInfoName'],
                    'pid'=> 1,
                    'CTC_Code'=> $data_v['consInfoName'],
                    'CTC_Desc'=> $data_v['consInfoName'],
                    'CTC_Status'=> 1,
                    'consInfoCode'=> $data_v['consInfoCode'],
                ];
                if(!!$type){
                   $u= DB::table('s_check_item_class')->where(['id'=>$type->id])->update([
                        'item_class_name'=> $data_v['consInfoName'],
                        'CTC_Code'=> $data_v['consInfoName'],
                        'CTC_Desc'=> $data_v['consInfoName'],
                    ]);

                }else{
                    $u=  DB::table('s_check_item_class')->insert($data);
                }
                if($u) $success_count++;
            }
        }
        return \Yz::JsonReturn(true,"更新完成",['success_count'=>$success_count]);
    }
    public function UpdateCheckItem(){

        $termClassId = request('termClassId');
        if(!isset($termClassId)){
            return \Yz::echoError1('类别id不能为空');
        }

        $data=[];
        $where=[];
        if($termClassId<>'all'){  //155为检查项目 不要使用all
            $data=[
                'termClassId' => $termClassId,
            ];

        }

        $His = new HisController();
        $res = $His::Get("查询非药品列表", $data);
        if($res['code']==200){
            $res_data=$res['data'];
            if(isset($res_data['list']) and !empty($res_data['list'])){
                $db_data=DB::table('s_check_item')->get();//库里的数据
                //根据 接收数据的undrugId，和库里的item_code进行比对，如果库里存在则更新，如果库里没有则添加，如果库里有但是接收数据里没有则在库里标记is_del=0
                $db_map = [];
                foreach ($db_data as $db_item) {
                    $db_map[$db_item->item_code] = $db_item;
                }

                // 用于记录接收到的数据中的 item_code，方便后面判断哪些需要删除
                $received_ids = [];

                foreach ($res_data['list'] as $item) {
                    // 假设远程返回字段是 undrugId 和 undrugName，对应数据库字段是 item_code 和 item_name
                    $item_code = $item['undrugId'];
                    $item_name = $item['termName'];

                    // 添加到接收 ID 列表
                    $received_ids[] = $item_code;
                    $item_class_id=null;
                    $class_type=  DB::table('s_check_item_class')->where(['consInfoCode'=>$item['sheetType']])->first();
                    if($class_type and !empty($item['sheetType'])){
                        $item_class_id=$class_type->id;
                    }

                    $department_arr=[];
                    //优先取默认科室，如果存在默认则忽略范围科室。2025-06-24 与叶工微信群沟通
                    if(isset($item['defaultExecDepts']) and !empty($item['defaultExecDepts'])){
                        $department_arr=[$item['defaultExecDepts']];
                    }else{
                        if(isset($item['execDepts']) and !empty($item['execDepts'])){
                            foreach ($item['execDepts'] as $dept) {
                                $department_arr[]=$dept['code'];
                            }
                        }
                    }
                    // 快速查找是否已存在该 item_code
                    if (isset($db_map[$item_code])) {
                        // 存在则更新
                        DB::table('s_check_item')
                            ->where('item_code', $item_code)
                            ->update([
                                'item_class_id'=>$item_class_id,
                                'sheetType'=>$item['sheetType'],
                                'item_name' => $item_name,
                                'item_desc' => $item_name,
                                'is_del' => 0, // 取消删除标记
                                'hisExecDepts'=>json_encode($department_arr, JSON_UNESCAPED_UNICODE),
                                'check_notice'=>$item['docmoTip']
                            ]);
                    } else {
                        // 不存在则插入新记录
                        DB::table('s_check_item')->insert([
                            'item_class_id'=>$item_class_id,
                            'sheetType'=>$item['sheetType'],
                            'item_code' => $item_code,
                            'item_name' => $item_name,
                            'item_desc' => $item_name,
                            'reservation_method' =>'0,1,2,3,4',
                            'limosis' =>0,
                            'check_time' =>0,
                            'hisExecDepts'=>json_encode($department_arr, JSON_UNESCAPED_UNICODE),
                            'check_notice'=>$item['docmoTip']
                        ]);

                       // $this->updateBindDrivers($item_code,$department_arr);自动绑定检查室 ，废弃
                    }

                }

                // 处理数据库中存在但远程没有返回的数据，标记为删除
                foreach ($db_map as $item_code => $db_item) {
                    if (!in_array($item_code, $received_ids)) {
                        DB::table('s_check_item')
                            ->where('item_code', (string)$item_code)
                            ->update([
                                'is_del' => 1
                            ]);
                    }
                }

                return \Yz::return(true,'更新检查项目成功',[]);
            }else{
                return \Yz::echoError1('His接口返回数据为空');
            }
        }else{
            return \Yz::echoError1('更新失败');
        }
    }
    //绑定设备
    public  function updateBindDrivers($item_code,$department_arr)
    {
        $iteminfo=DB::table('s_check_item')->where('item_code',$item_code)->first();
        $departments = DB::table('s_department')->whereIn('department_number',$department_arr)->get();
        $department_ids=[];
        foreach ($departments as $department) {
            $department_ids[]=$department->id;
        }
        if(count($department_ids)>0 and !!$iteminfo){
            $devices=DB::table('s_department_resources_device')->whereIn('department_id',$department_ids)->pluck('device_id')->toArray();
            //删除库里项目和设备绑定关系
            DB::table('s_check_item_device')->where(['item_id'=>$iteminfo->id])->whereIn('device_id',$devices)->delete();
            $data=[];
            foreach ($devices as $device) {
                $data[]=[
                    'item_id' => $iteminfo->id,
                    'device_id' => $device,
                ];
            }
            if(count($devices)>0 and !!$iteminfo){
                //插入表
                DB::table('s_check_item_device')->insert($data);
            }

        }


    }
}
