<?php
namespace Passport\Src\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 = 'dever_passport_v2';

    const CODE = 'dever_code';

    const MCODE = 'dever_mcode';

    protected $save;

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

    /**
     * 检测用户有效性
     *
     * @return mixed
     */
    public function check($state = true)
    {
        $signature = Dever::input('signature');
        $user = Dever::loginResult($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;
    }

    protected function code($code = false)
    {
        if ($code) {
            $save = $this->save->get(self::CODE);
            return $code == $save;
        }

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

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

    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) {
            $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;
    }
}
