<?php
namespace Passport\Src;

use Dever;
use Passport\Src\Lib\Base;

class App extends Base
{
    /**
     * 更新用户信息
     *
     * @return mixed
     */
    public function update()
    {
        $uid = $this->check();
        $name = Dever::input('username');
        $pic = Dever::input('avatar');
        $sex = Dever::input('gender');
        $city = Dever::input('city');
        $mobile = Dever::input('mobile');
        $province = Dever::input('province');
        $country = Dever::input('country');

        $info = Dever::load('passport/user-one', $uid);
        if ($info) {
            $update['set_username'] = $name;
            $update['set_avatar'] = $pic;
            $update['set_sex'] = $sex;
            $update['set_city'] = $city;
            $update['set_province'] = $province;
            $update['set_country'] = $country;
            if ($country && $province && $city) {
            	$update['set_area'] = $country . ',' . $province . ',' . $city;
            }
            
            $update['where_id'] = $uid;
            Dever::load('passport/user-update', $update);
        } else {
            Dever::alert('无效的用户id,请重新登录');
        }

        $result = Dever::db('passport/user')->one($uid);
        $result['uid'] = $uid;
        $result['signature'] = Dever::login($uid);

        return $result;
    }

    /**
     * 生成用户或者登录
     *
     * @return int
     */
    public function login()
    {
    	$mobile = Dever::input('mobile');
    	$code = Dever::input('code');
    	$source_type = Dever::input('source_type', 'applet');
    	$send['skin'] = 'code';
    	$send['mobile'] = $mobile;
    	$send['code'] = $code;

        # 添加测试账号
        if ($mobile) {

        } else {
        	$mobile = Dever::load('passport/reg')->checkMobileExists();
        }
    	

        $uid = false;
        $info = Dever::load('passport/user-one', array('mobile' => $mobile));
        if (!$info) {
            $user['add_username'] = Dever::hide($mobile);
            $user['add_mobile'] = $mobile;
            $user['add_bind'] = 1;
            $user['add_temp'] = 2;
            $user['add_source_type'] = $source_type;
            $uid = Dever::load('passport/user-insert', $user);

            Dever::score($uid, 'mobile_reg', '手机号注册');
        } else {
        	$uid = $info['id'];
        }

        # 记录app登录日志
        $appData = array('uid' => $uid, 'source_type' => $source_type);
        $app = Dever::db('passport/app')->one($appData);
        if (!$app) {
        	Dever::db('passport/app')->insert($appData);
        }

        $result = Dever::db('passport/user')->one($uid);
        $result['uid'] = $uid;
        $result['signature'] = Dever::login($uid);
        return $result;
    }

    //获取用户信息
    public function user() {
        $uid = $this->check();
        $data=Dever::db('passport/user')->one($uid);
        if(!$data['pic']){
                $data['pic']=DEVER_APP_HOST . '../data/upload/pic.png';
        }
        return $data;
    }
}