<?php

namespace Api\Controller;

class LoginController extends PublicController
{
    /**
     * @description: 子类的初始化
     */
    public function _initialize()
    {
    }
    /**
     * @description: 授权登录 未注册过 进行注册之后 登录
     */
    public function authLogin()
    {
        $wx_config = C('weixin');
        $appid = $wx_config['appid'];
        $secret = $wx_config['secret'];
        $code = trim($_REQUEST['code']);
        //合法性检查
        if (!$code) {
            echo json_encode(array('status' => 0, 'msg' => '非法操作！'));
            exit();
        }
        if (!$appid || !$secret) {
            echo json_encode(array('status' => 0, 'msg' => '非法操作！' . __LINE__));
            exit();
        }
        //从微信服务器获取用户信息
        $get_token_url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $getAuth = $this->apiUrl($get_token_url);
        //授权
        $where['openid'] = $getAuth['openid'];
        $field = array('name,photo,tel,sex,del');
        $userDb = D('user');
        $user = $userDb->field($field)->where($where)->find();
        if ($user !== null) {
            //账户停用返回状态
            if ($user['del'] == "1") {
                echo json_encode(array('status' => 0, 'msg' => '账户已停用'));
                exit();
            }
            // 用户已经注册 分发token等用户信息给前端
            $token = $this->makeToken($getAuth['openid'], $getAuth['session_key']);
            if ($user['tel'] != null) {
                $user['tel'] = $this->maskPhoneNumber($user['tel']); //用户已经填写过 电话的话 给前端返回 截取替换* 之后的电话号
            }
            $userInfo = array('token' => $token, 'name' => $user['name'], 'photo' => $user['photo'], 'sex' => $user['sex'], 'tel' => $user['tel'], 'topic_prefix' => $this->makeTopicPrefix($getAuth['openid']));
            echo json_encode(array('status' => 1, 'userInfo' => $userInfo));
        } else {
            //用户首次登录 先进行注册 再分发token给前端
            $data['openid'] = $getAuth['openid'];
            $data['addtime'] = time();
            if ($id = $userDb->data($data)->add()) {
                $user = $userDb->find($id); //获取刚刚插入的记录
                //分发token等用户信息给前端
                $token = $this->makeToken($getAuth['openid'], $getAuth['session_key']);
                $userInfo = array('token' => $token, 'name' => $user['name'], 'photo' => $user['photo'], 'sex' => $user['sex'], 'tel' => $user['tel'], 'topic_prefix' => $this->makeTopicPrefix($getAuth['openid']));
            } else {
                //数据库写入失败
                echo json_encode(array('status' => 0, 'msg' => '系统出错'));
                exit();
            }
        }
    }
}
