<?php

namespace app\controller\v2;

use app\extra\basic\Base;
use app\extra\tools\CodeExtend;
use app\extra\weMini\Crypt;
use app\extra\weMini\UserInfo;
use app\middleware\WxMiddleware;
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;


#[Controller(prefix: "/wx_v2/user"),Middleware(WxMiddleware::class)]
class User extends Base
{

    protected array $noNeedLogin = ["loginMobile","loginQuick"];


    #[Inject]
    protected BlueUserOpen $model;


    #[Route(path: "quick",methods: "post")]
    public function loginQuick(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "code.require"  => trans("empty.require"),
                "pid.default"   => 0
            ],$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()) return error("new");
            $userAuth = get_object_vars(AuthMode::guard("member")->login($userOpen->toArray()));
            return success("ok",['token' => $userAuth]);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    #[Route(path: "login",methods: "post")]
    public function loginMobile(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "code.require"  => trans("empty.require"),
                "login.require" => trans("empty.require"),
                "pid.default"   => 0
            ],$request->method());
            if (!is_array($param)) return error($param);
            $userinfo = (new Crypt([
                "appid"     => sConf("wechat.mini_appid"),
                "appsecret" => sConf("wechat.mini_secret")
            ]))->session($param['login']);
            if (!isset($userinfo['openid'])) return error("获取数据失败");
            $mobile = (new UserInfo([
                "appid"     => sConf("wechat.mini_appid"),
                "appsecret" => sConf("wechat.mini_secret")
            ]))->getPhoneNumber($param['code']);
            if ($mobile['errcode'] <> 0) return error($mobile['errmsg']);
            $map = ['openid' => $userinfo['openid'],'mobile' => $mobile['phone_info']['purePhoneNumber']];
            $userOpen = $this->model->where($map)->findOrEmpty();
            if ($userOpen->isEmpty()) {
                $userOpen->insertGetId([
                    'openid'    => $userinfo['openid'],
                    'parent'    => $param['pid'],
                    'uuid'      => CodeExtend::uniqidNumber(),
                    'mobile'    => $mobile['phone_info']['purePhoneNumber'],
                    "create_ip" => $request->getRealIp(),
                    "nickname"  => "微信用户",
                    "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());
        }
    }

}