<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Throwable;
use Exception;
use Carbon\Carbon;
use Illuminate\Validation\Rule;
use App\Http\Controllers\BaseController;
use App\Services\User\IUserService;
use Illuminate\Support\Facades\Auth;

class UserController extends BaseController
{
    private $time;
    private $userService;

    public function __construct(IUserService $userService)
    {
        $this->time = Carbon::now()->format('Y-m-d H:i:s');
        $this->userService = $userService;
    }

    /**
     * 用户登录
     * @return array
     * @date 2020/11/26
     * @author live
     */
    public function getLogin(Request $request)
    {
        return view('login.index', []);
        //$key = env('DD_APP_KEY');
        //$redirectUri = env('REDIRECT_URL');
        //$url = 'https://oapi.dingtalk.com/connect/qrconnect?appid='.$key.'&response_type=code&scope=snsapi_login&state=STATE&redirect_uri='.$redirectUri;
        //return redirect($url);
    }

    /**
     * 钉钉回调
     * @return array
     * @date 2020/11/26
     * @author live
     */
    public function getReturnLogin(Request $request)
    {
        $Input = $request->all();
        try {
            $data = $this->userService->getUserLogin($Input['code']);
            Auth::login($data);
            return redirect('/apk/list');
        } catch (Exception $e) {
         return $this->getErrorMsg($e->getCode(), $e->getMessage());
         }
    }


    /**
     * 用户登出
     * @return array
     * @date 2020/11/26
     * @author live
     */
    public function getLogout(Request $request)
    {
        Auth::logout();
        return redirect('/');
    }
    /**
     * 用户列表
     * @return array
     * @date 2020/11/19
     * @author live
     */
    public function getUserList(Request $request)
    {
        $name = $request->get('name', '');
        $data['LISTS'] = $this->userService->getUserList($name);
        $data['NAME'] = $name;
        return view('user.list', $data);
    }

    /**
     * 设置用户状态
     * @return array
     * @date 2020/11/19
     * @author live
     */
    public function getUserSetStatus(Request $request)
    {
        $postData = $request->all();
        $validate = Validator::make($postData, [
            'id' => 'required|numeric',
            'status' => 'required|numeric'
        ]);
        if ($validate->fails()) return $this->getErrorMsg('1001', config('msg.common.1001'));
        try {
            $data = $this->userService->getUserSetStatus($postData);
            return $this->getSuccessMsg($data);
        } catch (Exception $e) {
            return $this->getErrorMsg($e->getCode(), $e->getMessage());
        }
    }
}
