<?php
namespace App\Services\User;

use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Models\UserModel;
use App\Models\OptionLogModel;
use App\Services\User\IUserService;
use Illuminate\Support\Facades\Auth;
use App\Lib\dingtalk\DingTalkConstant;
use App\Lib\dingtalk\DingTalkClient;
use App\Lib\dingtalk\request\OapiSnsGetuserinfoBycodeRequest;

class UserService implements IUserService
{
    private $time;

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

    /**
     * 用户列表
     * @return array
     * @date 2020/11/25
     * @author live
     */
    public function getUserList($name)
    {
        $pageNum = env('PAGE_NUM',20);
        $paginateAppends = [];
        $lists = UserModel::when($name != '', function ($query) use ($name) {
            return $query->where('name','like',$name.'%');
        })->select('id','name','open_id as OpenID','union_id as UnionID','status','created_at')->paginate($pageNum);

        if($name != '') $paginateAppends['name'] = $name;
        if(!empty($paginateAppends)) $lists->appends($paginateAppends);
        return $lists;
    }

    /**
     * 管理用户状态
     * @return array
     * @date 2020/11/25
     * @author live
     */
    public function getUserSetStatus($postData)
    {
        $user = UserModel::find($postData['id']);
        if(!$user) throw new Exception(config('msg.common.1003'),1003);
        $status = 0;
        if($postData['status'] == 1) $status = 1;
        $user->status = $status;
        if($user->save()){
            unset($postData['_token']);
            OptionLogModel::getAddLog('user','update',$postData,Auth::id(),$user->id,'设置用户状态');
            return $user->id;
        }
        throw new Exception(config('msg.common.1006'),1006);
    }

    /**
     * 用户登录
     * @return array
     * @date 2020/11/26
     * @author live
     */
    public function getUserLogin($code){
        $client = new DingTalkClient(DingTalkConstant::$CALL_TYPE_OAPI, DingTalkConstant::$METHOD_POST , DingTalkConstant::$FORMAT_JSON);
        $req = new OapiSnsGetuserinfoBycodeRequest;
        $req->setTmpAuthCode($code);
        $result = $client->executeWithAccessKey($req, "https://oapi.dingtalk.com/sns/getuserinfo_bycode",env('DD_APP_KEY'),env('DD_APP_SECRET'));
        if($result->errcode == 0 && $result->errmsg == 'ok'){
            $user = self::getVerity( $result->user_info,$code);
            return $user;
        }
        throw new Exception(config('msg.user.2001'),2001);
    }

    /**
     * 严重用户
     * @return array
     * @date 2020/11/26
     * @author live
     */
    public static function getVerity($userInfo,$code)
    {
        $user = UserModel::where('name',$userInfo->nick)->where('open_id',$userInfo->openid)->first();
        if($user){
            if($user->status == 0) throw new Exception(config('msg.user.2002'),2002);
            return $user;
        }else{
            //$first = UserModel::first();
            //if($first){
                //if($first->union_id != $userInfo->unionid)  throw new Exception(config('msg.user.2003'),2003);
            //}
            $row = new UserModel();
            $row->name = $userInfo->nick;
            $row->password = bcrypt('123456');
            $row->open_id = $userInfo->openid;
            $row->union_id = $userInfo->unionid;
            if($row->save()){
                OptionLogModel::getAddLog('user','update',['code'=>$code],$row->id,$row->id,'用户登录');
                return $row;
            }
        }
    }
}
