<?php

namespace App\Http\Controllers\API\CAS;

use App\Http\Controllers\API\His\HisController;
use App\Http\Controllers\Controller;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use JWT;


class CasLoginController extends Controller
{
    public static $request;
    public static $CasUrl='http://192.168.80.53:8085/cas/serviceValidate';
    public function login(Request $request){
        $ticket = $request->query('ticket');
        $url=env('APP_URL').'/casLogin';
        $data = [
            'ticket' => $ticket,
            'service' => $url,
        ];
        self::RequestLog(self::$CasUrl , $data, "cas认证", 'CAS接口');
        $response = Http::get(self::$CasUrl,$data);

        if (!$response->successful()) {
            self::$request->response_data = "请求Roc接口失败";
            self::$request->save();
            return \Yz::JsonError("请求CAS失败");
        }

        // 处理成功的响应
        $res_string = $response->body();
        // dd($res_string);
        $str_len = mb_strlen($res_string, 'utf-8');
        $str_size = $str_len / 1024;
        $save_res = $res_string;
        if ($str_size > 10) $save_res = '{"data":"Row size too large"}';
        self::$request->response_data = $save_res;
        self::$request->save();


        $xml = simplexml_load_string($response->body());
        // 注册命名空间
        $namespaces = $xml->getNamespaces(true);

// 获取 cas 命名空间下的元素
        $cas = $xml->children($namespaces['cas']);

        if ($cas === false) {
            return \Yz::JsonError("解析CAS响应失败");
        }


        if (isset($cas->authenticationFailure)) {
            return \Yz::JsonError("认证失败");
        }

        $casResponse = $cas->authenticationSuccess;

        if (!$casResponse) {
            return \Yz::JsonError("认证失败");
        }

        $res_user = (string)$casResponse->user;

        $user=DB::table('users')->where(['cas_code'=>$res_user,'status'=>1])->first();
        if(!!$user){
            $send_his_data=[
                'docCode'=>$res_user
            ];
            $res = HisController::Get("查询医生有权限的科室", $send_his_data);
            $dept_arr=[];
            $deptIdsString='';
            $user_group=$user->group;
            if ($res['code'] == 200) {
                $res_data = $res['data'];
                if(is_array($res_data)){


                    $deptCodes = array_column($res_data, 'deptCode');
                    $dbDepts = DB::table('s_department')
                        ->whereIn('department_number', $deptCodes)
                        ->where('is_del', 0)
                        ->pluck('id', 'department_number'); // key: deptCode, value: id

                    foreach ($res_data as $v) {
                        if (isset($dbDepts[$v['deptCode']])) {
                            $dept_arr[] = [
                                'deptName' => $v['deptName'],
                                'deptId'   => $dbDepts[$v['deptCode']],
                            ];
                        }
                    }
                    $deptIdsString = implode(',', array_column($dept_arr, 'deptId'));
                    if(count($deptCodes)==1 and !empty($res_data[0]['deptType']) and in_array($user_group,[2,3])){
                        if($res_data[0]['deptType']=="N") $user_group=3;//护士
                        if($res_data[0]['deptType']=="I") $user_group=2;//病区护士
                    }
                }
            }
            $jwt= new JWT();
            $accessTimeout = $jwt -> GetGetSecretTimeOut();
            $refreshTimeout = $jwt -> GetRefreshTokenTimeOut();
            $access_token = $jwt->BuildJWT('yz','access',$user->id,$user_group,$accessTimeout);
            $refresh_token = $jwt->BuildJWT('yz','refresh',$user->id,'',$refreshTimeout);
            DB::table('users')->where(['id'=>$user->id,'status'=>1])->update(['token'=>md5($refresh_token),'group'=>$user_group,'department_ids'=>$deptIdsString]);
            return redirect(env('APP_URL')."/admin/#/caslogin?access_token=".$access_token."&refresh_token=".$refresh_token."&dept_arr=".urlencode(json_encode($dept_arr)));
        }else{
            echo "登录失败，未授权或者已注销";
        }




    }

    public static function RequestLog($url, $post_data, $mark, $code = 0)
    {
        self::CheckTableName();
        foreach ($post_data as $key => $post_datum) {
            $str_len = mb_strlen(json_encode($post_datum, JSON_UNESCAPED_UNICODE), 'utf-8');
            $str_size = $str_len / 1024;
            if ($str_size > 10) {
                $post_data["$key"] = 'Row size too large';
            }
        }
        $post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        self::$request->code = $code;
        self::$request->mark = $mark;
        self::$request->post_data = $post_data == '[]' ? '{}' : $post_data;
        self::$request->request_url = $url;
        self::$request->save();
    }

    public static function CheckTableName()
    {
        $table_name = 'zz_peis_log_' . date('ym');
        $table_count = DB::select('select count(1) as c from information_schema.TABLES where table_schema = ? and table_name = ?', [env('DB_DATABASE'), $table_name])[0];
        if ($table_count->c === 0) {
            Schema::create($table_name, function (Blueprint $table) {
                $table->id();
                $table->string('code', 50)->index();
                $table->string('mark', 50)->index();
                $table->text('post_data');
                $table->text('response_data')->nullable();
                $table->string('request_url', 2000);
                $table->timestamps();
            });
        }
        self::$request = new \App\Models\PEISLog();
        self::$request->setTable($table_name);
    }
}
