<?php

namespace App\Http\Controllers\API\Admin\YeWu;

use App\Http\Controllers\API\Third\CSharpController;
use App\Http\Controllers\Controller;
use App\Services\Admin\YeWu\PlanListService;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Tools;

class WorkMainController extends Controller
{

    //获取主工作列表详情
    public function getMainDetail()
    {
        date_default_timezone_set('PRC');
        $regnum = request('regnum');
        $entrustids = request('entrustid');
        $episodeid = request('episodeid');
        $appointment_type=request('appointment_type');

        $arrayEntrustids = explode(",", $entrustids);
        $info = DB::table('s_list as a')->where(['a.reg_num' => $regnum, 'a.episodeid'=>$episodeid,'a.is_nullify'=>0])
            ->select('a.*','c.period_begin_time','c.period_end_time')
            ->leftJoin('s_period as c','a.reservation_time','=','c.id')
            ->whereIn('a.entrust_id',$arrayEntrustids)
            ->get();
        if (!$info) return \Yz::echoError1('没有找到对应医嘱信息');
        $itemInfo=[];
        foreach ($info as $value){
           $ii = DB::table('s_check_item as a')
               ->leftJoin('s_check_item_device as b','a.id','=','b.item_id')
                ->where(['a.item_name' => $value->entrust,'a.status'=>1,"a.is_del"=>0])->get();
            $source=null;
           if(!empty($value->reservation_sources)){
               $source=DB::table('s_department_resources')->where(['id'=>$value->reservation_sources])->first();
           }
            $value->department_resources=$source;
            $value->user_sex_label='';
           if($value->user_sex==1){
               $value->user_sex_label='男';
           }
           if($value->user_sex==2){
               $value->user_sex_label='女';
           }
           $value->age=\Tools::getAgeFromBirthday($value->user_brithday);
           //患者类型
            $p_type=config('app.globals.患者类型');
           $value->patient_type_label=$p_type[$value->patient_type] ?? '';
            //星期
            $value->weekday_label=\Tools::GetWeekName($value->reservation_date);

           $msg='';

           if(count($ii)==0){
               $msg="检查项目不可用";
           }
           if(count($ii)>0 ){
               if(empty($ii[0]->device_id)){
                   $msg="检查项目未关联服务组";
               }

               $qudaos = explode(',', $ii[0]->reservation_method);
               if (!in_array($appointment_type, $qudaos)){
                   $msg=$msg.',该项目不支持在此渠道预约';
               }
//               if(isset($ii[0]->check_begin_time)){  //判断开医嘱后多久能预约
//                   $entrust_time = $value->entrust_date . ' ' . $value->entrust_time;  //医嘱时间
//                   $date = new DateTime($entrust_time);
//                   $date->modify("+" . $ii[0]->check_begin_time . " minutes");
//                   $enableCheckTime = $date;//到此时间后可进行预约
//                   $current_time = new DateTime();
//                   if ($current_time < $enableCheckTime){
//                       $msg=$msg.",请于" . $enableCheckTime->format("Y-m-d H:i:s") . "后进行预约";
//                   }
//               }

           }
            $generator = new \Picqer\Barcode\BarcodeGeneratorHTML();
            $tiaoma= $generator->getBarcode($value->app_num, $generator::TYPE_CODE_128, 2, 40);
            $updatedHtml = preg_replace('/background-color:\s*black\s*;/i', 'background-color: black !important;', $tiaoma);
            $value->barcode=$updatedHtml;
            $itemInfo[]=[
                'maininfo'=>$value,
                'iteminfo'=>$ii,
                'msg'=>$msg
            ];
        }
//        $itemInfo = DB::table('s_check_item')
//            ->whereIn('item_name',)
//            ->where(['item_name' => $info->entrust,'status'=>1,"is_del"=>0])->get();
//        if (count($itemInfo) == 0) return \Yz::echoError1('没有找到可用的检查项目信息');
//        $itemInfo=$itemInfo[0];
        return \Yz::Return(true,'查询完成',['today_date'=>date("Y-m-d"),'info'=>$itemInfo]);
    }
    public function GetList(Request $request)
    {
        $searchInfo = request('searchInfo');
        $page = request('page');
        $pageSize = request('pageSize');

        $userid = $request->get('userid');//中间件产生的参数
        $userInfo = DB::table('users')->where(['id' => $userid])->get();
        $department_id = $userInfo[0]->department_id;
        $department = DB::table('s_department')->where(['id' => $department_id,'is_del'=>0])->first();
     //   if(!$department) return \Yz::echoError1('科室信息不存在');

        $list=DB::table('s_list')
            ->leftJoin('s_period','s_list.reservation_time','=','s_period.id')
            ->leftJoin('s_department_resources','s_list.reservation_sources','=','s_department_resources.id')
            ->select('s_list.*','s_period.period_begin_time','s_period.period_end_time','s_department_resources.department_resources_name')
            ->where(['s_list.is_del'=>0,'s_list.is_nullify'=>0]);
        if($userInfo[0]->group==2){
          //  $list=$list->whereIn('warddesc', explode(",", $userInfo[0]->ward));
            $list=$list->where(['wardcode'=> $department->department_number]);
        }elseif($userInfo[0]->group==7){//如果是医生则查开立申请单的科室,用于his医生客户端直接跳转过来

            $list=$list->where(['reservation_department'=>$department->department_name]);
        }else{
            $list=$list->where(['RISRAcceptDeptCode'=>$department->department_number]);
        }
        if ($searchInfo['dateRange']!=null and count($searchInfo['dateRange']) == 2) {
            $list = $list->where(function ($q) use($searchInfo) {
                $q->whereBetween('s_list.entrust_date', $searchInfo['dateRange'])
                    ->orWhereBetween('s_list.reservation_date', $searchInfo['dateRange']);
            });

        }
        if (isset($searchInfo['list_status'])) {
            $list = $list->where('s_list.list_status', $searchInfo['list_status']);
        }
        if (isset($searchInfo['patient_type'])) {
            $list = $list->where('s_list.patient_type', $searchInfo['patient_type']);
        }
        if (!empty($searchInfo['resources'])) {
            $list = $list->whereIn('s_list.reservation_sources', $searchInfo['resources']);
        }
        if (isset($searchInfo['services_group'])) {
            $list = $list->whereRaw("FIND_IN_SET({$searchInfo['services_group']}, s_list.services_group)");
        }
        if (isset($searchInfo['reg_num'])) {
            $list = $list->where('s_list.reg_num', $searchInfo['reg_num']);
        }
        if (isset($searchInfo['user_name'])) {
            $list = $list->where('s_list.user_name', 'like','%'.$searchInfo['user_name'].'%');
        }
        if (isset($searchInfo['doctor'])) {
            $list = $list->where('s_list.docotr', 'like','%'.$searchInfo['doctor'].'%');
        }
        if (isset($searchInfo['apply_department'])) {
            $list = $list->where('s_list.reservation_department', 'like','%'.$searchInfo['apply_department'].'%');
        }

        $count = $list;
        $count = $count->count();
        $list=$list->orderBy('id', 'desc')->limit($pageSize)->skip(($page - 1) * $pageSize) // 跳过前9999条记录
        ->take($pageSize)->get();

        //匹配设备（服务组）
        $devices = DB::table('s_devices')->get();
        foreach ($list as $key => $value) {
            $list[$key]->age = Tools::calculateAgeText($value->user_brithday);
            $list[$key]->devices = [];
            $array_device_id = explode(",", $value->services_group);
            foreach ($devices as $k => $v) {
                if (in_array($v->id, $array_device_id)) {
                    $list[$key]->devices[] = $v;
                }
            }
        }
        return \Yz::Return(true,'查询完成',['list'=>$list,'count'=>$count]);
    }

