<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016～2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace basic;


use app\wap\model\user\User;
use app\wap\model\user\WechatUser;
use behavior\wap\WapBehavior;
use service\JsonService;
use think\Controller;
use behavior\wechat\UserBehavior;
use service\HookService;
use service\UtilService;
use service\WechatService;
use service\WechatSubscribe;
use think\Cookie;
use think\Request;
use think\Session;
use think\Url;

class WapBasic extends Controller
{
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        HookService::listen('wap_init',null,null,false,WapBehavior::class);
    }

    /**
     * 操作失败 弹窗提示
     * @param string $msg
     * @param int $url
     * @param string $title
     */
    protected function failed($msg = '操作失败', $url = 0, $title='信息提示')
    {

        if($this->request->isAjax()){
            exit(JsonService::fail($msg,$url)->getContent());
        }else {
            $this->assign(compact('title', 'msg', 'url'));
            exit($this->fetch('public/error'));
        }
    }

    /**
     * 操作成功 弹窗提示
     * @param $msg
     * @param int $url
     */
    protected function successful($msg = '操作成功', $url = 0, $title='成功提醒')
    {
        if($this->request->isAjax()){
            exit(JsonService::successful($msg,$url)->getContent());
        }else {
            $this->assign(compact('title', 'msg', 'url'));
            exit($this->fetch('public/success'));
        }
    }

    public function _empty($name)
    {
        $url = strtolower($name) == 'index' ? Url::build('Index/index','',true,true) : 0;
        return $this->failed('请求页面不存在!',$url);
    }

    /**判断redis状态
     * @param $msg
     */
    public function serRedisPwd($msg){
        if(strpos($msg,'username-password pair') !==false){
            return $this->failed('请检查redis密码!','http://help.crmeb.net/crmeb_zsff/2291680');
        }elseif (strpos($msg,'Connection refused') !==false){
            return $this->failed('请安装redis软件或连接被拒绝!');
        }elseif (strpos($msg,'NOAUTH Authentication required') !==false){
            return $this->failed('redis认证错误!','http://help.crmeb.net/crmeb_zsff/2000690');
        }elseif (strpos($msg,'not support: redis') !==false){
            return $this->failed('请安装redis扩展!','http://help.crmeb.net/crmeb_zsff/1863590');
        }else{
            return $this->failed('请设置redis密码!','http://help.crmeb.net/crmeb_zsff/1907223');
        }
    }
    /**
     * 微信用户自动登陆
     * @return string $openid
     */
    protected function oauth($spread_uid=0)
    {
        $openid = Session::get('loginOpenid','wap');
        if($openid) return $openid;
        if(!UtilService::isWechatBrowser()) exit($this->failed('请在微信客户端打开链接'));
        if($this->request->isAjax()) exit($this->failed('请登陆!'));
        $errorNum = (int)Cookie::get('_oen');
        if($errorNum && $errorNum > 3) exit($this->failed('微信用户信息获取失败!!'));
        try{
            $original=WechatService::oauthService()->getAccessToken($this->request->get('code'));
            if (!WechatUser::be(['openid' => $original->openid]) && $original->scope === 'snsapi_base'){
                exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                    ->redirect($this->request->url(true))->send());
            }
            $wechatInfo=WechatSubscribe::baseParseGet($original->access_token,$original->openid);//获取单个用户信息
            if(isset($wechatInfo['errcode']) && $wechatInfo['errcode']==48001){
                exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                    ->redirect($this->request->url(true))->send());
            }
        }catch (\Exception $e){
            Cookie::set('_oen',++$errorNum,900);
            exit(WechatService::oauthService()->scopes(['snsapi_base'])
                ->redirect($this->request->url(true))->send());
        }
        if(!isset($wechatInfo['nickname']) || $wechatInfo['nickname']==''){
            exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
                ->redirect($this->request->url(true))->send());
        }
        if(isset($wechatInfo['openid']) && $wechatInfo['openid']){
            $wechatInfoData = WechatService::getUserInfo($wechatInfo['openid']);
            $wechatInfo['subscribe'] =$wechatInfoData['subscribe'];
            $wechatInfo['subscribe_time'] =$wechatInfoData['subscribe_time'];
            $wechatInfo['groupid'] =$wechatInfoData['groupid'];
            if(isset($wechatInfoData['tagid_list'])) $wechatInfo['tagid_list'] = implode(',',$wechatInfoData['tagid_list']);
        }else{
            if(isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
            if (!WechatUser::be(['openid' => $wechatInfo['openid']])) $wechatInfo['subscribe'] = 0;
        }
        Cookie::delete('_oen');
        $openid = $wechatInfo['openid'];
        $wechatInfo['spread_uid']=$spread_uid;
        HookService::afterListen('wechat_oauth',$openid,$wechatInfo,false,UserBehavior::class);
        Session::set('loginOpenid',$openid,'wap');
        Cookie::set('is_login',1);
        return $openid;
    }

}
