<?php
/**
 * 公用控制器部分-无需授权
 */
namespace app\modules\engineer\v1\controllers;
use app\modules\common\Helper;
use app\modules\common\Verify;
use app\modules\logic\services\UserService;
use app\modules\logic\services\UploadService;
use app\modules\logic\services\CommonService;
use app\modules\logic\model\UsersShopInfoModel;
use app\modules\logic\model\UsersTechInfoModel;
use app\modules\logic\model\UsersModel;
use app\modules\logic\model\SysCarmodelSetModel;
use app\modules\logic\model\SysProductSetModel;
use app\modules\logic\model\SysBasePriceSetModel;
use app\modules\third\sms\Sms;
use Yii;
use yii\web\Controller;

class CommonController extends MiddleController {
	/**
	 * 返回
	 * @param $code
	 * @param string $info
	 * @param string $controller
	 * @param string $total
	 */
	protected function response($code, $info = '', $total = '', $controller = 'common') {
		return parent::response($code, $info, $total, $controller);
	}
	
    /**
     * [actionLogin 技师登录]
     * @apiDoc
     * @api     v1/common/login
     * @group   common
     * @name    技师登录
     * @desc    技师APP-登录
     * @method  POST
     * @param username string 手机号 req
     * @param password string 密码 noreq
     * @param code string 短信验证码 noreq
     * @param type string 登录方式【1，账号密码,2短信验证码】 req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
        {
        "code": "000000",
        "msg": "登录成功",
        "info": {
            "token": "b200fc29e11d02f8948115efe9067606_user",
            "auth": "pass"
        }
        }
     */
    public function actionLogin(){
        //1密码登录 2验证码登录
        if (!isset($this->para['type']) || !in_array($this->para['type'], array('1', '2'), true)) {
            return $this->response('para_miss', '登录方式缺失');
        }
        if (!isset($this->para['username']) || empty($this->para['username'])) {
            return $this->response('para_miss', '请输入手机号');
        }
        if (!Verify::phoneFormat($this->para['username'])) {
            return $this->response('para_error', '手机号格式错误');
        }

        $redis = Yii::$app->redis;
        $username = $this->para['username'];
        $redis_key_locked = md5($username . "_" . "LOCKED");

        switch ($this->para['type']) {
            case '1':
                if (!isset($this->para['password']) || empty($this->para['password'])) {
                    return $this->response('para_miss', '请输入密码');
                } 
                $is_pwderror_locked = $redis->get($redis_key_locked);
                if ($is_pwderror_locked >= 3) {
                    return $this->response('para_error', '账户被锁定1小时，请稍后再登录');
                }
                break;
            case '2':
                //判断验证码正确
                $sms = new Sms();
                $flag_verify = $sms->verifyCode(['mobile'=>$this->para['username'],'sms_code'=>$this->para['code']]);
                if (!$flag_verify) {
                    return $this->response('para_error', '短信验证码不正确');
                }
                break;
            default:
               return $this->response('para_miss', '登录方式缺失');
        }

        $result = UserService::login($this->para,'tech');
        if (in_array($result, array('lock', 'error', 'not_exists', 'log_error','pw_error'), true)) {
            //登陆失败；添加错误次数
            $redis_key_exist = $redis->exists($redis_key_locked);
            if ($redis_key_exist) {
                $number = $redis->incr($redis_key_locked);
            } else {
                $redis->set($redis_key_locked, 1, "EX", '3600');
                $number = 1;
            }
            $_number = 3 - $number;
            if ($result == 'lock') {
                return $this->response('para_error', "用户已锁定");
            } elseif ($result == 'error') {
                return $this->response('para_error', "用户名或密码错误," . "剩余登录次数:" . $_number . "次");
            } elseif ($result == 'not_exists') {
                return $this->response('para_error', '账号不存在,' . "剩余登录次数:" . $_number . "次");
            }elseif ($result == 'pw_error') {
                return $this->response('para_error', '用户名或密码错误,' . "剩余登录次数:" . $_number . "次");
            }else {
                return $this->response('deal_false', '处理登录记录失败' . "剩余登录次数:" . $_number . "次");
            }
        } else {
            //登录成功；删除错误次数
            $redis_key_exist = $redis->exists($redis_key_locked);
            if ($redis_key_exist) {
                $redis->del($redis_key_locked);
            }
            return $this->response('deal_succ', '登录成功', $result);
        }
    }
    /**
     * [actionReg 注册]
     * @apiDoc
     * @api     v1/common/reg
     * @group   common
     * @name    注册
     * @desc    技师APP-注册
     * @method  POST
     * @param mobile string 手机号 req
     * @param password string 密码 req
     * @param verify string 短信验证码 req
     * @param wx_nick string 微信昵称 noreq
     * @param wx_openid string 微信openid noreq
     * @author JOHN.W
     * @version [1.0]
     * @return  json
       {
        "code": "000000",
        "msg": "注册成功",
        "info": {
            "token": "b200fc29e11d02f8948115efe9067606_user",
            "auth": "pass"
        }
        }
     */
    public function actionReg()
    {

        if (!isset($this->para['mobile']) || empty($this->para['mobile'])) {
            return $this->response('para_miss', '请输入手机号');
        }

        if (!Verify::phoneFormat($this->para['mobile'])) {
            return $this->response('para_error', '手机号格式错误');
        }

        if (!isset($this->para['verify']) || empty($this->para['verify'])) {
            return $this->response('para_miss', '请输入验证码');
        }

        $sms = new Sms();
        $flag_verify = $sms->verifyCode(['mobile'=>$this->para['mobile'],'sms_code'=>$this->para['verify']]);
        if (!$flag_verify) {
            return $this->response('para_error', '短信验证码不正确');
        }

        $phone_flag = UserService::userPhoneExists($this->para['mobile'],'tech');
        if ($phone_flag) {
            return $this->response('Has_register');
        }


        if (!isset($this->para['password']) || empty($this->para['password'])) {
            return $this->response('para_miss', '请输入密码');
        }
        if (strlen($this->para['password']) < 6 || strlen($this->para['password']) > 20) {
            return $this->response('para_miss', '密码长度限制为6-20位');
        }
        $data_insert = array(
            'username' => $this->para['mobile'],
            'mobile' => $this->para['mobile'],
            'password' => $this->para['password'],
            'source' => $this->para['terminalType'],
            'type' => 'tech',
            'wx_nick' => isset($this->para['wx_nick'])?$this->para['wx_nick']:'',
            'wx_openid' => isset($this->para['wx_openid'])?$this->para['wx_openid']:'',
        );

        $result = UserService::reg($data_insert);

        if ($result === 'Has_register') {
            return $this->response('Has_register');
        } elseif ($result) {
            return $this->response('deal_succ', '注册成功', $result);
        } else {
            return $this->response('deal_false', '注册失败');
        }
    }
    /**
     * [actionWxlogin 微信登录]
     * @apiDoc
     * @api    v1/common/wxlogin
     * @group  common
     * @name   微信登录
     * @desc   微信快捷登录
     * @method POST
     * @param wx_openid string 微信openid req
     * @return json
        {
            "code": "003666",
            "msg": "用户未注册"
        }
        
        {
        "code": "000000",
        "msg": "登录成功",
        "info": {
            "token": "b200fc29e11d02f8948115efe9067606_user",
            "auth": "pass"
        }    
        }
     */
    public function actionWxlogin(){
        if (!isset($this->para['wx_openid']) || empty($this->para['wx_openid'])) {
            return $this->response('para_miss', '微信openid不能为空');
        }
        $user_id = UserService::checkWxOpenId($this->para['wx_openid'],'tech');
        if($user_id==false){
            return $this->response('no_register', '用户未注册');
        }
        $redis = Yii::$app->redis;
        $username = $this->para['wx_openid'];
        $redis_key_locked = md5($username . "_" . "LOCKED");
        $result =UserService::LoginByUid($user_id,'tech');
        if (in_array($result, array('lock', 'error', 'not_exists', 'log_error','pw_error'), true)) {
            //登陆失败；添加错误次数
            $redis_key_exist = $redis->exists($redis_key_locked);
            if ($redis_key_exist) {
                $number = $redis->incr($redis_key_locked);
            } else {
                $redis->set($redis_key_locked, 1, "EX", '3600');
                $number = 1;
            }
            $_number = 3 - $number;
            if ($result == 'lock') {
                return $this->response('para_error', "用户已锁定");
            } elseif ($result == 'error') {
                return $this->response('para_error', "用户名或密码错误," . "剩余登录次数:" . $_number . "次");
            } elseif ($result == 'not_exists') {
                return $this->response('para_error', '账号不存在,' . "剩余登录次数:" . $_number . "次");
            }elseif ($result == 'pw_error') {
                return $this->response('para_error', '用户名或密码错误,' . "剩余登录次数:" . $_number . "次");
            }else {
                return $this->response('deal_false', '处理登录记录失败' . "剩余登录次数:" . $_number . "次");
            }
        } else {
            //登录成功；删除错误次数
            $redis_key_exist = $redis->exists($redis_key_locked);
            if ($redis_key_exist) {
                $redis->del($redis_key_locked);
            }
            return $this->response('deal_succ', '登录成功', $result);
        }
    }
    /**
     * [actionModpwd 找回密码]
     * @apiDoc
     * @api     v1/common/modpwd
     * @group   common
     * @name    找回密码
     * @desc    门店APP-找回密码
     * @method  POST
     * @param username string 手机号 req
     * @param password string 新密码 req
     * @param verify string 短信验证码 req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
        {
        "code": "000000",
        "msg": "修改成功",
        "info": ''
        }
     */
    public function actionModpwd(){
        if (!isset($this->para['username']) || empty($this->para['username'])) {
            return $this->response('para_miss', '请输入手机号');
        }
        if (!isset($this->para['password']) || empty($this->para['password'])) {
            return $this->response('para_miss', '请输入新密码');
        }
        //校验账号+手机号是否一致
        $user_id  = UserService::checkUnameMobile($this->para['username'],$this->para['username'],'tech');
        if($user_id==false){
            return $this->response('para_miss', '账号和手机号不匹配');
        }
        $sms = new Sms();
        $flag_verify = $sms->verifyCode(['mobile'=>$this->para['username'],'sms_code'=>$this->para['verify']]);
        if (!$flag_verify) {
            return $this->response('para_error', '短信验证码不正确');
        }
        $where = [
            'user_id'=>$user_id
        ];
        $result = UserService::updatePassWord($where,$this->para['password']);
        return $this->response('deal_succ', '修改成功', $result);
    }
    /**
     * [actionApprove 提交认证]
     * @apiDoc
     * @api     v1/common/approve
     * @group   common
     * @name    提交认证
     * @desc    技师APP-提交认证-审核状态【0待审核，1通过，2拒绝，3驳回】   
     * @method  POST
     * @param  realname string 姓名 req
     * @param  id_card string 身份证号码 req
     * @param  positive_card string 身份证正面 req
     * @param  counter_card string 身份证反面 req
     * @param  work_type string 从业工种 req
     * @param  work_age string 从业年龄 req
     * @param  ut_contact string 紧急联系 req
     * @param  ut_tel string 紧急联系电话 req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
     {
        "code": "000000",
        "msg": "提交成功",
        "info": ''
        }
     */
    public function actionApprove(){
        if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        $UsersTechInfo = new UsersTechInfoModel();
        //查询门店是否认证或者驳回
        $row = $UsersTechInfo->getWidgetRow(['cols'=>['user_id','verify_status'],'user_id'=>$this->user_id]);
        $user_id  = 0;
        if(!empty($row) && isset($row['verify_status'])){
            switch ($row['verify_status']) {
                case '0':
                    return $this->response('para_miss', '正在审核中');
                    break;
                case '1':
                    return $this->response('para_miss', '审核已通过');
                    break;
                case '2':
                   return $this->response('para_miss', '审核已拒绝请联系平台');
                    break;
                default:
            }
           $user_id =  $row['user_id'];
        }
        $param = Helper::elements(['realname','id_card','positive_card','counter_card','work_type','work_age','ut_contact','ut_tel'],$this->para,'');
        $param['user_id'] = $this->user_id;
        $param['created'] = time();
        $res = $UsersTechInfo->saveUs($param,$user_id);
        return $this->response('deal_succ', '提交成功');
    }
   /**
     * [actionLogout 注销]
     * @apiDoc
     * @api     v1/common/logout
     * @group   common
     * @name    注销
     * @desc    门店APP-注销登录
     * @method  POST
     * @param token string Token req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
        {
        "code": "000000",
        "msg": "退出成功",
        "info": ''
        }
     */
     public function actionLogout()
    {
        if (empty($this->user_id)) {
            return $this->response('para_miss', '用户id为空');
        }
        $user_id = $this->user_id;
        $data = [
            'user_id' => $this->user_id,
            'registration' => '',
            'type' => 'shop',
            'source' => '',
        ];
        UserService::delToken($this->para['token'],'tech');
        //自动下线
        $Users = new UsersModel();
        $flag = $Users->getWidgetRow(['cols'=>['online_status','type','last_online_time','online_times'],'user_id'=>$this->user_id]);
        $redis = Yii::$app->redis;
        $redis_key = 'online:tech-info';
        if ($redis->hexists($redis_key, $this->user_id)) {
            $redis->hdel($redis_key, $this->user_id);
        }
        $Users->saveUs(['online_status'=>0,'online_times'=>(time()-$flag['last_online_time'])+$flag['online_times']],$this->user_id);
        //自动下线结束
        //UserService::addUserJPush($data);
        return $this->response('deal_succ', '退出成功');
    }
    /**
     * [actionSaveregid 绑定客户的registrationid]
     * @apiDoc
     * @api     v1/common/saveregid
     * @group   common
     * @name    绑定推送ID【极光】
     * @desc    门店APP-绑定客户的registrationid
     * @method  POST
     * @param registrationid string 设备号ID req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
        {
        "code": "000000",
        "msg": "保存设备号成功",
        "info": ''
        }
     */
    public function actionSaveregid()
    {
        if (empty($this->user_id)) {
            return $this->response('para_miss', '用户id为空');
        }
        if (!isset($this->para['registrationid']) || empty($this->para['registrationid'])) {
            return $this->response('para_miss', '设备号为空');
        }
        //1 ios/2 android
        $source=($this->para['terminalType']=='android')?'2':($this->para['terminalType']=='ios'?'1':'');
        if (empty($source)) {
            return $this->response('para_miss', '来源为空');
        }
        $data=[
            'user_id'=>$this->user_id,
            'registration'=>$this->para['registrationid'],
            'type'=>'tech',
            'source'=>$source,
        ];

        $re= UserService::addUserJPush($data);
        if ($re) {
            return $this->response('deal_succ', '保存设备号成功');
        } else {
            return $this->response('server_err', '保存设备号失败');
        }
    }
    /**
     * [actionOrdertype 获取订单类型]
     * @apiDoc
     * @api     v1/common/ordertype
     * @group   common
     * @name    获取订单类型
     * @desc    获取订单类型公用接口
     * @method  POST
     * @author JOHN.W
     * @version [1.0]
     * @return  json
    {
        "code": "000000",
        "msg": "获取成功",
        "info": [
        {
            "id": 1,
            "name": "实时单"
        },
        {
            "id": 2,
            "name": "预约单"
        }
        ]
    }
     */
    public function actionOrdertype(){
        $ret = Helper::getOrderType(1);
        return $this->response('deal_succ','获取成功' ,$ret);
    }