    //获取医嘱变更日志
    public function GetLoglist()
    {
        $id = request('id');
        $List=DB::table('s_list_log')->where(['list_id'=>$id])->orderBy('id','desc')->get();
        return \Yz::Return(true,'查询完成',$List);
    }

    //批量检查医嘱检查项目是否可以同时预约（如果关联的是同一个服务组则可以同时预约）返回可同时预约的row_id
    public function CheckEntrstItemGroup()
    {
        $list=[];
        $rowids=[];
        $itemNames=[];
        $items= request('items');
        if(!empty($items)){
            $FirstItemDevices=[];
            foreach ($items as $key=>$val){
                if($val['first']==1){
                    //获取点击的检查项目关联的设备id
                    $FirstItemDevices=  DB::table('s_check_item as a')
                        ->leftJoin('s_check_item_device as b','a.id','=','b.item_id')
                        ->select('b.device_id')
                        ->where(['a.item_name'=>$val['name'],'a.is_del'=>0,'a.status'=>1])
                        ->whereNotNull('b.device_id')
                        ->pluck('b.device_id')->toArray();
                    $FirstItem= DB::table('s_check_item as a')
                        ->where(['a.item_name'=>$val['name'],'a.is_del'=>0,'a.status'=>1])->first();
                    if(!$FirstItem) return \Yz::echoError1('此医嘱项目无效,请检查项目设置');
                }
                $itemNames[]=$val['name'];
            }
            //获取所有传过来的检查项目关联的设备,并且只有设置相同的医嘱后等待时间才能同时勾选
            $ItemsDevices=  DB::table('s_check_item as a')
                ->leftJoin('s_check_item_device as b','a.id','=','b.item_id')
                ->leftJoin('s_devices as c','b.device_id','=','c.id')
                ->whereIn('a.item_name',$itemNames)->where(['a.is_del'=>0,'a.status'=>1,'check_begin_time'=>$FirstItem->check_begin_time])->get();
            //按照第一个勾选的检查项目关联的设备进行分组，能在一个设备上进行检查的分在一组

            if(!empty($FirstItemDevices)){
                $group=[];
               foreach ($FirstItemDevices as $f_key=> $value){
                   $lg=[];
                    foreach ($ItemsDevices as $v){
                        if($v->device_id==$value){
                            foreach ($items as $item){
                                if($item['name']==$v->item_name){

                                    $v->rowid[]=$item['rowid'];
                                    $rowids[]=$item['rowid'];

                                }
                            }
                            $lg[]=$v;
                        }
                    }
                    if(count($lg)>1 or count($group)==0){
                        $group[]=$lg;
                    }


               }

                return   \Yz::Return(true,'查询完成',['group'=>$group,'rowids'=>$rowids]);
            }else{
                return \Yz::echoError1('当前勾选检查项目不可进行此操作');
            }

        }else{
            return \Yz::echoError1('检查项目不能为空');
        }




    }
    //检查当前时段是否有存在已经预约的待检查项目
    public function CheckIsDaiJian()
    {
        $reg_num= request('reg_num');
        $planid=request('planid');
        $query=DB::table('s_list')->where(['reg_num'=>$reg_num,'list_status'=>1,'is_nullify'=>0])
            ->select('s_list.*','s_period.period_begin_time','s_period.period_end_time')
            ->leftJoin('s_period','s_list.reservation_time','=','s_period.id')
            ->get();
        if(count($query)>0){
            $plan=DB::table('s_source_roster_detail')->where(['id'=>$planid])->first();
            foreach ($query as $key=>$value){
                $entrustTime=[$value->reservation_date.' '.$value->period_begin_time,$value->reservation_date.' '.$value->period_end_time];
                $planTime=[$plan->date.' '.$plan->begin_time,$plan->date.' '.$plan->end_time];
                if ($entrustTime[0] <= $planTime[1] && $planTime[0] <= $entrustTime[1]) {
                    return \Yz::echoError1('当前时段存在待检项目：'.$value->entrust.'，时间：'.$value->reservation_date.' '.substr($value->period_begin_time, 0, 5).'-'.substr($value->period_end_time, 0, 5).' 请确认是否继续预约');
                }
            }
        }
        return \Yz::Return(true,'可以预约',[]);
    }
    //检查是否有超时未支付的门诊预约记录，如果有则给其取消，并恢复名额
    public function NoPayCancel()
    {
        $success_count=0;
        //检测是否有作废医嘱
        $list_zuofei=DB::table('s_list')->where(['list_status'=>1,'is_del'=>0,'is_nullify'=>1])->get();
        foreach ($list_zuofei as $key=>$item){
            $u_data=[
                'list_status' => 0,
                'reservation_date' => null,
                'reservation_time' => null,
                'reservation_sources' => null,
                'services_group' => null,
                'roster_id' => null,
                'xuhao' => null,
                'department_id'=>null,
                'appointment_type_id' => null,
                'canel_time' =>  date('Y-m-d H:i:s'),
            ];
            $u_mainList = DB::table('s_list')->where(['id' => $item->id,'list_status'=>1])->update($u_data);
            $i_log=DB::table('s_list_log')->insert([
                'list_id'=>$item->id,
                'reg_num'=>$item->reg_num,
                'old_status'=>$item->list_status,
                'new_status'=>0,
                'create_user'=>null,
                'note'=>'作废取消',
                'data'=>json_encode($u_data)
            ]);
            $u_count=false;
            if($u_mainList){
                $u_count = DB::table('s_source_roster_detail_count')->where(['roster_detail_id' => $item->roster_id, 'appointment_type_id' => $item->appointment_type_id])->decrement('used_count');
            }
            if($u_count){
                $success_count++;
            }
        }

        //检测是否有超时未支付的
        date_default_timezone_set('PRC');
        $config=DB::table('configs')->where(['label'=>'门诊缴费超时时间'])->first();
        if($config->value>0){
            $currentDateTime = Carbon::now()->subHours($config->value);
            $list=DB::table('s_list')->where([
                'list_status' => 1,
                'patient_type' => 1,
                'is_pay' => 0,
                'is_del' => 0,
                'is_nullify' => 0,
            ])
                ->where(function ($query) use ($currentDateTime) {
                    $query->whereDate('entrust_date', '<', $currentDateTime->toDateString())
                        ->orWhere(function ($q) use ($currentDateTime) {
                            $q->whereDate('entrust_date', $currentDateTime->toDateString())
                                ->whereTime('entrust_time', '<', $currentDateTime->toTimeString());
                        });
                })->get();


            foreach ($list as $key=>$item){
                $u_data=[
                    'list_status' => 0,
                    'reservation_date' => null,
                    'reservation_time' => null,
                    'reservation_sources' => null,
                    'services_group' => null,
                    'roster_id' => null,
                    'xuhao' => null,
                    'department_id'=>null,
                    'appointment_type_id' => null,
                    'canel_time' =>  date('Y-m-d H:i:s'),
                ];
                $u_mainList = DB::table('s_list')->where(['id' => $item->id,'list_status'=>1])->update($u_data);
                $i_log=DB::table('s_list_log')->insert([
                    'list_id'=>$item->id,
                    'reg_num'=>$item->reg_num,
                    'old_status'=>$item->list_status,
                    'new_status'=>0,
                    'create_user'=>null,
                    'note'=>'超时取消',
                    'data'=>json_encode($u_data)
                ]);
                $u_count=false;
                if($u_mainList){
                    $u_count = DB::table('s_source_roster_detail_count')->where(['roster_detail_id' => $item->roster_id, 'appointment_type_id' => $item->appointment_type_id])->decrement('used_count');
                }
                if($u_count){
                    $success_count++;
                }
            }
            return \Yz::Return(true,"执行完成",['success_count'=>$success_count]);
        }else{
            return \Yz::echoError1("超时参数未设置");
        }

    }
    //医生取消预约
    public function DoctorCancelYuYue()
    {
        $MainListId = request('MainListId');
        $reg_num = request('reg_num');
        $do_userid=request('do_user');
        $service = new PlanListService();
        return  $service->CancelYuYue($MainListId,$reg_num,$do_userid);
    }
    //获取某个患者全部预约记录
    public function GetPersonYuYueList()
    {
        $searchInfo = request('searchInfo');
        $reg_num = request('reg_num');
        $list=DB::table('s_list')
            ->leftJoin('s_period','s_list.reservation_time','=','s_period.id')
            ->leftJoin('s_department_resources','s_list.reservation_sources','=','s_department_resources.id')
            ->select('s_list.*','s_period.period_begin_time','s_period.period_end_time','s_department_resources.department_resources_name')
            ->where(['s_list.is_del'=>0,'s_list.is_nullify'=>0])
            ->where('s_list.reg_num', $reg_num)
            ->whereIn('list_status',[1,2,3]);

        $count = $list;
        $count = $count->count();
        $list=$list->orderBy('id', 'desc')->get();

            $qudao=DB::table('s_appointment_type')->get();
            foreach ($list as $key=>$item){
                foreach ($qudao as $q){
                    if($q->id==$item->appointment_type_id){
                        $item->qudao_name=$q->name;
                    }
                }

            }

        return \Yz::Return(true,'查询完成',['list'=>$list,'count'=>$count]);
    }

