<?php

namespace app\api\controller;

use app\common\model\User as UserModel;
use app\admin\controller\Upload;

class User extends Base
{
    /**
     * 获取token
     * @url /api/User/token
     * @params uid 用户的UID
     * return json
     */
    public function token()
    {
        $uid   = input('post.uid');
        $user  = UserModel::get($uid);
        $token = $this->usertoken($user);
        return ["code" => 0, "msg" => "成功", "token" => $token, "user" => $user];
    }

    /**
     * 用户小程序授权
     * @url /api/User/login
     * @params  code
     * @params  encryptedData
     * @params  iv
     * return json
     */
    public function login()
    {
        $jscode = input("post.code");
//        $signature     = input("post.signature");
//        $rawData       = input("post.rawData");
        $encryptedData = input("post.encryptedData");
        $iv            = input('post.iv');

        // 获取session_key
        $appId     = config("wxapp.appKey");
        $appSecret = config("wxapp.appSecret");
        $wxurl     = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appId . "&secret=" . $appSecret . "&js_code=" . $jscode . "&grant_type=authorization_code";

        $response = http_get($wxurl);
        if (isset($response->errcode) && $response->errcode > 0) {
            return ["code" => 1, "msg" => $response->errmsg];
        }

        // session_key 和 openid
        // 过期时间2小时 7200s
        $session_key = $response->session_key;
        $openid      = $response->openid;

        // 解密加密数据
        include_once VENDOR_PATH . 'aesphp/wxBizDataCrypt.php';
        $pc      = new \WXBizDataCrypt($appId, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            $data = json_decode($data);
            $user = UserModel::where(['openid' => $data->openId])->find();
            if ($user) {
                //更新
                // 省份和城市
                $user->city     = $data->city;
                $user->province = $data->province;
                //ip
                $user->ip = request()->ip();
                $user->save();
                // 登录成功
                $token = $this->usertoken($user);
                return ["code" => 0, "msg" => "登录成功", "token" => $token, "user" => $user];
            } else {
                //第一次注册
                $user           = new UserModel;
                $user->openid   = $data->openId;
                $user->nickname = $data->nickName;;
                // 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                $user->gender = intval($data->gender);
                $user->avatar = $data->avatarUrl;
                $user->is_vip = 0;  // 0非会员 1会员 默认为非会员
                // 省份和城市
                $user->city     = $data->city;
                $user->province = $data->province;
                //ip
                $user->ip = request()->ip();
                if ($user->save()) {
                    // 注册成功
                    $token = $this->usertoken($user);
                    return ["code" => 0, "msg" => "注册成功", "token" => $token, "user" => $user];
                } else {
                    return ["code" => 1, "msg" => "注册失败"];
                }
            }
        } else {
            return ["code" => 1, "msg" => "注册失败，请重试！"];
        }
    }

    /**
     * 微信手机授权
     * @url /api/User/getPhoneNumber
     * @params code
     * @params encryptedData
     * @params iv
     * return json
     */
    public function getPhoneNumber()
    {
        $jscode        = input("post.code");
        $encryptedData = input("post.encryptedData");
        $iv            = input('post.iv');

        if (!$jscode || !$encryptedData || !$iv) {
            return ["code" => 1, "msg" => "参数错误"];
        }
        if (!$this->userinfo) {
            return ["code" => 1, "msg" => "未登录"];
        }

        // 获取session_key
        $appId     = config("wxapp.appKey");
        $appSecret = config("wxapp.appSecret");
        $wxurl     = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appId . "&secret=" . $appSecret . "&js_code=" . $jscode . "&grant_type=authorization_code";

        $response = http_get($wxurl);

        // session_key 和 openid
        // 过期时间2小时 7200s
        $session_key = $response->session_key;
        $openid      = $response->openid;

        // 解密加密数据
        include_once VENDOR_PATH . 'aesphp/wxBizDataCrypt.php';
        $pc      = new \WXBizDataCrypt($appId, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            $data      = json_decode($data);
            $phone     = $data->purePhoneNumber;
            $hidephone = substr_replace($phone, '****', 3, 4);

            $user        = UserModel::get($this->userinfo[0]);
            $user->phone = $phone;
            $user->save();

            $result = ['phone' => $phone, 'hidephone' => $hidephone];
            return ["code" => 0, "msg" => "获取成功", 'data' => $result];
        } else {
            return ["code" => 1, "msg" => "微信数据解密失败，请重试！"];
        }
    }

    public function index()
    {
        //用户UID
        $uid               = $this->userinfo[0];
        $user              = UserModel::get($uid)->toArray();
        //过期时间
        if($user['is_vip']){
            if(strtotime($user['vip_endtime'])>time()){
                $user['vip_endtime_str'] = '剩余'.ceil((strtotime($user['vip_endtime'])-time())/86400).'天';
            }else{
                $user['vip_endtime_str'] = '已到期';
            }
        }else{
            $user['vip_endtime_str'] = '';
        }
        $user['hidephone'] = substr_replace($user['phone'], '****', 3, 4);
        return ['code' => 0, 'msg' => 'success', 'data' => $user];
    }


    /**
     * 更新用户
     * @url /api/User/update
     * @param nickname 姓名
     * @param sex 性别
     * @return json
     */
    public function update()
    {
        //用户ID
        $uid  = $this->userinfo[0];
        $user = UserModel::get($uid);

        //可选更新
        if (input('post.nickname')) $user->nickname = input('post.nickname');
        if (input('post.gender')) $user->gender = input('post.gender');
        if (input('post.avatar')) $user->avatar = input('post.avatar');
        $user->save();
        return ['code' => 0, 'msg' => '更新成功'];
    }


    /**
     * 用户收藏列表
     * @url /api/User/userCollections
     * @param p 当前页
     * @param page 一页显示几条
     * @return json
     */
    public function userCollections()
    {
        $uid  = $this->userinfo[0];
        $p    = input('post.p/d', 1);
        $page = input('post.page/d', 8);


        
        $list = collection(UserModel::get($uid)->project()->page($p, $page)->select());


        if ($list->isEmpty()) {
            return ['code' => 1, 'msg' => '没有更多'];
        }
        $list = $list->visible(['id', 'title', 'poster', 'sign_limits', 'night_num', 'tags', 'price', 'vip_price', 'type', 'location', 'latitude', 'longitude'])->append(['sign_endtime_str']);
        
        return ['code'=>0,'msg'=>'success','data'=>$list];
    }

    /**
     * 更新头像
     * @url /api/User/uploadAvatar
     * @param avatar 头像资源
     * @return json
     */
    public function uploadAvatar()
    {
        $file   = request()->file('avatar');
        $upload = new Upload();
        $result = $upload->sava($file);
        if ($result['error'] == 1) {
            return ['code' => 1, 'msg' => $result['msg']];
        }
        $url = $result['result']['url'];
        //上传头像
        // $user         = UserModel::get($this->userinfo[0]);
        // $user->avatar = $url;
        // $user->save();
        return ['code' => 0, 'msg' => '更新成功', 'avatar_url' => $url];
    }

}