<?php
namespace Passport\Lib;

use Dever;
use Upload\Src\Lib\Img;
use Dever\Routing\Uri;
use Dever\Session\Oper as Save;
use Dever\String\Encrypt;

class Base
{
    const NAME = 'passportv1';

    const CODE = 'code';

    const MCODE = 'mcode';

    protected $save;

    public function __construct()
    {
        //$this->save = new Save(false, 'cookie');
        $this->save = new Save(false, 'session');
    }

    # 注册用户
    public function reg($type, $data)
    {
        $user = $this->getUserExtInfo($data);

        $user['source_type'] = $type;
        $user['system_id'] = isset($data['system']) ? $data['system'] : 1;

        if (isset($data['username'])) {
            $user['temp'] = 2;
            $user['username'] = $data['username'];
        } else {
            $user['temp'] = 1;
            $user['username'] = '临时用户';
        }

        if (isset($data['mobile'])) {
            $user['bind'] = 1;
            $user['mobile'] = $data['mobile'];
        } else {
            $user['bind'] = 2;
            $user['mobile'] = '';
        }

        $uid = Dever::db('passport/user')->insert($user);

        $this->createUsername($uid, $user['username'], true);

        return $uid;
    }

    # 更新用户
    public function updateUser($uid, $data)
    {
        $user = $this->getUserExtInfo($data);
        $user['username'] = $this->createUsername($uid, $data['username']);
        if (isset($user) && $user) {
            $update['where_id'] = $uid;
            Dever::db('passport/user')->update($update);
        }
        return $uid;
    }

    private function getUserExtInfo($data)
    {
        $user = array();
        if (isset($data['sex'])) {
            $user['sex'] = $data['sex'];
        }
        if (isset($data['avatar'])) {
            //$update['avatar'] = $this->saveAvatar($pic);
            $user['avatar'] = $data['avatar'];
        }
        if (isset($data['city'])) {
            $user['city'] = $data['city'];
        }
        if (isset($data['province'])) {
            $user['province'] = $data['province'];
        }
        if (isset($data['country'])) {
            $user['country'] = $data['country'];
        }
        if (isset($user['country']) && isset($user['province']) && isset($user['city'])) {
            $user['set_area'] = $user['country'] .','. $user['province'] .','. $user['city'];
        }

        return $user;
    }

    public function wechat($data, $user = array(), $account, $system, $source_type, $source = false)
    {
        $uid = false;

        if (!$data['openid']) {
            Dever::alert('错误的openid');
        }

        if (!isset($user['username'])) {
            Dever::alert('用户名错误');
        }

        if (isset($user['sex'])) {
            if ($user['sex'] != 1 && $user['sex'] != 2) {
                $user['sex'] = 3;
            }
        }

        if (isset($user['country']) && $user['country'] && isset($user['province']) && $user['province'] && isset($user['city']) && $user['city']) {
            $user['area'] = $user['country'] .','. $user['province'] .','. $user['city'];
        }
        
        $info = Dever::db('passport/wechat')->one(array('openid' => $data['openid']));

        if (!$info) {
            if (isset($data['unionid']) && $data['unionid']) {
                $info = Dever::db('passport/wechat')->one(array('unionid' => $data['unionid']));
                if (!$info) {
                    $uid = false;
                } else {
                    $uid = $info['uid'];
                }
                $wechat['unionid'] = $data['unionid'];
            }
            if (!$uid) {
                $user['source_type'] = 'service';
                if ($system) {
                    $user['system_id'] = $system;
                }
                if ($source_type) {
                    $user['source_type'] = $source_type;
                }
                $uid = Dever::db('passport/user')->insert($user);
            } else {
                $user['where_id'] = $uid;
                Dever::db('passport/user')->update($user);
            }

            $wechat['access_token'] = $data['access_token'];
            $wechat['openid'] = $data['openid'];
            $wechat['expires_in'] = $data['expires_in'];
            $wechat['refresh_token'] = $data['refresh_token'];
            $wechat['account_id'] = $account;
            if ($system) {
                $wechat['system_id'] = $system;
            }
            
            $wechat['uid'] = $uid;
            $wechat['type'] = 2;
            if ($source_type == 'applet') {
                $wechat['type'] = 1;
            } elseif ($source_type == 'ios') {
                $wechat['type'] = 3;
            } elseif ($source_type == 'android') {
                $wechat['type'] = 4;
            }
            $id = Dever::db('passport/wechat')->insert($wechat);

            if (Dever::project('source') && isset($source) && $source && $source > 0) {
                Dever::load('source/lib/core')->saveUser($id, $uid, $source, 'oauth', $account);
            }
        } else {
            $uid = $info['uid'];
            if (isset($data['unionid']) && $data['unionid']) {
                $wechat['unionid'] = $data['unionid'];
                # 判断用户是否存在，是否需要合并
                //$wechat['uid'] = $this->combine($uid, $data['unionid']);
            }
            
            $wechat['access_token'] = $data['access_token'];
            $wechat['openid'] = $data['openid'];
            $wechat['expires_in'] = $data['expires_in'];
            $wechat['refresh_token'] = $data['refresh_token'];
            $wechat['where_id'] = $info['id'];
            $wechat['account_id'] = $account;
            if ($system) {
                $wechat['system_id'] = $system;
            }
            $id = $info['id'];
            //Dever::db('passport/wechat')->update($wechat);

            $user['where_id'] = $uid;
            //Dever::load('passport/user-update', $user);
        }

        $this->createUsername($uid, $user['username']);

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

        $this->save($user);

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

        return $user;
    }

