<?php
namespace app\home\controller;
use think\Lang;

class Connectwx extends BaseMall
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/connectwx.lang.php');
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/login-register.lang.php');
    }
    /**
     * 微信登录
     */
    public function index(){
        if(empty(input('get.code'))) {
            echo $this->fetch($this->template_dir.'index');
        } else {
            $this->get_info();
        }

    }
    /**
     * 微信注册后修改密码
     */
    public function edit_info(){
        if (model('member')->getMemberInfo(array('member_email' => input('param.email')))){
            $this->error(lang('login_register_email_exists'), 'Login/register');
        }
            $member_model = model('member');
            $member = array();
            $member['member_password'] = md5(input('post.password'));
            if(!empty(input('post.email'))) {
                $member['member_email']= input('post.email');
                session('member_email', input('post.email'));
            }
            $member_model->editMember(array('member_id'=> session('member_id')),$member);
            $this->success(lang('ds_common_save_succ'),'member/index');
    }
    /**
     * 回调获取信息
     */
    public function get_info(){
        $code = input('get.code');
        if(!empty($code)) {
            $user_info = $this->get_user_info($code);
            if(!empty($user_info['unionid'])) {
                $unionid = $user_info['unionid'];
                $member_model = model('member');
                $member = $member_model->getMemberInfo(array('member_wxunionid'=> $unionid));
                if(!empty($member)) {//会员信息存在时自动登录
                    if (!$member['member_state']) {//1为启用 0 为禁用
                        $this->error(lang('login_index_account_stop'));
                    }
                    $member_model->createSession($member);
                    $this->success(lang('login_index_login_success'),'member/index');
                }
                if(session('member_id')) {//已登录时绑定微信
                    $member_id = session('member_id');
                    $member = array();
                    $member['member_wxunionid'] = $unionid;
                    $member['member_wxinfo'] = $user_info['member_wxinfo'];
                    $member_model->editMember(array('member_id'=> $member_id),$member);
                    $this->success(lang('wechat_binding_was_successful'),'member/index');
                } else {
                    //自动注册会员并登录
                    $logic_connect_api = model('connectapi', 'logic');
                    
                    $reg_info = array(
//                        'member_wxopenid'=>$user_info['openid'], #开发者帐号唯一标识,与公众号标识不同
                        'member_wxopenid'=>'',
                        'member_wxunionid'=>$user_info['unionid'],
                        'nickname'=> isset($user_info['nickname'])?$user_info['nickname']:'',
//                        'headimgurl'=> isset($user_info['headimgurl'])?$user_info['headimgurl']:'',#提高体验暂时不对图片进行处理
                    );
                    
                    $wx_member = $logic_connect_api->wx_register($reg_info,'wx');
                    if (!empty($wx_member)) {
                        if (!$wx_member['member_state']) {//1为启用 0 为禁用
                            $this->error(lang('login_index_account_stop'));
                        }
                        $member_model->createSession($wx_member, true); //自动登录
                        $this->assign('user_info', $user_info);
                        $this->assign('headimgurl', $user_info['headimgurl']);
                        $this->assign('password', '');
                        echo $this->fetch($this->template_dir . 'register');
                    }
                    exit;
                }
            }
        }
        $this->success(lang('wechat_binding_was_failed'),'login/login');
    }
    /**
     * 获取用户个人信息
     */
    public function get_user_info($code){
        $weixin_appid = config('weixin_appid');
        $weixin_secret = config('weixin_secret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$weixin_appid.'&secret='.$weixin_secret.'&code='.$code.'&grant_type=authorization_code';
        $access_token = http_request($url);//通过code获取access_token
        $code_info = json_decode($access_token, true);
        $user_info = array();
        if(!empty($code_info['access_token'])) {
            $token = $code_info['access_token'];
            $openid = $code_info['openid'];
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid;
            $result = http_request($url);//获取用户个人信息
            $user_info = json_decode($result, true);
            $member_wxinfo = array();
            $member_wxinfo['unionid'] = $user_info['unionid'];
            $member_wxinfo['nickname'] = $user_info['nickname'];
            $member_wxinfo['openid'] = $user_info['openid'];//普通用户的标识，对当前开发者帐号唯一   不是公众号的 openid
            $user_info['member_wxinfo'] = serialize($member_wxinfo);
        }
        return $user_info;
    }
}