    //开单统计
    public function CountMakeList(){
        $searchInfo = request('searchInfo');
        // 基础查询
        $baseQuery = DB::table('s_list')
            ->where(['s_list.is_del' => 0, 's_list.is_nullify' => 0]);

        // 日期范围条件（如果有）
        if(isset($searchInfo['dateRange']) && !empty($searchInfo['dateRange'])){
            $startDate = $searchInfo['dateRange'][0] . ' 00:00:00';
            $endDate = $searchInfo['dateRange'][1] . ' 23:59:59';
            $baseQuery->whereBetween('s_list.created_at', [$startDate, $endDate]);
        }

        // 开单总量：克隆基础查询
        $count = clone $baseQuery;
        $count = $count->count();

        // 按月开单量：克隆基础查询
        $MonthCountList = clone $baseQuery;
        $MonthCountList = $MonthCountList
            ->select(DB::raw('DATE_FORMAT(s_list.created_at, "%Y-%m") as month'), DB::raw('count(*) as count'))
            ->groupBy(DB::raw('DATE_FORMAT(s_list.created_at, "%Y-%m")'))
            ->get();

        // 预约总量：克隆基础查询并添加条件
        $appointmentCount = clone $baseQuery;
        $appointmentCount = $appointmentCount->whereIn('s_list.list_status',[1,2,3])->count();

        return \Yz::Return(true, '操作成功', [
            'MonthCountList' => $MonthCountList,
            'Count' => $count,
            'AppointmentCount' => $appointmentCount
        ]);
    }

}
