<?php

namespace app\lib;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/20
 * Time: 13:33
 */

//服务端下发数据包标准格式;

class DataPack
{
    private static $Datas = [];
    private static $Instance = null ;

    public function getInstance($cache = true)
    {
        if ($cache && self::$Instance) {
            return self::$Instance;
        }
        self::$Instance = new self();
        return self::$Instance;
    }

    public static function Create($array)
    {
        self::$Datas = $array;
    }

    public static function toJson($array = [])
    {
        if (!empty($array)) {
            self::Create($array);
        }
        $ret = [
            'id' => isset(self::$Datas['id']) ? self::$Datas['id'] : self::UUID(),
            'fr' => isset(self::$Datas['from']) ? self::$Datas['from'] : 0,
            'to' => isset(self::$Datas['to']) ? self::$Datas['to'] : 0,
            'ct' => time(),
            'mt' => isset(self::$Datas['mtype']) ? self::$Datas['mtype'] : '',
            'st' => isset(self::$Datas['stype']) ? self::$Datas['stype'] : '',
            'cf' => isset(self::$Datas['confirm']) ? self::$Datas['confirm'] : 0,
            'data' => isset(self::$Datas['data']) ? self::$Datas['data'] : 0,
        ];
        return json_encode($ret, JSON_UNESCAPED_UNICODE);
    }

    public static function setKey($key, $val)
    {
        self::$Datas[$key] = $val;
    }

    public static function getKey($key, $default = '')
    {
        if (isset(self::$Datas[$key])) {
            return self::$Datas[$key];
        }
        return $default;
    }

    public static function reset()
    {
        self::$Datas = [];
    }

    public static function UUID()
    {
        return md5(microtime() . uniqid('pack_') . rand(1, 999999));
    }

}