<?php

namespace App\JsonRpc;

use App\Model\Link;
use Hyperf\RpcServer\Annotation\RpcService;
use App\Tools\Result;


#[RpcService(name: "LinkService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class LinkService implements LinkServiceInterface
{
    /**
     * @param array $data
     * @return array
     */
    public function getLinkList(array $data): array
    {
        $where = [];
        if(isset($data['keyWord'])){
            $where = [
                ['link.title','like','%'.$data['keyWord'].'%']
            ];
        }
        $result  = [];
        if(isset($data['pageSize'])){
            $rep = Link::where($where)
                ->leftJoin("website","website.id","link.website_id")
                ->select("link.*","website.website_name")
                ->limit($data['pageSize'])->offset(($data['page']-1)*$data['pageSize'])->orderBy("sort","asc")->get();
            $count = Link::where($where)->count();
            $result = [
                'rows'=>$rep,
                'count'=>$count
            ];
        }else{
            $result = Link::where($data)->orderBy("sort","asc")->get();
        }
        return $result?Result::success($result):Result::error("没有查到数据");
    }

    /**
     * @param array $data
     * @return array
     */
    public function createLink(array $data): array
    {


        $result = Link::insertGetId($data);
        if (empty($result)) {
            return Result::error("创建失败", 0);
        } else {
            return Result::success(["id" => $result]);
        }
    }

    /**
     * @param array $data
     * @return array
     */
    public function updateLink(array $data): array
    {
        //website_name` = '三农市场网', `status_name` =
        unset($data['website_name']);
        unset($data['status_name']);
        $result = Link::where('id', $data['id'])->update($data);
        if (empty($result)) {
            return Result::error("更新失败", 0);
        } else {
            return Result::success();
        }
    }

    /**
     * @param int $id
     * @return array
     */
    public function delLink(int $id): array
    {
        $result = Link::where('id', $id)->delete();
        if (empty($result)) {
            return Result::error("删除失败", 0);
        } else {
            return Result::success();
        }
    }


}