<?php
/**
 * Created by PhpStorm.
 * User: glsy
 * Date: 2018/6/28
 * Time: 下午2:20
 */

namespace App\Resps\Eloquents;

use App\Resps\Interfaces\News as NewsInterface;
use App\Models\News as NewsModel;
use App\Models\NewsSorts as NewsSortsModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class News implements NewsInterface
{

    public function index(array $condition = [])
    {
        $page = is_or($condition, 'page', 1);
        $per_page_num = is_or($condition, 'per_page_num', 20);
        $list = DB::table('news as n')
            ->leftJoin('administrators as a', 'n.creator_id', '=', 'a.id')
            ->leftJoin('administrators as b', 'n.mender_id', '=', 'b.id')
            ->leftJoin('news_sorts as c', 'n.sort_id', '=', 'c.id');
        if ($title = urldecode(is_or($condition, 'title'))) {
            $list = $list->where('n.title', 'like', '%' . $title . '%');
        }
        if ($sort_id = is_or($condition, 'sort_id')) {
            $list = $list->whereIn('n.sort_id', explode(',', $sort_id));
        }
        if ($keyword = urldecode(is_or($condition, 'keyword'))) {
            $list = $list->whereRaw("find_in_set(n.keyword,'" . $keyword . "')");
        }
        if (isset($condition['status']) && $condition['status'] !== null) {
            $list = $list->where('n.status', $condition['status']);
        }
        $list = $list->select(['n.*', 'a.username as creator_name', 'b.username as mender_name', 'c.name as sort_name'])
            ->orderBy('n.id', 'desc')
            ->paginate($per_page_num, ['*'], 'page', $page)
            ->toArray();
        return [
            'total' => $list['total'],
            'per_page' => $list['per_page'],
            'current_page' => $list['current_page'],
            'last_page' => $list['last_page'],
            'list' => get_select($list['data'])
        ];
    }

    public function show($id)
    {
        $detail = NewsModel::leftJoin('news_sorts', 'news.sort_id', '=', 'news_sorts.id')
            ->where('news.id', $id)
            ->select('news.*', 'news_sorts.name as sort_name')
            ->first();
        $detail = $detail ? $detail->toArray() : [];
        !empty($detail) && $detail['sorttree'] = $this->getSortTree($detail['sort_id'], true);
        return $detail;
    }

    public function create(array $params)
    {
        $insertData = [];
        if (!isset($params['title']) || !$insertData['title'] = trim($params['title'])) {
            return ['code' => 201];
        }
        if (!isset($params['sort_id']) || !$insertData['sort_id'] = intval($params['sort_id'])) {
            return ['code' => 202];
        }
        if (!NewsSortsModel::find($insertData['sort_id'])) {
            return ['code' => 410];
        }
        $insertData['keyword'] = is_or($params, 'keyword');
        $insertData['abstract'] = is_or($params, 'abstract');
        $insertData['index_image'] = is_or($params, 'index_image');
        $insertData['content'] = is_or($params, 'content');
        $insertData['creator_id'] = $insertData['mender_id'] = Auth::id();
        try {
            NewsModel::create($insertData);
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 203];
        }
    }

    public function update($id, array $params)
    {
        $updateData = [];
        if (!$id || !NewsModel::find($id)) {
            return ['code' => 204];
        }
        if (!isset($params['title']) || !$updateData['title'] = trim($params['title'])) {
            return ['code' => 201];
        }
        if (!isset($params['sort_id']) || !$updateData['sort_id'] = intval($params['sort_id'])) {
            return ['code' => 202];
        }
        if (!NewsSortsModel::find($updateData['sort_id'])) {
            return ['code' => 410];
        }
        $updateData['keyword'] = is_or($params, 'keyword');
        $updateData['abstract'] = is_or($params, 'abstract');
        $updateData['index_image'] = is_or($params, 'index_image');
        $updateData['content'] = is_or($params, 'content');
        $updateData['mender_id'] = Auth::id();
        try {
            NewsModel::where('id', $id)->update($updateData);
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 206];
        }

    }

    public function changeStatus($id, $status)
    {
        if (!in_array($status, [0, 1, 2, 3])) {
            return ['code' => 208];
        }
        if (!$id || !NewsModel::find($id)) {
            return ['code' => 204];
        }
        try {
            NewsModel::where('id', $id)->update(['status' => $status]);
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 206];
        }

    }

    public function destroy($id)
    {
        if (!$id || !NewsModel::find($id)) {
            return ['code' => 204];
        }
        try {
            NewsModel::destroy($id);
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 205];
        }
    }

    public function getSort($fid = 0)
    {
        $return = NewsSortsModel::where('fid', $fid)->get()->toArray();
        return $return;

    }

    public function addSort(array $params)
    {
        $fid = intval(is_or($params, 'fid'));
        if ($fid > 0 && (!$father = NewsSortsModel::find($fid))) {
            return ['code' => 405];
        }
        if (!$name = trim(is_or($params, 'name'))) {
            return ['code' => 406];
        }
        $inserData = ['fid' => $fid, 'level' => $fid === 0 ? 1 : $father->level + 1, 'name' => $name];
        if (NewsSortsModel::where($inserData)->count()) {
            return ['code' => 407];
        }
        try {
            $res = NewsSortsModel::create($inserData);
            return ['code' => 0, 'data' => ['id' => $res->id, 'level' => $res->level, 'name' => $res->name]];
        } catch (\Exception $e) {
            return ['code' => 408];
        }
    }

    public function updateSort($id, array $params)
    {
        if (!$id = intval($id)) {
            return ['code' => 409];
        }
        if ((!$res = NewsSortsModel::find($id))) {
            return ['code' => 410];
        }
        if (!$name = trim(is_or($params, 'name'))) {
            return ['code' => 406];
        }
        if (NewsSortsModel::where(['fid' => $res->fid, 'name' => $name])->count()) {
            return ['code' => 407];
        }
        try {
            NewsSortsModel::where('id', $id)->update(['name' => $name]);
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 414];
        }
    }

    public function deleteSort($id)
    {
        if (in_array($id, [1, 2, 3, 4, 5, 6])) {
            return ['code' => 421];
        }
        if (!$id) {
            return ['code' => 409];
        }
        if (!$res = NewsSortsModel::find($id)) {
            return ['code' => 410];
        }
        if (NewsSortsModel::where('fid', $id)->count()) {
            return ['code' => 411];
        }
        if (NewsModel::where('sort_id', $id)->count()) {
            return ['code' => 412];
        }
        try {
            NewsSortsModel::destroy($id);
            return ['code' => 0];
        } catch (\Exception $e) {
            return ['code' => 413];
        }
    }

    public function getSortTree($id, $symbol = false)
    {
        if (!$id) {
            return ['code' => 409];
        }
        if (!$res = NewsSortsModel::find($id)) {
            return ['code' => 410];
        }
        $level = $res->level;
        $ids = [$res->id];
        $names = [$res->name];
        $where = ['id' => $res->fid];
        while ($level > 1) {
            $sort = NewsSortsModel::where($where)->first();
            if ($sort) {
                array_unshift($ids, $sort->id);
                array_unshift($names, $sort->name);
                $where = ['id' => $sort->fid];
                $level--;
            }
        }
        $data = ['ids' => $ids, 'names' => $names];
        return $symbol ? $data : ['code' => 0, 'data' => $data];
    }
}