<?php
namespace App\JsonRpc;

use App\Model\Article;
use App\Model\ArticleData;
use App\Model\Category;
use Hyperf\DbConnection\Db;
use Hyperf\RpcServer\Annotation\RpcService;
use App\Tools\Result;

#[RpcService(name: "NewsService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class NewsService implements NewsServiceInterface
{

    /**
     * @param array $data
     * @return array
     */
    public function getCategoryList(array $data): array
    {
        $where = [
            ['name','like','%'.$data['keyWord'].'%'],
            ['website_id','=',$data['website_id']],
            ['pid','=',$data['pid']??0]
        ];
        $rep = Category::where($where)->limit($data['pageSize'])->orderBy("sort","asc")->offset(($data['page']-1)*$data['pageSize'])->get();
        $count =  Category::where($where)->count();
        $data = [
            'rows'=>$rep->toArray(),
            'count'=>$count
        ];
        if(empty($rep->toArray())){
            return Result::error("没有栏目数据");
        }
        return Result::success($data);
    }

    /**
     * @param array $data
     * @return array
     */
    public function categoryList(array $data): array
    {
       $result =  Category::where($data)->get();
        if(empty($result)){
            return Result::error("没有栏目数据");
        }
        return Result::success($result);
    }
    /**
     * @param array $data
     * @return array
     */
    public function addCategory(array $data): array
    {
        $id = Category::insertGetId($data);
        if(empty($id)){
            return Result::error("添加失败");
        }
        return Result::success(['id'=>$id]);
    }

    /**
     * @param array $data
     * @return array
     */
    public function delCategory(array $data): array
    {
        $categoryList = Category::where(['pid'=>$data['id']])->get();
        var_dump("分类列表：",$data,$categoryList);
        if($categoryList->toArray()){
            return Result::error("分类下面有子分类不能删除");
        }
        $articleList = Article::where(['catid'=>$data['id']])->get();
        var_dump("文章列表：",$articleList);
        if($articleList->toArray()){
            return Result::error("分类下面有资讯不能删除");
        }
        $result = Category::where($data)->delete();
        if(!$result){
            return Result::error("删除失败");
        }
        return Result::success($result);
    }

    /**
     * @param array $data
     * @return array
     */
    public function updateCategory(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        $result = Category::where($where)->update($data);
        if($result){
            return Result::success($result);
        }else{
            return Result::error("更新失败");
        }
    }

    /**
     * @param array $data
     * @return array
     */
    public function getArticleList(array $data): array
    {
        var_dump("资讯：",$data);
        $where= [];
        if(isset($data['keyWord'])){
            $where[] =   ['article.title','like','%'.$data['keyWord'].'%'];
            $where[] =   ['article.status','!=','5'];
        }
        $rep = Article::where($where)
            ->leftJoin('category','article.catid','category.id')
            ->leftJoin("article_data","article.id","article_data.article_id")
            ->select("article.*","category.name","article_data.content")
            ->orderBy("article.id","desc")
            ->limit($data['pageSize'])
            ->offset(($data['page']-1)*$data['pageSize'])->get();
        $count =  Article::where($where)->count();
        $data = [
            'rows'=>$rep->toArray(),
            'count'=>$count
        ];
        if(empty($rep)){
            return Result::error("没有信息数据");
        }
        return Result::success($data);
    }

    /**
     * @param array $data
     * @return array
     */
    public function addArticle(array $data): array
    {
        Db::beginTransaction();
        try{

        $data['cat_arr_id'] = isset($data['cat_arr_id'])?json_encode($data['cat_arr_id']):'';
        $data['tag'] = isset($data['tag'])?json_encode($data['tag']):'';
            $articleData = $data;
            unset($articleData['content']);
            $id = Article::insertGetId($articleData);
            $articleDataContent = [
                'article_id'=>$id,
                'content'=>$data['content']
            ];
            ArticleData::insertGetId($articleDataContent);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            var_dump($ex->getMessage());
            return Result::error("创建失败",0);
        }

        return Result::success(['id'=>$id]);
    }

    /**
     * @param array $data
     * @return array
     */
    public function delArticle(array $data): array
    {
        $result = Article::where($data)->update(['status'=>5]);
        if(!$result){
            return Result::error("删除失败");
        }
        return Result::success($result);
    }

    /**
     * @param array $data
     * @return array
     */
    public function updateArticle(array $data): array
    {
        Db::beginTransaction();
        try{
            $data['cat_arr_id'] = isset($data['cat_arr_id'])?json_encode($data['cat_arr_id']):'';
            $data['tag'] = isset($data['tag'])?json_encode($data['tag']):'';
            $articleData = $data;
            unset($articleData['content']);
            unset($articleData['status_name']);
            unset($articleData['name']);
            unset($articleData['content']);
            unset($articleData['pid_arr']);
            unset($articleData['pid']);
            $id = Article::where(['id'=>$data['id']])->update($articleData);
            $articleDataContent = [
                'content'=>$data['content']
            ];
            ArticleData::where(['article_id'=>$data['id']])->update($articleDataContent);
        } catch(\Throwable $ex){
            Db::rollBack();
            var_dump($ex->getMessage());
            return Result::error("更新失败",0);
        }
        return Result::success([]);

    }

    /**
     * @param array $data
     * @return array
     */
    public function getArticleInfo(array $data): array
    {
        $where = [
            'article.id'=>$data['id']
        ];
        $result = Article::where($where)->leftJoin("article_data","article.id","article_data.article_id")->first();
        if($result){
            return Result::success($result->toArray());
        }else{
            return Result::error("查询失败",0);
        }
    }
}