<?php namespace Wechat\Lib;
use Dever;
class Auth
{
    # 获取数据
    public function get($place_id)
    {
        $info = Dever::db('auth', 'wechat')->find(array('place_id' => $place_id));
        if ($info) {
            if (time() >= $info['expires']) {
                # 需要重新获取最新的信息
                $param['component_access_token'] = Dever::load('info', 'wechat')->getAccessToken();
                $param['authorizer_appid'] = $info['appid'];
                $param['authorizer_refresh_token'] = $info['refresh_token'];
                $data = Dever::load('account', 'api')->run($this->account, 'auth_refresh_token', $param);
                if (isset($data['authorizer_access_token'])) {
                    return $this->up($info['id'], $info['place_id'], $data['authorizer_access_token'], $data['authorizer_refresh_token'], $data['expires_in']);
                }
                Dever::error('系统错误');
            }
            return $info['access_token'];
        }
    }

    # 更新数据
    public function up($id, $place_id, $access_token, $refresh_token, $expires, $appid = false, $func_info = false)
    {
        if (!$id) {
            $data['place_id'] = $place_id;
            $info = Dever::db('auth', 'wechat')->find($data);
            if ($info) {
                $id = $info['id'];
            }
        }
        $data['access_token'] = $access_token;
        $data['refresh_token'] = $refresh_token;
        $data['expires'] = $expires - 60 + time();
        if ($appid) {
            $data['appid'] = $appid;
        }
        if ($func_info) {
            $data['func_info'] = Dever::json_encode($func_info);
        }
        if ($id) {
            Dever::db('auth', 'wechat')->update($id, $data);
        } else {
            Dever::db('auth', 'wechat')->insert($data);
        }
        return $access_token;
    }
}