<?php namespace Wechat\Lib;
use Dever;
class Info
{
    # 获取accesstoken
    public function getAccessToken()
    {
        $call = function() {
            $param['component_verify_ticket'] = $this->get('component_verify_ticket');
            $data = Dever::load('account', 'api')->run('wechat_open', 'token', $param);
            if (isset($data['component_access_token'])) {
                return array($data['component_access_token'], $data['expires_in']);
            }
            Dever::error('系统错误');
        };
        return $this->get('component_access_token', $call);
    }

    # 获取预授权码
    public function getPreAuthCode()
    {
        $call = function() {
            $param['component_access_token'] = $this->getAccessToken();
            $data = Dever::load('account', 'api')->run('wechat_open', 'pre_auth_code', $param);
            if (isset($data['pre_auth_code'])) {
                return array($data['pre_auth_code'], $data['expires_in']);
            }
            Dever::error('系统错误');
        };
        return $this->get('pre_auth_code', $call);
    }

    # 获取某个有效的信息数据
    public function get($key, $call = false)
    {
        $info = Dever::db('info', 'wechat')->find(array('key' => $key));
        if ($info) {
            if (time() >= $info['expires']) {
                # 需要重新获取最新的信息
                if ($call) {
                    list($value, $expires) = $call();
                    return $this->up($info['id'], $key, $value, $expires);
                }
            }
            return $info['value'];
        }
        if ($call) {
            list($value, $expires) = $call();
            return $this->up(false, $key, $value, $expires);
        }
    }

    # 更新某个信息数据
    public function up($id, $key, $value, $expires, $place_id = -1)
    {
        $data['key'] = $key;
        $data['place_id'] = $place_id;
        if (!$id) {
            $info = Dever::db('info', 'wechat')->find($data);
            if ($info) {
                $id = $info['id'];
            }
        }
        $data['value'] = $value;
        $data['expires'] = $expires - 60 + time();
        if ($id) {
            Dever::db('info', 'wechat')->update($id, $data);
        } else {
            Dever::db('info', 'wechat')->insert($data);
        }
        return $value;
    }
}