<?php
namespace Passport\Src;

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

# 小程序

class Applet extends Base
{
  	public function init()
    {
      	$uid = $this->check();
        $user = Dever::load('passport/user-one', $uid);

        return $user;
    }
    /**
     * 用户绑定 生成用户信息
     *
     * @return mixed
     */
    public function bind()
    {
        $token = Dever::project('token');
        $applet = array();
        if ($token) {
            $applet = Dever::db('token/project')->one(Dever::input('appid', 1));
        }

        if (!$applet) {
            $applet = Dever::config('base', 'project')->applet;
        }
        

        $appid = $applet['appid'];
        $secret = $applet['secret'];
        $url = $applet['url'];
        $code = Dever::input('code');

        $url .= '?appid=' . $appid;
        $url .= '&secret=' . $secret;
        $url .= '&js_code=' . $code;
        $url .= '&grant_type=authorization_code';

        $data = Dever::curl($url);
        if (strstr($data, 'errcode')) {
            Dever::alert($data);
        }

        //YzJkOThpRFhwZ1lQTF9mZl9hLVZjZnFXemJVenlYcDQ3d3JWekk0b1I4NjBBQ0Naejg4a0VQa0U=
        //$data = '{"session_key":"aNAXk7nG\/DRYI\/G0KzJRsw==","openid":"oIZ895RZs2ZkywasoZIv6WavPZlQ"}';
        $data = Dever::json_decode($data);

        $user = $this->create($data);

        return $user;
    }

    /**
     * 更新用户信息 绑定用户手机号
     *
     * @return mixed
     */
    public function bind_mobile()
    {
        $uid = $this->check();
        //$code = Dever::input('mcode');
        $mobile = Dever::load('passport/reg')->checkMobileExists();
        if ($mobile && $uid) {
            $info = Dever::load('passport/user-one', $uid);
            $result['mobile'] = $mobile;
            if ($info) {
                $update['set_mobile'] = $mobile;
                $update['set_bind'] = 1;
                $update['where_id'] = $uid;
                Dever::load('passport/user-update', $update);

                $state = Dever::config('base', 'project')->regSendSms;
                if ($state) {
                    Dever::setInput('skin', $state);
                    $this->send($mobile, $uid);
                }
            } else {
                Dever::alert('无效的用户id,请重新登录');
            }
        }

        if (!$info['mobile']) {
            Dever::score($uid, 'bind_mobile', '绑定手机号');
        }

        $result['uid'] = $uid;
        $result['signature'] = Dever::login($uid);

        return $result;
    }

    /*
    public function test_sms()
    {
        $uid = Dever::input('uid');
        $mobile = Dever::input('mobile');
        $state = Dever::config('base', 'project')->regSendSms;
        if ($state) {
            Dever::setInput('skin', $state);
            $this->send($mobile, $uid);
        }
    }
    */

    /**
     * 生成用户，返回uid
     *
     * @return int
     */
    private function create($data)
    {
        $uid = false;
        $info = Dever::load('passport/wechat-one', array('option_openid' => $data['openid']));

        if (!$info) {
            if (isset($data['unionid']) && $data['unionid']) {
                $info = Dever::load('passport/wechat-one', array('unionid' => $data['unionid']));
                if (!$info) {
                    $uid = false;
                } else {
                    $uid = $info['uid'];
                }
                $wechat['unionid'] = $data['unionid'];
            }
            if (!$uid) {
                $user['bind'] = 2;
                $user['temp'] = 1;
                $user['username'] = '临时用户';
                $user['source_type'] = 'applet';

                $uid = Dever::load('passport/user-insert', $user);
            }
             
            $wechat['openid'] = $data['openid'];
            $wechat['session_key'] = $data['session_key'];
            $wechat['uid'] = $uid;
            $wechat['type'] = 1;
            $id = Dever::load('passport/wechat-insert', $wechat);
        } else {
            $uid = $info['uid'];
            if (isset($data['unionid']) && $data['unionid']) {
                $wechat['unionid'] = $data['unionid'];
            }
            
            $wechat['session_key'] = $data['session_key'];
            $wechat['where_id'] = $info['id'];
            $id = $info['id'];
            Dever::load('passport/wechat-update', $wechat);
        }

        $user = Dever::load('passport/user-one', $uid);

        $result['vid'] = $id;
        $result['uid'] = $uid;
        $result['signature'] = Dever::login($uid);
      
      	if ($user['mobile']) {
        	$result['mobile'] = $user['mobile'];
        }

        return $result;
    }

