<?php

namespace app\common\controller;

use think\App;
use app\enterprise\model\User as UserModel;
use app\enterprise\model\Group;
use app\admin\model\UserView;
use app\manage\model\Config;
use think\facade\Session;
use think\facade\Db;
use GatewayClient\Gateway;

use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\TranslateTextRequest;


/**
 * 控制器基础类
 */
class User
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    protected $lang;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        Gateway::$registerAddress = config('gateway.registerAddress');
        $this->app     = $app;
        $this->request = $this->app->request;
        $this->lang = request()->header('Lang', 'en');
    }

    //客户端登录
    public function login(){

    // $client = new TranslationServiceClient();

    // $request = new TranslateTextRequest();
    // $request->setTargetLanguageCode('en-US');
    // $request->setContents(['こんにちは']);
    // $request->setParent('projects/php-docs-samples-kokoro');

    // // The request and response will be logged to STDOUT when the environment
    // // variable GOOGLE_SDK_PHP_LOGGING=true
    // $response = $client->translateText($request);
    // print_r($response);die;
        $params=request()->param();
        $where['role'] = 0;
        if (empty($params['account']) || empty($params['uid']) || empty($params['from'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        if (!empty($params['account'])) {
            $where[] = ['account', '=', $params['account']];
        } 
        if (!empty($params['from'])) {
            $where[] = ['from', '=', $params['from']];
        }
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }
        try {
            Db::startTrans();
                
            $userInfo=UserModel::where($where)->withoutField('register_ip,login_count,update_time,create_time')->find();
            if($userInfo==null){
                $cs_uid = 0;
                $autoTask=Config::autoTask();
                if($autoTask && $autoTask['user_id']){
                    $cs_uid = $autoTask['user_id'];
                }
                $salt = \utils\Str::random(4);
                $userInfo = UserModel::create([
                    'account'=>$params['account'],
                    'realname'=> !empty($params['realname'])  ? $params['realname'] : $params['account'],
                    'name_py' => !empty($params['realname']) ? pinyin_sentence($params['realname']) : '',
                    'phone'=>!empty($params['phone']) ? $params['phone'] : '',
                    'email'=>!empty($params['email']) ? $params['email'] : '',
                    'from'=>$params['from'],
                    'uid'=>$params['uid'],
                    'salt' => $salt,
                    'avatar' => !empty($params['avatar']) ? $params['avatar'] : '',
                    'password' => password_hash_tp(123456,$salt),
                    'cs_uid' => $cs_uid,
                    'role' => 0,
                    'status' =>1,
                    'register_ip' => $this->request->ip(),
                    'last_login_ip' => $this->request->ip(),
                    'last_login_time' => time(),
                    'login_count' => 1
                ]);
                // 监听用户注册后的操作
                event('UserRegister',['user_id' => $userInfo['user_id'], 'realname' => $userInfo['realname']]);

            } else {
                //$userInfo['avatar']=avatarUrl($userInfo['avatar'],$userInfo['realname'],$userInfo['user_id']);
                //    如果用户已经有设置
                $setting=$userInfo['setting'] ?: '';
                if($setting){
                    $setting['hideMessageName']= $setting['hideMessageName']=='true' ? true : false;
                    $setting['hideMessageTime']= $setting['hideMessageTime']=='true' ? true : false;
                    $setting['avatarCricle']= $setting['avatarCricle']=='true' ? true : false;
                    $setting['isVoice']= $setting['isVoice']=='true' ? true : false;
                    $setting['sendKey']=(int)$setting['sendKey'];
                    $userInfo['setting']=$setting;
                }
            }
            if($userInfo['status']==0){
                return warning(lang('user.forbid'));
            }  
            
            $update=[
                'last_login_time'=>time(),
                'last_login_ip'=>$this->request->ip(),
                'login_count'=>Db::raw('login_count+1'),
                'avatar' => !empty($params['avatar']) ? $params['avatar'] : '',
            ];
            if (!empty($params['realname'])) {
                $update['realname'] = $params['realname'];
            }
            UserModel::where('user_id',$userInfo['user_id'])->update($update);
            
            //记录用户浏览
            UserView::addData($userInfo['user_id']);
        
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
        
        //如果登录信息中含有client——id则自动进行绑定
        $client_id=$this->request->param('client_id');
        if($client_id){
            $cid=$this->request->header('cid','');
            $this->doBindUid($userInfo['user_id'],$client_id,$cid);
        }

        $userInfo['qrUrl']=getMainHost().'/scan/u/'.encryptIds($userInfo['user_id']);
        unset($userInfo['password'],$userInfo['salt']);
        $userInfo['displayName']=$userInfo['realname'];
        $userInfo['id']=$userInfo['user_id'];
        $authToken=UserModel::refreshToken($userInfo,$param['terminal'] ?? 'web');
        
        $data=[
            'sessionId'=>Session::getId(),
            'authToken'=>$authToken,
            'userInfo'=>$userInfo
        ];
           
        return success(lang('user.loginOk'),$data);
   }

   // 执行绑定
    public function doBindUid($user_id,$client_id,$cid=''){
        // 如果当前ID在线，将其他地方登陆挤兑下线
        if(Gateway::isUidOnline($user_id)){
            wsSendMsg($user_id,'offline',['id'=>$user_id,'client_id'=>$client_id,'isMobile'=>$this->request->isMobile()]);
        }
        Gateway::bindUid($client_id, $user_id);
        // 查询团队，如果有团队则加入团队
        $group=Group::getMyGroup(['gu.user_id'=>$user_id,'gu.status'=>1]);
        if($group){
            $group=$group->toArray();
            $group_ids=arrayToString($group,'group_id',false);
            foreach($group_ids as $v){
                Gateway::joinGroup($client_id, $v); 
            }
        }
        if($cid){
            bindCid($user_id,$cid);
        }
        wsSendMsg(0,'isOnline',['id'=>$user_id,'is_online'=>1]);
    }


}
