<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-25 17:23
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;
use app\model\api\User as UserModel;
use app\model\api\UserLogin;
use app\model\api\UserShowTemplate;
use app\Request;
use library\lib\weixina;
use library\services\JsonNull;
use library\services\UtilService;

use think\Cache;
use think\Image;

class Login extends BaseController
{


    /**
     * 微信登录
     * @param Request $request
     */
    public function weixinLogin(Request $request){
        [$code,$nickname,$avatar,$device_id,$model,$platform,$system,$gender,$parent_uid] = UtilService::getMore([
            ['code', '', 'empty', 'code参数错误'],
            ['nickname','微信用户',],
            ['avatar','',],
            ['device_id',''],
            ['model',''],
            ['platform',''],
            ['system',''],
            ['gender','0'],
            ['parent_uid','0'],
        ], $request, true);
        //用户登录
        if(empty($avatar)){
            //默认通向
            $avatar = "";
        }
        if(!in_array((string)$gender, array("0","1","2"))){
            $gender = 0;
        }
        $regip = get_client_ip();
        if(empty($regip)){
            $regip = $request->ip();
        }
        $weixinA = new weixina();
        $data=$weixinA->auth_code2Session($code);//新版
        if(empty($data) || empty($data['openid'])) {
            return app('json')->fail("微信授权登录失败,关闭页面重新授权".$weixinA->error);
        }
        $member = (new UserModel)->where("openid",$data["openid"])->find();
        if(empty($member)){
            $p_id = 0;
            if(!empty($parent_uid)){
                $pcount = (new UserModel)->where("uid",$parent_uid)->count();
                if($pcount>0){
                    $p_id = (int)$parent_uid;
                }
            }
            //用户注册
            $uid = (new UserModel)->insertGetId(array(
                "openid"     =>$data["openid"],
                "unionid"    =>empty($data["unionid"])?"":$data["unionid"],
                "nickname"   =>$nickname,
                "avatar"     =>$avatar,
                "sex"        =>(int)$gender,
                "regtime"    =>time(),
                "regip"      =>$regip,
                "parent_uid" =>$p_id,
                "parent_time"=>$p_id <= 0 ? 0 : time(),
            ));
            if(empty($uid)){
                return app('json')->fail("网络繁忙，请稍后尝试");
            }
            //绑定初始化模板
            (new UserShowTemplate)->userBindTempInit($uid);
            //生成MD5
            $token = base64_encode(md5($uid ."openid" .$data["openid"] . time()));
            (new UserModel)->where('uid', $uid)->save(['lasttime'=>time(),'token'=>$token]);
            //生成登录日志
            (new UserLogin)->insert([
                'uid'         => $uid, 
                'ip'          => $regip, 
                'time'        => time(),
                'device_id'   => $device_id,
                'from_plat'   => $platform,
                'device_type' => $system,
                'version'     => $model,
            ]);
            $result             = [];
            $result['nickname'] = $nickname;
            $result['avatar']   = $avatar;
            $result['token']    = $token;
            return app('json')->success($result);
        }
        if ($member['status'] == -1) {
            return app('json')->fail("账号已被禁用");
        }
        //生成MD5
        $token = base64_encode(md5($member['uid'] ."openid" . $member['openid'] . time()));
        (new UserModel)->where('uid', $member['uid'])->save([
            'lasttime' => time(),
            'token'    => $token,
        ]);
        //生成登录日志
        (new UserLogin)->insert([
            'uid'         => $member['uid'], 
            'ip'          => $regip, 
            'time'        => time(),
            'device_id'   => $device_id,
            'from_plat'   => $platform,
            'device_type' => $system,
            'version'     => $model,
        ]);
        $result             = [];
        $result['nickname'] = $member['nickname'];
        $result['avatar']   = $member['avatar'];
        $result['token']    = $token;
        return app('json')->success($result);
    }

}
