<?php
namespace App\JsonRpc;

use App\Model\OldModel\Article as OldArticle;
use App\Model\Article;
use App\Model\Web;
use Hyperf\DbConnection\Db;
use Hyperf\RpcServer\Annotation\RpcService;
use App\Tools\Result;


#[RpcService(name: "CollectorService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class CollectorService implements CollectorServiceInterface
{
    /**
     * 添加网站
     * @param array $data
     * @return array|mixed
     */
    public function addWeb(array $data): array
    {
        $where = [
            'name' => $data['name']
        ];
        $isweb = Web::where($where)->first();
        if(empty($isweb)){
            date_default_timezone_set('Asia/Shanghai');
            $time = time();
            $catetime = date('Y-m-d H:i:s', $time);
            $data['created_at'] = $catetime;
            $web = Web::insert($data);
            
        }else{
            return Result::error('此网站已存在，不可重复添加！');
        }
        if(empty($web)){
            return Result::error('添加失败');
        }
        return Result::success('添加成功');
    }
    /**
     * 获取并搜索网站
     * @param array $data
     * @return array|mixed
     */
    public function getWeb(array $data): array
    {
        
        if(isset($data['keyWord'])){
            $where = [
                ['name','like','%'.$data['keyWord'].'%']
            ];
            $webss = Web::where($where)->first();
            if(empty($webss)){
                return Result::error('未查找到相关网站！');
            }
        }else{
            $web = Web::get();
        }
        
        if(empty($web)){
            return Result::error('您还未添加网站，请先去添加！');
            
        }
        
        return Result::success($web);
    }
    /**
     * 修改网站
     * @param array $data
     * @return array|mixed
     */
    public function upWeb(array $data): array
    {
        $web = Web::where('id',$data['id'])->first();
        if(empty($web)){
            return Result::error('请输入正确的网站id！');
            
        }else{
            $id = Web::where('id',$data['id'])->update($data);
            if(empty($id)){
                return Result::error('无法修改！');
            }
        }
        return Result::success($id);
    }
    /**
     * 删除网站
     * @param array $data
     * @return array|mixed
     */
    public function delWeb(array $data): array
    {
        $web = Web::where('id',$data['id'])->first();
        if(empty($web)){
            return Result::error('请输入正确的网站id！');
            
        }else{
            $id = Web::where('id',$data['id'])->delete();
            if(empty($id)){
                return Result::error('无法删除！');
            }
        }
        return Result::success($id);
    }
}