    /**
     * 更新用户信息 手机号
     *
     * @return mixed
     */
    public function mobile()
    {
        $uid = $this->check();
        $vid = Dever::input('vid');
        $result = array();
        $mobile = $phoneNumber = '';

        $iv = Dever::input('iv');
        $encryptedData = Dever::input('encryptedData');
        
        if ($iv && $encryptedData) {
            $vinfo = Dever::load('passport/wechat-one', $vid);
            $data = $this->decryptData($vinfo['session_key']);
            if ($data && isset($data->purePhoneNumber) && isset($data->phoneNumber)) {
                $mobile = $data->purePhoneNumber;
                $phoneNumber = $data->phoneNumber;
            }
        }

        if ($mobile && $phoneNumber && $uid) {
            $info = Dever::load('passport/user-one', $uid);
            $result['mobile'] = $mobile;
            if ($info) {
                $update['set_mobile'] = $mobile;
                $update['set_bind'] = 1;
                $update['where_id'] = $uid;
                Dever::load('passport/user-update', $update);

                $state = Dever::config('base', 'project')->regSendSms;
                if ($state) {
                    Dever::setInput('skin', $state);
                    $this->send($mobile, $uid);
                }
            } else {
                Dever::alert('无效的用户id,请重新登录');
            }
        }

        if (!$info['mobile']) {
            Dever::score($uid, 'bind_mobile', '绑定手机号');
        }

        $result['vid'] = $vid;
        $result['uid'] = $uid;
        $result['signature'] = Dever::login($uid);

        return $result;
    }

    /**
     * 更新用户信息
     *
     * @return mixed
     */
    public function update()
    {
        $uid = $this->check();
        $name = Dever::emoji(Dever::input('nickname'));
        $pic = Dever::input('avatarurl');
        $sex = Dever::input('gender');
        $city = Dever::input('city');
        $mobile = Dever::input('mobile');
        $province = Dever::input('province');
        $country = Dever::input('country');
        $vid = Dever::input('vid');

        $update['temp'] = 3;
        if ($vid) {
            $vinfo = Dever::load('passport/wechat-one', $vid);

            $unionid = $this->unionid($vinfo['session_key']);
            if ($unionid) {
                $vinfo = Dever::load('passport/wechat-one', array('option_unionid' => $unionid));
                if (!$vinfo) {
                    $wechat['set_unionid'] = $unionid;
                    $wechat['where_id'] = $vid;
                    Dever::load('passport/wechat-update', $wechat);
                } elseif ($vinfo && $vinfo['id'] != $vid) {
                    $wechat['set_unionid'] = $unionid;
                    $wechat['set_uid'] = $vinfo['uid'];
                    $wechat['where_id'] = $vid;

                    # 删除user信息
                    if ($uid != $vinfo['uid']) {
                        Dever::load('passport/user-update', array('set_state' => 2, 'where_id' => $uid));
                    }
                    
                    $uid = $vinfo['uid'];
                    Dever::load('passport/wechat-update', $wechat);
                }
                
                $update['temp'] = 2;
            }
        }

        $info = Dever::load('passport/user-one', $uid);
        if ($info) {

            if ($info['temp'] == 1) {
                Dever::score($uid, 'bind_wechat', '用户微信授权');
            }
            $update['temp'] = 2;
            if ($name) {
                $update['set_username'] = $name;
            }
            
            if ($sex == 1) {
                $update['set_sex'] = 1;
            } elseif ($sex == 2) {
                $update['set_sex'] = 2;
            } else {
                $update['set_sex'] = 3;
            }
            /*
            if ($sex || $sex == 0) {
                $update['set_sex'] = $this->saveSex($sex);
            }
            */
            
            if ($pic) {
                //$update['set_avatar'] = $this->saveAvatar($pic);
              	$update['set_avatar'] = $pic;
            }
            
            if ($city) {
                $update['set_city'] = $city;
            }
            
            //$update['set_mobile'] = $mobile;
            if ($province) {
                $update['set_province'] = $province;
            }
            
            if ($country) {
                $update['set_country'] = $country;
            }
            
            if ($country && $province && $city) {
                $update['set_area'] = $country . ',' . $province . ',' . $city;
            }
            if (isset($update) && $update) {
                $update['where_id'] = $uid;
                Dever::load('passport/user-update', $update);
            }
            
        } else {
            Dever::alert('无效的用户id,请重新登录');
        }

        $result['vid'] = $vid;
        $result['uid'] = $uid;
        $result['signature'] = Dever::login($uid);

        return $result;
    }

    private function unionid($session_key)
    {
        $data = $this->decryptData($session_key);
        if ($data && isset($data->unionId)) {
            return $data->unionId;
        }
        
        return false;
    }

    private function decryptData($session_key)
    {
    	$iv = Dever::input('iv');
        $encryptedData = Dever::input('encryptedData');

        if (!$iv || !$encryptedData) {
        	return false;
        }
        if (strlen($session_key) != 24) {
            return false;
        }
        if (strlen($iv) != 24) {
            return false;
        }

        $aesKey = base64_decode($session_key);

        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj  == NULL) {
            return false;
        }
      	$applet = Dever::config('base', 'project')->applet;
        $appid = $applet['appid'];
        if($dataObj->watermark->appid != $appid) {
            return false;
        }
        return $dataObj;
    }
}
