<?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();
    }

    /**
     * 用户登陆
     * 
     * @return type
     */
    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')) {
                    $user_data->last_login_ip = ip2long($this->request->ip());
                    $user_data->last_login_time = date('Y-m-d H:i:s');
                    $user_data->save();
                    if ($user_data->user_pic) {
                        $user_data->user_pic = HEADERIMGURL.$user_data->user_pic;
                    }
                    $jwt_data['id']        = $user_data->id;
                    $jwt_data['userNick']  = $user_data->user_nick;
                    $jwt_data['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;
                } 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';
            $data['data']['AuthToken'] = '';
        } 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)
                    ->where('send_time','between time',[date('Y-m-d').' 00:00:00',date('Y-m-d').' 23:59:59'])
                    ->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);

                    $noteLog->phone        = $phone;
                    $noteLog->template_msg = '【同联商业】您的验证码为'.$_code.'，请于5分钟内正确输入，如非本人操作，请忽略此短信。';
                    $noteLog->code         = $_code;
                    $noteLog->send_time    = date('Y-m-d H:i:s');
                    $result['statusCode'] = 1;
                    if ($result['statusCode'] == 1) {
                        $jwt = new JwtUntils();
                        $noteLog->is_success = 1;
                        $jwt_data['phone']   = $phone;
                        $jwt_data['code']    = $_code;

                        $data['data']['sms_code']   = $_code;
                        $data['data']['token']  = $jwt->createToken($jwt_data);
                        $data['status'] = 200;
                        $data['msg']    = '发送短信成功';
                    } else {
                        $noteLog->is_success = 2;
                        $data['msg']    = '短信发送失败';
                    }
                    $noteLog->save();
                }
            } else {
                $data['msg'] = '手机号码错误';
            }
        } else {
            $data['msg'] = '手机号码为空';
        }
                
        return $this->response($data['status'], $data['msg'], $data['data']);
    }    
    
    /**
     * 用户注册、编辑、邀请注册
     * 
     * @return type
     */
    public function register() {
        $type   = $this->request->param('type');
        $phone  = $this->request->param('phone');
        $pwd    = $this->request->param('pwd');
        $user_nick = $this->request->param('user_nick');
        $user_pic  = $this->request->param('user_pic');
        $token  = $this->params['token'];

        if ($type == '') {
            return $this->response(101, 'type is null');
        }

        if (!check_phone($phone) && $phone != '') {
            return $this->response(101, '手机号码错误');
        }

        if (mb_strlen($pwd) < 6 && $pwd != '') {
            return $this->response(101, '密码少于6位');
        }

        if (empty($token) && $type != 'edit') {
            return $this->response(101, 'token is null');
        }

        if ($token && $this->params['type'] != 'register') {
            $jwt = new JwtUntils();
            $jwt_data = $jwt->getDecode($token);
            $code = $jwt_data['data']['code'];
            $jwt_phone =  $jwt_data['data']['phone'];
            
            $note = new NoteLog();
            $note_data = $note->field('id,code,send_time')->where([
                'phone'=> $phone,
                'code' => $code,
                'is_success' => 1,
            ])->whereTime('send_time', '>',time()-300)->find();

            if (time() - strtotime($note_data->send_time) > 300) {
                return $this->response(101, '请重新获取验证码');
            }
        }

        $data['status'] = 101;
        $data['data']   = array();

        if ($phone) {
            $user_data = $this->user->get(['user_phone' => $phone]);
        } else {
            $user_data = $this->user->get($this->userId);
        }
        $date = date('Y-m-d H:i:s');
        $pwd = md5(md5($pwd) . '+123');

        switch ($type) {
            case 'add' :
                if ($pwd == '') {
                    return $this->response(101, '密码为空');
                }

                if ($phone == '') {
                    return $this->response(101, '手机号码为空');
                }

                if (empty($user_data->id)) {
                    if ($this->request->param('code') == $code && $code != '') {

                        $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'] = $user_nick;
                        $insert_data['user_pic']  = $user_pic;
                        $this->user->save($insert_data); //注册用户

                        if ($this->user->id) {
                            $jwt_data['id'] = $this->user->id;
                            $jwt_data['userNick'] = $insert_data['user_nick'];
                            $jwt_data['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'] = '验证码错误';
                    }
                } else {
                    $data['msg'] = '该手机号已注册';
                }
                break;
            case 'forget' :
                if ($pwd == '') {
                    return $this->response(101, '密码为空');
                }

                if ($code == $this->request->param('code')  && $jwt_phone == $phone) {
                    $user_data->update_time = $date;
                    $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['msg'] = '验证码错误';
                }
                break;

            default :
                $result['AuthToken'] = $this->authToken;
                if ($user_nick) {
                    $user_data->user_nick  = $user_nick;
                    $result['user_nick'] = $user_nick;
                }

                if ($this->request->param('pwd2')) {
                    $pwd2 = $this->request->param('pwd2');
                    //修改密码
                    if (md5(md5($pwd2).'+123') == $user_data->user_pswd) {
                        $user_data->user_pswd = $pwd;
                        $result['user_pswd']    = $pwd;
                    } else {
                        $data['status'] = 101;
                        $data['msg']    = '密码错误';
                    }
                }

                if ($user_pic) {
                    $user_data->user_pic   = $user_pic;
                    $result['user_pic']    = $user_pic;
                }

                $user_data->update_time = $date;
                $user_data->save();

                if ($user_data->id) {
                    $data['data']   = $result;     //编辑完返回用户信息
                    $data['status'] = 200;
                    $data['msg'] = '修改成功';
                } else {
                    $data['status'] = 101;
                    $data['msg']    = '编辑失败';
                }
                break;
        }
        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\GenerateCodeUntils();
                $url  = $this->request->domain().'/test.html?referrer_source=0&id='.$result->id;
                $path = $code->getCode($url, $result->id);
                $data['data']   = ['path' => $this->request->domain().'/'.$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']);
    }
    
    /**
     * 通过AuthToken获取用户信息编辑用
     * @return type
     */
    public function getUserInfo() {
        
        $data['status'] = 200;
        $data['data']   = '';
        if ($this->params['AuthToken']) {
            $fields = 'id,user_pswd,user_nick,user_phone,user_pic,referrer_id,referrer_source,integral,create_time,update_time,last_login_time,last_login_ip';
            $data['data']   = $this->user->selectUser($this->userId, $fields);
            $data['data']['AuthToken'] = $this->params['AuthToken'];
        }

        $data['msg']    = '';
        return $this->response($data['status'], $data['msg'], $data['data']);
    }

    /**
     * 上传头像
     *
     * @return \think\Response
     */
    public function uploadHeadImg() {
        $data['status'] = 101;
        $data['msg']    = '';
        $data['data']   = '';

        $file = request()->file('image');
        if($file){
            $path = ROOT_PATH . 'public' . DS . 'static'. DS . 'head_portrait';
            $info = $file->validate(['size'=>512000,'ext'=>'jpg,png'])      //限制500KB
                ->move($path);
            if($info){
                if ($this->userId) {
                    $user = new Users();
                    $user_data = $user->field('user_pic')->where('id',$this->userId)->find();
                    @unlink($path.DS.$user_data->user_pic); //删除原来的图片
                    $img_path    = $info->getSaveName();  //生成的图片路径
                    //更新用户信息
                    $user_data->user_pic = $img_path;
                    $user_data->save();

                    $static_path = $path.DS.$img_path;    //生成图片的绝对路径
                    $image = \think\Image::open($static_path);
                    $image->thumb(500, 500)->save($static_path);   //生成缩略图

                    $data['status'] = 200;
                    $data['msg']    = '上传成功';
                    $data['data']   = ['file_name' => HEADERIMGURL . $img_path];
                }

            }else{
                // 上传失败获取错误信息
                $data['msg'] = $file->getError();
            }
        } else {
            $data['msg'] = '没有该文件';
        }

        return $this->response($data['status'], $data['msg'], $data['data']);
    }
}