<?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 = [];
        if(isset($data['name']) && $data['name']){
            array_push($where, ['category.name','like','%'.$data['name'].'%']);
        }
        if(isset($data['department_id']) && $data['department_id']){
            array_push($where, ['category.department_id','=',$data['department_id']]);
        }
        if(isset($data['city_id']) && $data['city_id']){
            array_push($where, ['category.city_id','=',$data['city_id']]);
        }
        $rep = Category::where($where)
            ->leftJoin('district','category.city_id','district.id')
            ->leftJoin('department','category.department_id','department.id')
            ->select("category.*","district.name as city_name","department.name as department_name")
            ->limit($data['pageSize'])->orderBy("category.sort","desc")->orderByDesc('category.updated_at')->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
    {
        $where[] = [
            'pid','=',$data['pid']
        ];
        if(isset($data['name'])){
            array_push($where, ['category.name','like','%'.$data['name'].'%']);
        }
        var_dump($where);
       $result =  Category::where($where)->select('category.*','category.id as category_id')->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 getCategoryInfo(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        $result = Category::where($where)->first();
        if($result){
            return Result::success($result);
        }else{
            return Result::error("更新失败");
        }
    }
    /**
     * @param array $data
     * @return array
     */
    public function getArticleList(array $data): array
    {
        $where= [];

        if(isset($data['title'])  && $data['title']){
            array_push($where,['article.title','like','%'.$data['title'].'%']);
        }
        if(isset($data['category_name'])  && $data['category_name']){
            array_push($where,['category.name','like','%'.$data['category_name'].'%']);
        }
        if(isset($data['author'])  && $data['author']){
             array_push($where,['article.author','=',$data['author']]);
        }
        if(isset($data['islink'])  && $data['islink']!==""){
            array_push($where,['article.islink','=',$data['islink']]);
        }
        if(isset($data['status']) && $data['status']!==""){
            array_push($where,['article.status','=',$data['status']]);
        }
        
        $rep = Article::where($where)
            ->whereNotIn('article.status',[404])
            ->leftJoin('category','article.catid','category.id')
            ->select("article.*","category.name as category_name")
            ->orderBy("article.id","desc")
            ->limit($data['pageSize'])
            ->offset(($data['page']-1)*$data['pageSize'])->get();
        $count =  Article::where($where)->whereNotIn('article.status',[404])
            ->leftJoin('category','article.catid','category.id')->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{

            $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'=>404]);
        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 upArticleStatus(array $data):array
    {
       $result =  Article::where(['id'=>$data['id']])->update($data);
        if($result){
            return Result::success();
        }else{
            return Result::error("更新状态失败",0);
        }
    }
    /**
     * @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);
        }
    }
}