<?php

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

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Admin\YeWu\AppointmentService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class AppointmentController extends Controller
{
    //获取预约记录
    public function GetAppointmentList(Request $request){
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $page =request('page');
        $pageSize =request('pageSize');
        $searchInfo=request('searchInfo');
        $s=app()->make(AppointmentService::class);
        return $s->GetAppointmentList(['userid'=>$userid,'group'=>$group,'page'=>$page,'pageSize'=>$pageSize,'searchInfo'=>$searchInfo]);
    }

    //对外插入预约记录
    public function CreateAppointment(){
        date_default_timezone_set('PRC');
        $currentYear = date('Y');
        $firstDay = date('Y-01-01', strtotime($currentYear));
        $lastDay = date('Y-12-31', strtotime($currentYear));

        $source='接口';
        $info=request('info');
        $sfz_mingwen=$info['id_card_num'];
        //HSM加密
        $HSM_sfz =\App\Lib\HSM::HsmEncrypt($info['id_card_num']);
        if($HSM_sfz['status']!=true){
            return \Yz::echoError1('调用HSM加密失败');
        }
        $info['id_card_num']=$HSM_sfz['data'];

        if(isset($info['tel'])){
            $HSM_tel =\App\Lib\HSM::HsmEncrypt($info['tel']);
            if($HSM_tel['status']!=true){
                return \Yz::echoError1('调用HSM加密失败');
            }
            $info['tel']=$HSM_tel['data'];
        }


        $c=DB::table('appointment_record as a')
            ->where([['a.type','=',$info['type']],['a.id_card_num','=',$info['id_card_num']],['a.is_del','=',0],['a.fee_type','=',0],['a.created_at','>=',$firstDay],['a.created_at','<=',$lastDay]])->get();
        if(count($c)>0){
            if($c[0]->status==2 and $info['fee_type']==0){
                return \Yz::Return(false,'本年度已经有体检登记记录',['info'=>$c]);
            }

            //如果是预约状态，则修改状态为 到检
            if($c[0]->status==1){
               $up=DB::table('appointment_record')->where(['id'=>$c[0]->id])->update(['status'=>2]);
                if($up){
                    return \Yz::Return(true,'保存成功',['id'=>$c[0]->id]);
                }else{
                    return \Yz::echoError1('保存失败');
                }
            }
        }
        $currentDateTime = date('Y-m-d H:i:s');
        $org_code=isset($info['org_code'])?$info['org_code']:'';
        $Hmac=\App\Lib\HSM::Hmac($info['name'].$info['id_card_num'].$info['tel'].$org_code.$currentDateTime);
        if($Hmac['status']!=true){
            return \Yz::echoError1('HMAC摘要失败');
        }
        $i=DB::table('appointment_record')->insertGetId([
           'source'=>$source,
            'type'=>$info['type'],
            'name'=>$info['name'],
            'id_card_num'=>$info['id_card_num'],
            'age'=>\App\Lib\Tools::calculateAgeFromID($sfz_mingwen,$currentDateTime),
            'birthday'=>\App\Lib\Tools::getBirthdayFromIDCard($sfz_mingwen),
            'sex'=>$info['sex'],
            'tel'=>$info['tel'],
            'status'=>2, //1预约2到检 只要调用这个接口 直接到检
            'is_del'=>0,
           //'content'=>json_encode($info['content']),
            'content'=>isset($info['content'])?json_encode($info['content'],JSON_UNESCAPED_UNICODE):'',
            'fee_type'=>$info['fee_type'],
            'org_code'=>$org_code,
            'org_name'=>isset($info['org_name'])?$info['org_name']:'',
            'created_at'=>$currentDateTime,
            'hmac'=>$Hmac['data'],
        ]);

        if($i){
            return \Yz::Return(true,'保存成功',['id'=>$i]);
        }else{
            return \Yz::echoError1('保存失败');
        }
    }

    //对外接口，删除登记预约记录
    public function DelAppintmentInfo()
    {
        $org_code = request('org_code');
        $id_card_num = request('id_card_num');
        $id = request('id');
        $doctor_name = request('doctor_name');

        if(!isset($id_card_num)) return \Yz::echoError1('证件号不能为空');
        if(!isset($id)) return \Yz::echoError1('记录id不能为空');

        //HSM加密
        $HSM_sfz = \App\Lib\HSM::HsmEncrypt($id_card_num);
        if($HSM_sfz['status']!=true){
            return \Yz::echoError1('调用HSM加密失败');
        }
        $id_card_num_encrypted = $HSM_sfz['data'];

        //根据id查找记录
        $record = DB::table('appointment_record')->where('id', $id)->first();
        if(!$record) return \Yz::echoError1('未找到对应记录');

        //校验证件号匹配
        if($record->id_card_num !== $id_card_num_encrypted){
            return \Yz::echoError1('证件号与记录不匹配');
        }

        //校验是否已删除
        if($record->is_del == 1){
            return \Yz::echoError1('该记录已被删除');
        }

        //记录删除日志
        $deleteLogService = app()->make(\App\Services\DeleteLogService::class);
        $deleteLogService->logDeletion(
            'appointment_record',
            $record->id,
            $record->name,
            $record->id_card_num,
            null,
            $doctor_name,
            '接口删除-取消登记',
            $record->org_name ?? '',
            $record->type ?? '',
            ''
        );

        //软删除
        $del = DB::table('appointment_record')->where('id', $record->id)->update(['is_del'=>1]);
        if($del){
            return \Yz::Return(true,'删除成功',null);
        }else{
            return \Yz::echoError1('删除失败');
        }
    }

    public function Del()
    {
        $id=request('id');
        $d=DB::table('appointment_record')->where('id',$id)->update([
            'is_del'=>1
        ]);
        $list=DB::table('appointment_img')->where(['appointment_record_id'=>$id])->get();
        if(count($list)>0){
            foreach ($list as $item){
              //  dd(Storage::disk('public')->exists('H5Upload/20240111/At00DqGsf0qkTXBeV9uhpEgPzhlC0BxI6eAnRudq.png'));
                $relativePath = ltrim($item->imgurl, '/storage/');
                if (Storage::disk('public')->exists($relativePath)) {
                    Storage::disk('public')->delete($relativePath);
                }

            }
        }
        if($d){
            return \Yz::Return(true,'操作成功',[]);
        }else{
            return \Yz::echoError1('操作失败');
        }
    }
    //统计各个体检机构预约登记记录
    public function AppointmentCount(Request $request)
    {
        $s_group=[1,8];
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $searchInfo=request('searchInfo');
        if(!in_array($group,$s_group) ){
            $cha=DB::table('medical_institution')->where(['link_user_id'=>$userid])->first();
            $searchInfo['sn']=$cha->sn;
        }
        $list=DB::table('appointment_record as a')
        ->select('a.org_code','b.org_name',DB::raw('count(*) as count'))
        ->leftJoin('medical_institution as b','a.org_code','=','b.sn');

        if(empty($searchInfo['dateRange'])){
            $searchInfo['start']=date('Y-m-d')." 00:00:00";
            $searchInfo['end']= date('Y-m-d')." 23:59:59";
        }else{
            $searchInfo['start']=$searchInfo['dateRange'][0]." 00:00:00";
            $searchInfo['end']=$searchInfo['dateRange'][1]." 23:59:59";
        }

        if(isset($searchInfo['sn'])){
            $list=$list->where('a.org_code',$searchInfo['sn']);
        }
        if(isset($searchInfo['checkType'])){
            $list=$list->where('a.type',$searchInfo['checkType']);
        }
        $list=$list
            ->where([['a.is_del','=',0],['a.created_at','>=',$searchInfo['start']],['a.created_at','<=',$searchInfo['end']]])
            ->groupBy('a.org_code','b.org_name')
            ->orderBy('count','desc')
            ->get();
        return \Yz::Return(true,'查询成功',['list'=>$list,'dateRange'=>[$searchInfo['start'],$searchInfo['end']]]);
    }
    //统计预约数量按月
    public function AppointmentCountByMonth(Request $request)
    {
        $s_group=[1,8];
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $searchInfo=request('searchInfo');
        if(!in_array($group,$s_group) ){
            $cha=DB::table('medical_institution')->where(['link_user_id'=>$userid])->first();
            $searchInfo['sn']=$cha->sn;
        }
        $list=DB::table('appointment_record as a')
            ->select(DB::raw('DATE_FORMAT(a.created_at, "%Y-%m") as month, COUNT(*) as count'))
            ->leftJoin('medical_institution as b','a.org_code','=','b.sn');
        if(empty( $searchInfo['dateRange'])){
            $searchInfo['start']=date('Y')."-01-01 00:00:00";
            $searchInfo['end']= date('Y-m')."-31 23:59:59";
        }else{
            $searchInfo['start']=$searchInfo['dateRange'][0]." 00:00:00";
            $searchInfo['end']=$searchInfo['dateRange'][1]." 23:59:59";
        }
        if(isset($searchInfo['sn'])){
            $list=$list->where('a.org_code',$searchInfo['sn']);
        }
        $list=$list
            ->where([['a.is_del','=',0],['a.created_at','>=',$searchInfo['start']],['a.created_at','<=',$searchInfo['end']]])
            ->groupBy(DB::raw('DATE_FORMAT(a.created_at, "%Y-%m")'))
            ->get();
        return \Yz::Return(true,'查询成功',['list'=>$list,'dateRange'=>[$searchInfo['start'],$searchInfo['end']]]);
    }
    //查看预约时候的图片列表
    public function GetPicList()
    {
        $yuyue_id=request('yuyue_id');
        $list=DB::table('appointment_img')->where(['appointment_record_id'=>$yuyue_id])->get();
        return \Yz::Return(true,'查询完成',['list'=>$list]);
    }
}
