<?php

namespace app\controller\api;

use app\extra\basic\Base;
use app\extra\tools\CodeExtend;
use app\extra\weMini\Crypt;
use app\middleware\WxMiddleware;
use app\model\blue\BlueCategory;
use app\model\blue\BlueExpertPlatform;
use app\model\blue\BlueUserOpen;
use DI\Attribute\Inject;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Middleware;
use LinFly\Annotation\Route\Route;
use Shopwwi\WebmanAuth\Facade\Auth as AuthMode;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

#[Controller(prefix: "/wx_api/auth"),Middleware(WxMiddleware::class)]
class Auth extends Base
{

    protected array $noNeedLogin = ["loginCodeData"];

    #[Inject]
    protected BlueUserOpen $model;


    /**
     * 微信code登录
     * @param Request $request
     * @return Response
     */
    #[Route(path: "loginCode",methods: "post")]
    public function loginCodeData(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "code.require"  => trans("empty.require")
            ],$request->method());
            if (!is_array($param)) return error($param);
            $userinfo = (new Crypt([
                "appid"     => sConf("wechat.mini_appid"),
                "appsecret" => sConf("wechat.mini_secret")
            ]))->session($param['code']);
            if (!isset($userinfo['openid'])) return error("获取数据失败");
            $map = ['openid' => $userinfo['openid']];
            $userOpen = $this->model->where($map)->findOrEmpty();
            if ($userOpen->isEmpty()) {
                $userOpen->insertGetId(['openid' => $userinfo['openid'],"create_ip" => $request->getRealIp(),"nickname" => "wx_".strtoupper(CodeExtend::random(5,3)),"headimg" => "https://blue-data.oss-cn-guangzhou.aliyuncs.com/logo.png"]);
                $userOpen = $this->model->where($map)->findOrEmpty();
            }
            $userAuth = get_object_vars(AuthMode::guard("member")->login($userOpen->toArray()));
            return success("ok",['token' => $userAuth]);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}