<?php

/**
 * +------------------------------------------------------------
 * | 在线升级客户端 (admin/controller/upgrade/Client.php)
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018年9月27日10:50:17
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018年9月27日10:50:39
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\cim\controller\upgrade;

use app\common\controller\Init;

class Client extends Init
{
    private static $domain = "https://cimxx.com/cim/upgrade.Service/check";

    private static $config = "";

    public function initialize()
    {
        parent::initialize();
        self::$config = config('')['cim'];
    }

    /**
     * 检测版本更新
     */
    public function check()
    {
        $cache_key = 'check_upgrade';
        $cache_data = cache($cache_key);
        if (!empty($cache_data)) if (time() - $cache_data['time'] > 7200) $cache_data = '';
        if (empty($cache_data)) {
            $data = json_decode(http(self::$domain, 10, 'POST', [
                'version' => self::$config['version'],
                'host' => input('server.HTTP_HOST')
            ]), 1);
            $cache_data = ['time' => time(), 'data' => $data];
            cache($cache_key, $cache_data);
        }
        $cache_data = $cache_data['data'];
        if (!empty($cache_data)) {
            if (count(explode('.', $cache_data['version'])) != 3) return json(['code' => 1, 'errcode' => '21003', 'msg' => '已是最新版本']);
            if (count(explode('.', self::$config['version'])) != 3 || ((float)$cache_data['version'] < (float)self::$config['version']) || ((float)$cache_data['version'] == (float)self::$config['version'] && explode('.', $cache_data['version'])[2] < explode('.', self::$config['version'])[2])) return json(['code' => 1, 'errcode' => '210002', 'msg' => '版本号格式错误,最新版本号为【' . $cache_data['version'] . '】,请检查您的配置文件']);
            if (self::$config['version'] == $cache_data['version']) return json(['code' => 1, 'errcode' => '21003', 'msg' => '已是最新版本']);
            if ((string)((float)$cache_data['version'] - (float)self::$config['version']) > (float)0.1) return json(['code' => 1, 'errcode' => '21004', 'url' => '升级包地址', 'msg' => '当前版本过低，请先升级到版本' . ((float)self::$config['version'] + 0.1)]);
            return json(['code' => 1, 'errcode' => '0', 'msg' => '有新版本可以升级', 'data' => $cache_data]);
        } else {
            return json(['code' => 1, 'errcode' => '21003', 'msg' => '已是最新版本']);
        }
    }

}