<?php

namespace app\api\controller;

use think\Request;
use app\api\extend\Basic;
use app\api\untils\MessageUntils;
use app\model\Users;
use app\model\NoteLog;
use think\Session;
use app\api\untils\JwtUntils;
class Member extends Basic
{
    public $user;

    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->user = new Users();
    }

    public function login() {

        $data['data']   = array();
        $data['status'] = 101;
        
        if ($this->params['phone'] && $this->params['pwd']) {
            $user_data = $this->user->get([
                'user_phone' => $this->params['phone'],
                'status'     => 0,
            ]);

            if (isset($user_data->id)) {
                if ($user_data->user_pswd == md5(md5($this->params['pwd']) . '+123')) {
                    
                    $jwt_data['id']         = $user_data->id;
                    $jwt_data['user_nick']  = $user_data->user_nick;
                    $jwt_data['user_phone'] = $user_data->user_phone;

                    $jwt = new JwtUntils();              
                    $data['data'] = $user_data->getData();
                    $data['data']['last_login_ip'] = long2ip($data['data']['last_login_ip']);
                    
                    $data['data']['authToken'] = $jwt->createToken($jwt_data);
                    $data['msg']    = '登陆成功';
                    $data['status'] = 200;
                    Session::set('u_user', $data['data']);
                    $user_data->last_login_ip = ip2long($this->request->ip());
                    $user_data->last_login_time = date('Y-m-d H:i:s');
                    $user_data->save();
                } else {
                    $data['msg'] = '密码错误';
                }
            } else {        
                $data['msg']    = '没有该用户';
            }
        } else {
            $data['msg']    = '用户名或密码为空';
        }       
        
        return $this->response($data['status'], $data['msg'],$data['data']);
    }
    
    /**
     * 退出登录
     * 
     * @return type
     */
    public function logout() {
        $id = $this->userId ? $this->userId : $this->params['id'];

        $data['status'] = 101;
        $data['msg']    = '';
        $u_user = Session::get('u_user');

        if ($id == $u_user['id']) {
            Session::delete('u_user');
            $data['status'] = 200;
            $data['msg']    = 'logout successful';
        } else {
            $data['msg'] = 'logout error';
        }
        
        return $this->response($data['status'], $data['msg']);
    }
    
    /**
     * 发送短信
     * @param Request $this->request
     * @return type
     */
    public function sendSms() {
        $data['data']   = array();
        $data['status'] = 101;
        if ($this->request->param('phone')) {
            $phone = $this->request->param('phone');
            $noteLog = new NoteLog();
            $num     = $noteLog->where('phone', $phone)->where('is_success',1)->count();   
            
            if (check_phone($phone)) {
                if ($num > 7) {
                    $data['msg'] = '短信发送超过上限';
                } else {
                    $result['statusMsg']  = '';
                    $result['statusCode'] = '';

                    $message = new MessageUntils();
                    $_code   = mt_rand(1000, 9999) . '';
//                    $result  = $message->sendCCPSMS($phone, array($_code, '5分钟'), 214759);
                    $jwt = new JwtUntils();
                    $noteLog->phone        = $phone;
                    $noteLog->template_msg = '【同联商业】您的验证码为'.$_code.'，请于5分钟内正确输入，如非本人操作，请忽略此短信。';
                    $noteLog->code         = $_code;
                    $noteLog->is_success   = $result['statusCode'] == 0 ? 1 : 2;
                    $noteLog->send_time    = date('Y-m-d H:i:s');
                    $noteLog->save();

                    Session::set('_code', $_code);
                    $jwt_data['phone'] = $phone;
                    $jwt_data['code']  = $_code;
                    
                    $data['data']['sms_code']   = $_code;
                    $data['data']['token']  = $jwt->createToken($jwt_data);
                    $data['msg']    = ($result['statusCode'] == 0) ? '发送短信成功':$result['statusMsg'];
                    $data['status'] = ($result['statusCode'] == 0) ? 200 : 101;                
                }
            } else {
                $data['msg'] = '手机号码错误';
            }
        } else {
            $data['msg'] = '手机号码为空';
        }
                
        return $this->response($data['status'], $data['msg'], $data['data']);
    }    
    
    /**
     * 用户注册、编辑、邀请注册
     * 
     * @return type
     */
    public function register() {      
        $result = 0;
        
        if ($this->params['type']) {
            $type = $this->params['type'];
        
            //根据不同的类型验证不同的场景
            switch ($type) {
                case 'add' : $check = 'users.register';             
                    break;
                case 'invite' : $check = 'users.invite';
                    break;
                default:    
                        $check = 'users.edit';
                    break;
            }    
      
            $result = $this->validate([
                'user_phone' => $this->request->param('phone'),
                'user_pswd'  => $this->request->param('pwd'),
                'referrer_id' => $this->request->param('referrer_id'),
                'referrer_source' => $this->request->param('referrer_source'),
                'code' => $this->request->param('code'),
                'user_nick' => $this->request->param('user_nick'),
                'token' => $this->request->param('token')
                    ], $check);
        } else {
            return $this->response(101, 'type is null');
        }
        
        $phone  = $this->request->param('phone');
        
        if ($this->params['token']) {
            $jwt = new JwtUntils();
            $jwt_data = $jwt->getDecode($this->params['token']);
            $code = Session::get('_code')? Session::get('_code') :  $jwt_data['data']['code'];
            $jwt_phone =  $jwt_data['data']['phone'];
            
            $note = new NoteLog();
            $note_data = $note->field('send_time')->where([
                'phone'=> $phone,
                'code'=>$code,
                'is_success'=>1
            ])->find();
            
            if (time()-$note_data->send_time > 18000) {
                return $this->response(101, '请重新获取验证码');
            }

        }
        
        $data['status'] = 101;
        $data['data']   = array();
        if (true === $result){
            $user_data = $this->user->get(['user_phone' => $this->params['phone']]);
            $date = date('Y-m-d H:i:s');
            $pwd = md5(md5($this->request->param('pwd')) . '+123');
            
            
            if (empty($user_data->id)) {
                if ($this->request->param('code') == $code && $code != '' && $jwt_phone == $phone) {
                    
                    $insert_data['referrer_id'] = $this->request->param('referrer_id');
                    $insert_data['referrer_source'] = $this->request->param('referrer_source');
                    $insert_data['status'] = 0;
                    $insert_data['create_time'] = $date;
                    $insert_data['update_time'] = $date;
                    $insert_data['last_login_time'] = $date;
                    $insert_data['last_login_ip'] = ip2long($this->request->ip());
                    $insert_data['user_phone'] = $phone;
                    $insert_data['user_pswd'] = $pwd;
                    $insert_data['user_nick'] = $this->request->param('user_nick');
                    $insert_data['user_pic']  = $this->request->param('user_pic');           
                    
                    $this->user->save($insert_data); //注册用户
                    
                    if ($this->user->id) {
                        $jwt_data['id'] = $this->user->id;
                        $jwt_data['user_nick'] = $insert_data['user_nick'];
                        $jwt_data['user_phone'] = $insert_data['user_phone'];
                                
                        $jwt = new JwtUntils();
                        $insert_data['authToken'] = $jwt->createToken($jwt_data);
                        $insert_data['id'] = $this->user->id;

                        Session::set('u_user', $insert_data['data']);   //登录
                        Session::delete('_code');      //销毁验证码
                        $data['data'] = $insert_data;
                        $data['msg']  = '注册成功';
                        $data['status'] = 200;
                    } else {
                        $data['status'] = 101;
                        $data['msg']    = '注册失败';
                    }

                } else {
                    $data['msg'] = '验证码错误';
                }                

            }
            
            $user_data->update_time     = $date;
            //编辑
            if ($type == 'edit') {
                $user_data->user_nick  = $this->request->param('user_nick')? $this->request->param('user_nick') : $user_data->user_nick;
                $user_data->user_phone =  $this->request->param('phone') ? $this->request->param('phone') : $user_data->user_phone;
                $user_data->user_pic   = $this->request->param('user_pic') ? $this->request->param('user_pic') : $user_data->user_pic;              
                $user_data->last_login_ip   = $this->request->param('last_login_ip') ? $this->params['last_login_ip'] : $user_data->last_login_ip;

                //修改密码
                if ($this->request->param('pwd') == $user_data->user_pswd) {
                    $user_data->user_pswd = $pwd;
                }

                $user_data->save();
                if ($user_data->id) {
                    $data['data']   = ['id' => $user_data->id];
                    $data['status'] = 200;
                    $data['msg'] = '修改成功';
                } else {
                    $data['msg'] = '编辑失败';
                }

            }
         
            //忘记密码
            if ($type == 'forget') {
                if ($this->request->param('code') == $code && $code != '' && $jwt_phone == $phone) {
                    $user_data->user_pswd   = $pwd;
                            
                    $user_data->save();
                    if ($user_data->id) {
                        $data['data']   = ['id' => $user_data->id];
                        $data['status'] = 200;
                        $data['msg'] = '修改成功';
                    } else {
                        $data['msg'] = '密码修改失败';
                    }

                } else {
                    $data['status'] = 101;
                    $data['msg']    = '修改失败';
                }
            }
            
        } else {
            $data['msg']    = $result;
        }
        return $this->response($data['status'], $data['msg'], $data['data']);
    }
    
    /**
     * 邀请记录
     * 
     * @return type
     */
    public function inviteList() {
        $id = $this->params['id'];
        $data['status'] = 101;
        $data['data']   = array();
        $data['msg']    = '';
        
        if ($id) {
            $restult = $this->user->field('user_nick,user_phone,create_time')
                    ->where('referrer_id',$id)
                    ->where('status',0)
                    ->select();
   
            foreach ($restult as $k=>$v) {
                 $arr = $v->getData();
                 $data_arr[$k]['user_nick']   = $arr['user_nick'];
                 $data_arr[$k]['user_phone']  = $arr['user_phone'];
                 $data_arr[$k]['create_time'] = date('Y-m-d', strtotime($arr['create_time']));
            }
            $data['data']   = $data_arr;
            $data['status'] = 200;
        } else {
            $data['msg'] = 'id is null';
        }
        
        return $this->response($data['status'], $data['msg'], $data['data']);
    }
    
    /**
     * 生成邀请二维码
     * 
     * @return type
     */
    public function qrCode() {

        $parms = $this->params;
        $data['status'] = 101;
        $data['data']   = array();
        $data['msg']    = '';
   
        if ($parms['id'] && $parms['referrer_source']) {
            $result = $this->user->where('status',0)->where('id',$parms['id'])->find();
           
            if ($result) {
                $code = new \app\api\untils\GenerateCode();
                $url  = config('url').'test.html?referrer_source=0&id='.$result->id;
                $path = $code->getCode($url, $result->id);
                $data['data']   = ['path' => config('url').$path]; 
                $data['status'] = 200;
            } else {
                $data['msg'] = '没有该用户';
            }
        } else {
            $data['msg']    = 'id or referrer_source is null';
        }
        return $this->response($data['status'], $data['msg'], $data['data']);
    }
}
