<?php

namespace Api\PhpServices\Towerpro;


use Api\PhpUtils\Http\Request;

class Towerpro
{
    /**
     * 申请一个key，可以通过本接口申请，也可以在平台网页中申请
     * 一般本接口只需本地调用一次，不会在业务接口中使用
     * http://ydwiki.yidian-inc.com/pages/viewpage.action?pageId=53663475
     *
     * @param $appid string 应用id
     * @param $env int 0:测试环境，1:线上环境
     * @param $version string 版本号
     * @param $os int 操作系统,0:ios,1:安卓,2 所有
     * @param $creator string 创建者
     * @param $keyTag string key 的关键词标志
     * @param null $note string 备注说明
     */
    public static function create($appid, int $env, $version, int $os, $creator, $keyTag, $note=null){
        $url =  config("interface","towerpro.create_key");
        $data = [
            "appid"     => $appid,
            "env"       => $env,
            "version"   => $version,
            "os"        => $os,
            "creator"   => $creator,
            "keyTag"    => $keyTag,
            "note"      => $note,
        ];

        $res = (new Request())->post($url, $data,5000, 'json');
        return $res;
    }

    /**
     * 使用key配置数据
     * @param $key
     * @param array $data
     */
    public static function set($key, array $data){
        $url =  config("interface","towerpro.set");
        $data = [
            "uniqueKey" => $key,
            "data"      => $data
        ];
        $res = (new Request())->post($url, $data,5000, 'json');
        return $res;
    }

    /**
     * 使用key获取配置数据
     * @param $key
     * @param int $type 0 所有信息（key信息+data）; 1 仅 data ; 2 仅 key 信息
     * @return array|bool|mixed
     */
    public static function get($key, int $type = 0){
        $url =  config("interface","towerpro.get");
        $data = [
            "uniqueKey" => $key
        ];
        $res = (new Request())->get($url, $data,5,["Content-Type"=>"application/json"]);

        if($res["code"] != 0){
            return $res;
        }

        $all = [
            "keyInfo"   => null,
            'data'      => null
        ];
        if($res && isset($res["result"]) && $res["result"]){
            if (isset($res["result"]["data"])){
                $all["data"] = $res["result"]["data"];
                unset($res["result"]["data"]);
            }
            $all["keyInfo"] = $res["result"];
        }

        switch ($type){
            case 1:
                $data = $all['data'];
                break;
            case 3:
                $data = $all['keyInfo'];
                break;
            default:
                $data = $all;
                break;
        }

        return ["code"=>0, "data"=>$data];
    }
}