<?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);
        $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 ($keyword = urldecode(is_or($condition, 'keyword'))) {
            $list = $list->whereRaw("find_in_set(n.keyword,'" . $keyword . "')");
        }
        $list = $list->select(['n.*', 'a.username as creator_name', 'b.username as mender_name', 'c.name as sort_name'])
            ->orderBy('n.id', 'desc')
            ->paginate(20, ['*'], '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);
            $this->publish($id, false);
            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);
            $this->publish($id, false);
            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() > 1) {
            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 (!$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];
    }

    public function publish($id, $model = true)
    {
        if ($model) {
            $type = request()->get('type');
            NewsModel::where('id', $id)->update(['status' => $type ? 1 : 2]);
        }

        $data = get_select(DB::table('net')->find(1));
        $data['lianjie_name'] = explode('@', $data['lianjie_name']);
        $data['lianjie'] = explode('@', $data['lianjie']);

        $news = get_select(NewsModel::where('status', 2)->get());
        array_map('unlink', glob(public_path('detail/*')));
        foreach ($news as $key => $vo) {
            @file_put_contents(public_path('detail/' . $vo['id'] . '.html'), view('admin.news.news_detail', ['net' => $data,'detail' => $vo])->render());
        }
        $ds = glob(public_path('detail/*'));
        usort($ds, function ($a, $b) {
            preg_match('/(\d+)\.html/', $a, $m);
            preg_match('/(\d+)\.html/', $b, $n);
            return $m[1] > $n[1] ? -1 : 1;
        });
        $res = [];
        while (!empty($s = array_splice($ds, 0, 10))) {
            $res[] = $s;
        }
        $newsData = ['list' => $res, 'titles' => array_column($news, 'title', 'id'), 'times' => array_column($news, 'created_at', 'id')];
        view()->share(['data' => array_merge($data, $newsData)]);
        $fillables = [];
        foreach (glob(base_path('resources/views/web/*')) as $vo) {
            $e = explode('.',basename($vo));
            $name = $e[0];
            $fillables[$name . '.html'] = 'web.' . $name;
        }
        foreach ($fillables as $key => $vo) {
            @file_put_contents(public_path($key), view($vo)->render());
        }
        return ['code' => 0];
    }
}