<?php

namespace app\ucentre\admin;
use app\admin\AdminBaseController;
use app\ucentre\model\Client as byClient;
use wendasns\facade\Wendid;
use wendasns\Wend;

class Client extends AdminBaseController
{
	
    public function index()
    {
		return view();
    }

    public function list()
    {
    	$limit = input('limit',20,'intval');

    	$dm = byClient::order('id', 'desc')->paginate($limit);

    	$data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }

    //添加
    public function post()
    {
    	$id = input('post.id',0,'intval');
		$name = input('post.name','');
		$url = input('post.url','');
		$secretkey = input('post.secretkey','');
		$apifile = input('post.apifile','uclient.php');
		
		if($id){
			$dm = byClient::find($id);
			if(!$dm){
				error('客户端不存在');
			}
			$dm->name = $name;
			$dm->url = $url;
			$dm->secretkey = $secretkey;
			$dm->apifile = $apifile;
			$dm->save();
			success('操作完成');
		}
		$dm = byClient::where('name',$name)->find();
		
		if($dm){
			error('已有相同客户端');
		}

    	try {
            validate([
            	'name' => 'require',
            	'url' => 'require|url',
            	'secretkey' => 'require',
            ])->check([
            	'name' => $name,
            	'url' => $url,
            	'secretkey' => $secretkey,
            ]);
        } catch (\think\exception\ValidateException $e) {
            error($e->getError());
        }
        
		
		$client = byClient::create([
			'name' =>  $name,
			'url' =>  $url,
			'secretkey' =>  md5(time()),
			'apifile' =>  $apifile
		]);
		if(isset($client->id)){
			success('操作完成');
		}
		error('操作失败');
    }
    
    //删除
    public function remove()
    {
		$id = input('post.id',[],'');
		if(is_array($id)){
    		byClient::destroy($id);
		}
		success('操作完成');
    }
    
    //测试
    public function test()
    {
    	$id = input('post.id',0,'intval');
    	$dm = byClient::find($id);
    	if(!$dm){
    		error('客户端不存在');
    	}
    	
    	try {
            $result = Wendid::open('test',['testdata' => 1]);
            if(!isset($result->testdata)){
	    		error('失败');
	    	}
        } catch (\think\Exception $e) {
            error($e->getMessage());
        }
		success('操作完成');
    }
}