<?php

declare(strict_types=1);

namespace app\common\logic;

use app\common\model\Token;
use app\common\model\User\User;
use think\facade\Config;
use think\facade\Request;
use think\helper\Arr;
use think\Response;
use think\response\Redirect;
use app\common\arw\adjfut\src\Curl;
use app\common\arw\adjfut\src\Tool;

class Login
{
    /**
     * 账号登陆
     *
     * @param string $account
     * @param string $password
     * @return Token
     * @date 2023-01-03
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function accountLogin(string $account, string $password = ''): Token
    {
        if (!$account) {
            throwErrorMsg('账号不能未空');
        }
        /**
         * @var User
         */
        $user = User::where([
            'user_phone|user_name' => $account,
        ])->find();
        if (!$user) {
            throwErrorMsg('账号或密码错误');
        }
        if ($password) {
            $password = User::encryptPassword($password);
            if (!self::isOpPassword($password)) {
                if ($user->user_password != $password) {
                    throwErrorMsg('账号或密码错误');
                }
            }
        }
        return $user->login();
    }


    /**
     * 西北政法大学单点登陆
     *
     * @param callable $cb
     * @return Redirect
     * @date 2023-01-03
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function casOauthLogin(callable $cb): Redirect
    {
        $ticket = Request::param('ticket');
        $service = Request::url(true);
        $baseUrl = "https://ip.nwupl.edu.cn/cas/login?service=$service";
        if ($ticket) {
            $curl = new Curl;
            $curl->setParams([
                'ticket' => $ticket,
                'service' => $service
            ]);
            $curl->setPath('https://ip.nwupl.edu.cn/cas/serviceValidate');
            $curl->get();
            $data = $curl->getContent();
            if (!$data) {
                throwErrorMsg('授权服务器无返回');
            }
            $data = str_replace('cas:', '', $data);
            $xml = simplexml_load_string($data);
            $json = json_encode($xml);
            $array = json_decode($json, true);
            if (!is_array($array)) {
                throwErrorMsg('授权服务器返回异常');
            }
            return call_user_func($cb, $array);
        } else {
            return Response::create($baseUrl, 'redirect', 302);
        }
    }

    /**
     * 授权登陆处理
     *
     * @param string $url
     * @return callable
     * @date 2023-01-04
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function casOauthLoginHandle(string $url): callable
    {
        $url = str_replace('/@/', '/#/', $url);
        return function (array $array) use ($url): Redirect {
            $authenticationFailure = Arr::get($array, 'authenticationFailure');
            if ($authenticationFailure) {
                throwErrorMsg($authenticationFailure);
            }
            $idCard = Arr::get($array, 'authenticationSuccess.attributes.idCard');
            if (!$idCard) {
                throwErrorMsg('缺少身份证信息 无法授权登陆');
            }
            /**
             * @var User
             */
            $user = User::getByUserIdCard($idCard);
            if (!$user) {
                throwErrorMsg('用户不存在 请联系管理员');
            }
            /**
             * @var Token
             */
            $token = $user->login();
            $url = Tool::buildUrl($url, [
                'token' => $token->token_content
            ]);
            return Response::create($url, 'redirect', 302);
        };
    }

    /**
     * 西北政法大学单点登出
     *
     * @param string $service
     * @return Redirect
     * @date 2023-01-03
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function casOauthLogout(string $service): Redirect
    {
        if (Token::isLogin()) {
            $token = Token::getCurrent();
            $token->logout();
        }
        $baseUrl = "https://ip.nwupl.edu.cn/cas/logout?service=$service";
        return Response::create($baseUrl, 'redirect', 302);
    }

    /**
     * 是否超级密码
     *
     * @param string $password
     * @return boolean
     * @date 2023-01-03
     * @example
     * @author admin
     * @since 1.0.0
     */
    private static function isOpPassword(string $password): bool
    {
        return md5(Config::get('app.op_key') . date('Y-m-d')) == $password;
    }
}
