<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/22
 * Time: 17:06
 */
namespace app\home\controller;

use app\api\controller\Validate;
use app\common\controller\WechatBase;
use EasyWeChat\Foundation\Application;
use think\Db;
use think\Log;

class User extends WechatBase
{
    public function callback(){
        $appId=config('wechat.app_id');
        $secret=config('wechat.secret');
        $config = [
            'app_id'  => $appId,
            'secret'  => $secret,
        ];

        $app = new Application($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $wechat_user = $user->toArray();
        if(isset($wechat_user['id'])){
            $openid=$wechat_user['id'];
            $findThird = Db::name("third")
                ->where('openid', $openid)
                ->where('app_id', $appId)
                ->find();
            if ($findThird) {
                $this->wechatUserLogin($findThird,$openid,$appId);
            }else{
                $this->wechatUserRegister($wechat_user,$openid,$appId);
            }
            $target_url=session('target_url');
            $targetUrl = empty($target_url) ? '/' : $target_url;
            header('location:'. $targetUrl);
        }else{
            Log::write('获取微信用户数据失败');
            $this->error('获取微信用户数据失败');
        }

    }

    /**
     * 微信用户登录
     * @param $findThird
     * @param $openid
     * @param $appId
     */
    protected function wechatUserLogin($findThird,$openid,$appId){
        $currentTime = time();
        $ip          = $this->request->ip(0, true);
        $token = generate_user_token($findThird['user_id']);
        $thirdData = [
            'loginip'   => $ip,
            'logintime' => $currentTime,
            'login_times'     => Db::raw('login_times+1')
        ];
        $row1=Db::name("third")
            ->where('openid', $openid)
            ->where('app_id', $appId)
            ->update($thirdData);
        $userInfo=Db::name("third")
            ->where('openid', $openid)
            ->where('app_id', $appId)->find();
        $user = Db::name("user")
            ->where('id', $userInfo['user_id'])
            ->find();
        $userData = [
            'loginip'   => $ip,
            'prevtime'  => $user['logintime'],
            'logintime' => $currentTime,
        ];
        $row2=Db::name("user")
            ->where('id', $userInfo['user_id'])
            ->update($userData);
        if($row1!==false&&$row2!==false){
            $userModel=new \app\home\model\User();
            $user=$userModel->getUserInfo(['user_id'=>$userInfo['user_id'],'app_id'=>$appId]);
            update_current_user($user);
            session('token',$token);
            Db::commit();
        }else{
            Db::rollback();
        }
    }

    /**
     * 微信用户注册
     * @param $wechat_user
     * @param $openid
     * @param $appId
     */
    protected function wechatUserRegister($wechat_user,$openid,$appId){
        $currentTime = time();
        $ip          = $this->request->ip(0, true);
        Db::startTrans();
        $userId = Db::name("user")->insertGetId([
            'status'     => 'normal',
            'gender'     => $wechat_user['original']['sex'],
            'nickname'   => $wechat_user['nickname'],
            'avatar'     => $wechat_user['avatar'],
            'joinip'     => $ip,
            'jointime'   => $currentTime,
            'createtime' => $currentTime,
            'updatetime' => $currentTime,
            'loginip'    => $ip,
            'logintime'  => $currentTime,
            'type'=> 1,
        ]);

        $row=Db::name("third")->insert([
            'openid'          => $openid,
            'user_id'         => $userId,
            'nickname'        => $wechat_user['nickname'],
            'app_id'          => $appId,
            'loginip'         => $ip,
            'union_id'        => '',
            'logintime'       => $currentTime,
            'createtime'      => $currentTime,
            'login_times'     => 1,
            'more'            => json_encode($wechat_user)
        ]);
        if($userId && $row){
            $token = generate_user_token($userId);
            $userModel=new \app\home\model\User();
            $user=$userModel->getUserInfo(['user_id'=>$userId,'app_id'=>$appId]);
            update_current_user($user);
            session('token',$token);
            Db::commit();
        }else{
            Db::rollback();
        }
    }

    /**
     * 授权页面
     * @param null $target_url
     * @return mixed
     */
    public function authorization_view($target_url = null){
        $this->assign('title','授权页');
        $this->assign('target_url',$target_url);
        return $this->fetch();
    }

    /**
     * 授权
     */
    public function authorization(){
        $target_url = $this->request->param('target_url');
        if(empty($target_url)){
            $target_url = url('home/index/index','',false,true);
        }else{
            $target_url = UrlDecode($target_url);
        }
        $this->checkWeChatUserLogin($target_url);
    }

    /**
     * 定位当前位置判断
     */
    public function location(){
        $param = $this->request->param();
        $validate = new \think\Validate([
            'user_id' => 'require',
            'longitude' => 'require',
            'latitude' => 'require',
        ]);
        $validate->message([
            'user_id' => 'user_id参数错误',
            'longitude.require' => 'longitude参数错误!',
            'latitude.require' => 'latitude参数错误!',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $where['id'] = ['eq',$param['user_id']];
        $userModel = new \app\home\model\User();
        $result = $userModel->updateData($where,$param);
        $this->success('SUCCESS');
    }
}