    /**
     * [actionUploadimg 上传图片]
     * @apiDoc
     * @api     v1/common/uploadimg
     * @group   common
     * @name    上传图片【公用】
     * @desc    公用上传图片接口
     * @method  POST
     * @param   upload_file png 图片路径 req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
        {
        "code": "000000",
        "msg": "上传成功",
        "info": "4"
        }
     */
    public function actionUploadimg(){
        $Upload = new UploadService();
        if(!isset($this->para['modelname'])) $this->para['modelname'] = 'tech';
        if(!isset($this->para['filename'])) $this->para['filename'] = 'upload_file';
        $res  = $Upload->sendUpimg($this->para);
        if(isset($res['code']) && $res['code']=='000000'){
            return $this->response('deal_succ',"上传成功",$res['info']);
        }else{
            return $this->response('deal_false',"上传失败", $res['msg']);
        }
    }
    /* [actionFeedback 提交投诉或意见]
     * @apiDoc
     * @api     v1/common/feedback
     * @group   common
     * @name    提交投诉或意见
     * @desc    个人设置-提交投诉或意见
     * @method  POST
     * @param  content string 内容 req
     * @author JOHN.W
     * @version [1.0]
     * @return  json
        {
        "code": "000000",
        "msg": "提交成功",
        "info": ""
        }
     */
    public function actionFeedback(){
        if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if (empty($this->para['content'])) {
            return $this->response('para_miss', '意见不能为空');
        }
        $param = [
            'content'=>$this->para['content'],
            'user_id'=>$this->user_id,
            'created'=>time(),
        ];
        $res = UserService::addComplaint($param);

        return $this->response('deal_succ',"提交成功");
    }
    /**
     * [actionModmobile 修改账号/手机号]
     * @apiDoc
     * @api    v1/common/modmobile
     * @group  common
     * @name   修改账号/手机号
     * @desc   技师APP-修改账号/手机号
     * @method POST
     * @param new_mobile string 新手机号 req
     * @param sms_code string 短信验证码 req
     * @return json
        {
        "code": "000000",
        "msg": "修改成功",
        "info": ''
        }
     */
    public function actionModmobile(){
        if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if(empty($this->para['new_mobile']) || !Verify::phoneFormat($this->para['new_mobile'])){
            return $this->response('para_miss', '手机号格式错误');
        }
        if(empty($this->para['sms_code'])){
            return $this->response('para_miss', '短信验证码不能为空');
        }
        $sms = new Sms();
        $param = [
            'mobile'=>$this->para['new_mobile'],
            'sms_code'=>$this->para['sms_code'],
        ];
        $flag_sms = $sms->verifyCode($param);
        if(!$flag_sms){
            return $this->response('para_miss', '短信验证码不正确');
        }
        $res = UserService::updateMobile(['user_id'=>$this->user_id],$this->para['new_mobile']);
        if ($res){
            return $this->response('deal_succ', '修改成功');
        } else {
            return $this->response('deal_false', '修改失败');
        }
    }
    /**
     * [actionSendsms description]
     * @apiDoc
     * @api    v1/common/sendsms
     * @group  common
     * @name   发送短信验证码
     * @desc   技师APP-公用发送短信
     * @method POST
     * @param mobile string 手机号 req
     * @param type string 类型【reg:注册 login:登录 modmobile:修改手机号 resetpwd:重置密码】 req
     * @return json
        {
        "code": "000000",
        "msg": "发送成功",
        "info": ''
        }
     */
    public function actionSendsms(){
        if(empty($this->para['mobile']) || !Verify::phoneFormat($this->para['mobile'])){
            return $this->response('para_miss', '手机号格式错误');
        }
        if(empty($this->para['type']) || !in_array($this->para['type'], ['reg','modmobile','login','resetpwd'])){
            return $this->response('para_miss', '发送验证类型不正确');
        }
        //校验手机号是否存在
        if($this->para['type']=='modmobile'){
           $flag_mobile =  UserService::userPhoneExists($this->para['mobile']);
           if($flag_mobile){
               return $this->response('para_miss', '修改手机号码占用');
           }
        }

        $sms = new Sms();
        $param = [
            'mobile'=>$this->para['mobile'],
            'tp_code'=>$this->para['type'],
        ];
        $res = $sms->send($param);
        if ($res) {
            return $this->response('deal_succ', '发送成功');
        } else {
            return $this->response('deal_false', '发送失败');
        }
    }
}