<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
use App\Resps\Interfaces\News as NewsInterface;

class NewsController extends Controller
{
    protected $news;

    public function __construct(NewsInterface $news)
    {
        $this->news = $news;
    }

    public function index()
    {
        $fillables = [
            'page',
            'title',
            'keyword',
            'sort_id',
            'is_ajax'
        ];
        $params = request()->only($fillables);
        return $params['is_ajax'] ? $this->news->index($params) : view('admin.news.news');
    }

    public function show($id)
    {
        if ($id && !empty($detail = $this->news->show($id))) {
            return Response::success($detail);
        }
        return Response::error(['code' => 207]);
    }

    public function form($id = '')
    {
        return view('admin.news.news_form', $id ? ['id' => $id] : []);
    }

    public function store()
    {
        $fillables = [
            'title',
            'keyword',
            'abstract',
            'sort_id',
            'index_image',
            'content',
        ];
        $params = request()->only($fillables);
        $res = $this->news->create($params);
        return Response::auto($res);
    }

    public function update($id)
    {
        $fillables = [
            'title',
            'keyword',
            'abstract',
            'sort_id',
            'index_image',
            'content',
        ];
        $params = request()->only($fillables);
        $res = $this->news->update($id, $params);
        return Response::auto($res);
    }

    public function changeStatus($id){
        $res = $this->news->changeStatus($id, request()->get('status'));
        return Response::auto($res);
    }

    public function destroy($id)
    {
        if (!$id) {
            return Response::auto(['code' => 204]);
        }
        $res = $this->news->destroy($id);
        return Response::auto($res);
    }

    public function setting()
    {
        return request()->get('is_ajax') ? '' : view('admin.news.news_setting');
    }

    public function getSort($fid)
    {
        return $this->news->getSort($fid);
    }

    public function updateSort($id)
    {
        return $this->news->updateSort($id, request()->only(['name']));
    }

    public function addSort()
    {
        return Response::auto($this->news->addSort(request()->only(['fid', 'name'])));
    }

    public function deleteSort($id)
    {
        return Response::auto($this->news->deleteSort($id));
    }

    public function getSortTree($id)
    {
        return Response::auto($this->news->getSortTree($id));
    }
}