    /**
     * 更新用户信息 绑定用户手机号
     *
     * @return mixed
     */
    public function bind_mobile()
    {
        $uid = $this->check();
        //$code = Dever::input('mcode');
        $mobile = Dever::load('passport/reg')->checkMobileExists();
        //$mobile = Dever::input('mobile');
        if ($mobile && $uid) {
            $info = Dever::load('passport/user-one', array('mobile' => $mobile));
            if ($info && $info['bind'] == 1) {
                Dever::alert('该手机号已绑定');
            }
            $uid = $this->combine($uid, $mobile, 'mobile');
            $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 createUsername($uid, $username, $update = false)
    {
        if (!$username || $username == '临时用户') {
            $username = $uid + 100000;
            $username = 'JM' . $username;

            if ($update) {
                Dever::db('passport/user')->update(array('where_id' => $uid, 'username' => $username));
            }
        }
        
        return $username;
    }

    # 合并用户
    public function combine($uid, $unionid, $col = 'unionid')
    {
        $cur = $uid;
        if ($col == 'mobile' || $col == 'id') {
            $user_wechat = Dever::load('passport/user-all', array($col => $unionid));
        } else {
            $user_wechat = Dever::load('passport/wechat-getByUnionid', array($col => $unionid));
        }

        if ($user_wechat) {
            # 合并去
            $drop = array();
            $total = count($user_wechat);
            if ($total <= 1) {
                return $cur;
            }

            $new = false;
            foreach ($user_wechat as $k => $v) {
                if (!isset($v['uid'])) {
                    $v['uid'] = $v['id'];
                    $user = $v;
                } else {
                    $user = Dever::db('passport/user')->one($v['uid']);
                    $user['uid'] = $user['id'];
                }

                if (!$new) {
                    if ($user['bind'] == 1 && !strstr($user['username'], '****')) {
                        $new = $user;
                    } elseif ($user['temp'] == 2 && $user['source_type'] == 'applet') {
                        $new = $user;
                    } elseif ($user['avatar']) {
                        $new = $user;
                    } elseif ($user['mobile']) {
                        $new = $user;
                    } else {
                        $drop[$user['uid']] = $user;
                    }
                } else {
                    $drop[$user['uid']] = $user;
                }
            }
            $cur = $new;

            if (Dever::input('test') == 1) {
                print_r($user_wechat);
                print_r($cur);
                print_r($drop);die;
            }

            # 异步处理
            $this->updateCombine($cur, $drop);

            $cur = $new['uid'];
        }

        return $cur;
    }

    private function updateCombine($new, $drop)
    {
        # 队列
        //Dever::queue();
        if (isset($drop[$new['uid']])) {
            unset($drop[$new['uid']]);
        }
        $drops = array();
        if ($drop) {
            foreach ($drop as $k => $v) {
                $drops[] = $k;
                $update = array();
                if (!$new['username'] && $v['username']) {
                    $update['username'] = $v['username'];
                } elseif (strstr($new['username'], '****') && $v['username']) {
                    $update['username'] = $v['username'];
                }

                if (!$new['avatar'] && $v['avatar']) {
                    $update['avatar'] = $v['avatar'];
                }

                if (!$new['mobile'] && $v['mobile']) {
                    $update['mobile'] = $v['mobile'];
                }

                if (!$new['area'] && $v['area']) {
                    $update['area'] = $v['area'];
                }

                if (isset($update) && $update) {
                    $update['where_id'] = $new['uid'];
                    Dever::load('passport/user-update', $update);
                }
            }

            if ($drops) {
                asort($drops);
                $drop_uid = implode(',', $drops);
                //Dever::load('passport/lib/base.handleCombine?new_uid=' . $new['uid'] . '&old_uid=' . $drop_uid);
                Dever::daemon('lib/base.handleCombine?new_uid=' . $new['uid'] . '&old_uid=' . $drop_uid, 'passport');
            }
        }
    }

    public function handleCombine()
    {
        $combine = array();
        $combine['status'] = 1;
        $combine['new_uid'] = Dever::input('new_uid');
        $combine['old_uid'] = Dever::input('old_uid');

        $info = Dever::db('passport/combine')->one($combine);
        if (!$info) {
            Dever::db('passport/combine')->insert($combine);
        }

        Dever::load('passport/user-updates', array('set_state' => 2, 'where_id' => $combine['old_uid']));

        Dever::load('passport/wechat-updates', array('set_uid' => $combine['new_uid'], 'where_uid' => $combine['old_uid']));
    }

    /**
     * 检测用户有效性
     *
     * @return mixed
     */
    public function check($state = true)
    {
        $signature = Dever::input('signature');
        $user = Dever::checkLogin($signature, $state);
        if ($state && !isset($user['uid'])) {
            Dever::alert('user error');
        }
        if (isset($user['uid']) && $user['uid']) {
            return $user['uid'];
        }
        return -1;
    }

    public function getToken($request = array())
    {
        return http_build_query(Dever::token($request));
    }

    public function getUrl($method, $request = array())
    {
        return Dever::proxy($method, $this->getToken($request));
    }

    protected function info()
    {
        $data = $this->save->get(self::NAME);
        return $data;
    }

    public function code($code = false, $image = true)
    {
        if ($code) {
            $save = $this->save->get(self::CODE);
            $state = $code == $save;
            if ($state) {
                //$this->save->un(self::CODE);
            }
            return $state;
        }

        if ($image) {
            $code = new Code();
            $code->create();
            $code = $code->code;
        } else {
            $code = Dever::code();
        }

        $this->save->add(self::CODE, $code, 86400);

        return $code;
    }

    protected function mcode($mobile, $code = false)
    {
        if ($code) {
            $save = $this->save->get(self::MCODE);
            return $mobile . '_' . $code == $save;
        }

        $day = date('Ymd', time());

        # 检测当前手机号最新一次发送时间，不允许一分钟之内发送
        $param['option_day'] = $day;
        $param['option_mobile'] = $mobile;

        # 检测当前手机号今天已经发送多少验证码了
        $info = Dever::load('passport/code-total', $param);

        if ($info >= 1) {
            $check = Dever::load('passport/code-one', $param);

            if ($check) {
                if (time() - $check['cdate'] < Dever::config('base', 'project')->mobileCode['time']) {
                    Dever::alert('请不要在一分钟之内申请多次验证码，请您稍后再试');
                }
            }
        }

        $total = Dever::config('base', 'project')->mobileCode['total'];
        if ($info >= $total) {
            Dever::alert('很抱歉，您已经申请获取验证码超过' . $total . '次，今天您已经无法获取验证码了，请您明天再来');
        }

        $code = new Code();
        $code->createM();

        # 记录当前的验证码
        $insert['add_mobile'] = $mobile;
        $insert['add_day'] = $day;
        $insert['add_code'] = $code->mcode;
        $id = Dever::load('passport/code-insert', $insert);

        # 启动发送
        $this->send($mobile, $insert['add_code'], $id);

        $this->save->add(self::MCODE, $mobile . '_' . $code->mcode, Dever::config('base', 'project')->mobileCode['timeout']);

        return $code->mcode;
    }

    public function send($mobile, $code, $id = false)
    {
        if (Dever::project('sms')) {
            $send['skin'] = 'code';
            $send['mobile'] = $mobile;
            $send['param'] = array
            (
                'code' => $code
            );
            $send['param'] = Dever::json_encode($send['param']);
            return Dever::load('sms/api.send', $send);
        }
        $url = Dever::config('base', 'project')->mobileCode['url'];

        if (!$url) {
            return;
        }

        $content = Dever::config('base', 'project')->mobileCode['body'];

        $content = $this->replace($content, $mobile, $code);

        parse_str($content, $param);

        $type = Dever::config('base', 'project')->mobileCode['method'];
        $json = Dever::config('base', 'project')->mobileCode['json'];
        $header = Dever::config('base', 'project')->mobileCode['header'];

        return Dever::curl($url, $param, $type, $json, $header);
    }

    private function replace($content, $mobile = '', $code = '')
    {
        $skin = Dever::config('base', 'project')->mobileCode['skin'];
        $skin_key = Dever::input('skin', 'code');
        if (isset($skin[$skin_key])) {
            $skin = $skin[$skin_key];
        } else {
            $skin = array_shift($skin);
        }

        $config = array('{code}', '{mobile}', '{sign}', '{skin}', '{param}');
        $replace = array($code, $mobile, Dever::config('base', 'project')->mobileCode['sign'], $skin);
        return str_replace($config, $replace, $content);
    }

    protected function refer($state = false)
    {
        $refer = Dever::input('refer');

        $project = 'main';

        if ($refer) {
            if (!strstr($refer, 'http://')) {
                $refer = Encrypt::decode($refer);
            }
            
            /*
            $url = parse_url(Encrypt::decode($refer));
            $url['path'] = preg_replace('/^\//', '', $url['path']);
            if (!isset($url['query'])) {
                $url['query'] = '';
            }

            if (Uri::$type == '?') {
                $refer = Dever::url(str_replace($url['path'] . Uri::$type, '', $url['query']), $project);
            } else {
                $refer = Dever::url($url['path'] . '?' . $url['query'], $project);
            }
            */
            
        } else {
            $refer = Dever::url('home', $project);
        }

        $param = Dever::input('param');

        if ($param) {
            $refer .= '&' . $param;
        }

        if ($state) {
            return $refer;
        }
        Dever::out($refer);
    }

    protected function save($user)
    {
        if (is_numeric($user)) {
            $user = Dever::load('passport/user-one', $user);
        }

        if ($user && is_array($user)) {
            if (Dever::mobile()) {
                $time = 30;
            } else {
                $time = 7;
            }
            $this->save->add(self::NAME, $user, 3600 * 24 * $time);

            $user['signature'] = Dever::login($user['id']);

            if (Dever::config('base', 'project')->regAction) {
                Dever::load(Dever::config('base', 'project')->regAction, $user);
            }

            return $user;
        }
    }

    public function createRefer()
    {
        return 'refer=' . Encrypt::encode(Dever::url(false, 'main'));
    }

    protected function saveSex($sex)
    {
        if ($sex || $sex == 0) {
            $config_sex = Dever::config('base', 'project')->sex;
            if (isset($config_sex[$sex])) {
                $sex = $config_sex[$sex];
            } else {
                if ($sex == '男') {
                    $sex = 1;
                } elseif ($sex == '女') {
                    $sex = 2;
                } elseif ($sex == '未知') {
                    $sex = 3;
                }
            }
        }
        return $sex;
    }

    protected function saveAvatar($value)
    {
        if (!$value) {
            return '';
        }
        $value = Dever::pic($value);
        $base = Dever::data();
        $date = explode('-', date("Y-m-d"));
        if (is_array($value)) {
            $user = $value[1];
            $value = $value[0];

            if (is_array($value)) {
                $name = md5($value['tmp_name'] . rand(0, 100) . microtime());
                $path = 'avatar/' . $date[0] . '/' . $date[1] . '/' . $date[2] . '/';
                $ext = '.jpg';
                $temp = Dever::path($base, $path . $name . $ext);

                move_uploaded_file($value['tmp_name'], $temp);

                $value = $temp;
            }
        }
        //$result = Dever::$global['host']['img'] . 'chead.jpg';
        if ($value) {
            # 裁图
            $handle = new Img();

            $size = '200_200_2';

            $user = isset($user) && $user ? $user : $this->init();
            if ($user && isset($user['id']) && $user['id']) {
                $name = md5($user['id']);
            } else {
                $name = md5($value . rand(0, 100) . microtime());
            }

            $path = 'avatar/' . $date[0] . '/' . $date[1] . '/' . $date[2] . '/';
            $ext = '.jpg';
            $file = Dever::path($base, $path . $name . $ext);
            $temp = $file . '.temp.jpg';

            //$value = Dever::curl($value);
            //file_put_contents($temp, file_get_contents($value));

            $file = $handle->thumb($value, $size, true, $file);
            if ($file) {
                $result = str_replace('/upload/', '/', Dever::config('host')->uploadRes . $path . $name . $ext);
            } else {
                $result = $value;
            }
        }

        return $result;
    }
}