<?php

namespace App\Http\Controllers\Admin;

use App\Models\Tag;
use App\Models\Setting;
use Illuminate\Http\Request;
use App\Http\Requests\TagRequest;
use App\Models\TagDescription as Description;
use Illuminate\Support\Facades\DB;

class TagController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = $request->except('page') + ['field' => 'tag_id'];

        $query = Tag::select('taggable_tags.*')
            ->leftJoin('taggable_taggables', 'taggable_tags.tag_id', '=', 'taggable_taggables.tag_id')
            ->selectRaw('COUNT(' . DB::getTablePrefix() . 'taggable_taggables' . '.tag_id) as taggable_count')
            ->groupBy('taggable_tags.tag_id');

        if (isset($where['order']) && $where['order']) {
            $query = $query->orderBy('taggable_count', $where['order'] == '1' ? 'desc' : 'asc');
        } else {
            $query = $query->latest();
        }

        if (isset($where['flag'])) {
            if ($where['flag'] == 1) {
                $query = $query->has('taggables');
            }

            if ($where['flag'] == 2) {
                $query = $query->has('taggables', '=', 0);
            }
        }

        if (isset($where['name']) && $where['name']) {
            $ids   = Description::where('name', 'like', "%{$where['name']}%")->where('lang', config('setting.lang'))->get()->pluck($where['field'])->toArray();
            $query = $query->whereIn('taggable_tags.tag_id', $ids);
        }

        $tags = $query->paginate($where['perPage'] ?? 20);
        $tags->map(function ($tag) {
            if ($tag->description) {
                $tag->name = $tag->description->name;
            }

            return $tag;
        });

        return view('admin.tag.tag', compact('tags', 'where'));
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getKeyword()
    {
        // 关键词
        $metaKeyword = Setting::where('lang', config('setting.lang'))->where('name', 'meta_keywords')->value('value');
        $keywords = $metaKeyword ? explode(',' ,$metaKeyword) : [];

        // tags
        $tags = Description::get();
        $hostTags = Tag::getPieceTags(array_merge($keywords, $tags->where('lang', config('setting.lang'))->pluck('name')->toArray()));
        $words = array_unique(array_merge($hostTags, $tags->pluck('name')->toArray()));
        $config = Setting::where('lang', 'single')->lists('value', 'name')->toArray();

        return view('admin.tag.tag_keyword', compact('words', 'config'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.tag.tag_create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param TagRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(TagRequest $request)
    {
        if (config('managerLang') != config('setting.lang')) {
            return back()->withInput()->with('error', '请在主语言添加内容！');
        }

        $tags = $request->input('description.' . config('setting.lang') . '.name');
        $tags = explode(',', trim(str_replace(["，",",","、","|","。","\r\n","\n"], ',', $tags)));
        $tags = array_unique(array_filter($tags));

        $result = true;
        if (!empty($tags)) {
            foreach ($tags as $tag) {
                if (Tag::where('name', $tag)->first()) {
                    continue;
                }

                $result = Tag::create(['name' => $tag]);

                if ($result) {
                    Tag::attachSlug($result, $tag, 'tag_id');
                    Description::attachDescription([config('setting.lang') => ['name' => $tag]], $result->tag_id, 'tag_id', true);
                    event(new \App\Events\TranslateEvent('tag', $result->tag_id));
                }
            }
        }

        if ($result) {
            return redirect('admin/tag')->with('success', '标签添加成功');
        }

        return back()->withInput()->with('error', '标签添加失败');
    }

    //异步更新Tags
    public function ajaxUpdate(Request $request)
    {
        $request->merge(['name' => trim($request->input('description.' . config('setting.lang') . '.name'))]);
        $data = $request->all();
        $data['description'][config('setting.lang')]['name'] = trim($data['description'][config('setting.lang')]['name']);

        if (Tag::where('name', $data['name'])->first()) {
            return response()->json(['status' => 'error', 'message' => '标签已经存在，请不要重复添加！']);
        }

        $result = Tag::create($data);

        if ($result) {
            Tag::attachSlug($result, $data['description'][config('setting.lang')]['name'], 'tag_id');
            Description::attachDescription($data['description'], $result->tag_id, 'tag_id', true);
            return response()->json(['status' => 'sucess', 'name' => $data['description'][config('setting.lang')]['name']]);
        }

        return response()->json(['status' => 'error', 'message' => '添加标签失败，请重新添加！']);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tag = Tag::where('tag_id', $id)->first();
        $descriptions = Description::where('tag_id', '=', $id)->get()->groupBy('lang');

        if (!isset($descriptions[config('managerLang')])) $descriptions[config('managerLang')] = $descriptions[config('setting.lang')];
        return view('admin.tag.tag_edit', compact('tag', 'descriptions'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param TagRequest $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(TagRequest $request, $id)
    {
        $request->merge(['name' => trim($request->input('description.' . config('managerLang') . '.name'))]);

        if (Tag::where('name', trim($request->input('name')))->where('tag_id', '<>', $id)->first()) {
            return back()->withInput()->with('error', '标签已经存在，请不要重复添加！');
        }

        $data = $request->all();
        $data['description'][config('managerLang')]['name'] = trim($data['description'][config('managerLang')]['name']);

        $result = Tag::find($id)->update($data);

        if ($result) {
            Description::attachDescription($data['description'], $id, 'tag_id');
            event(new \App\Events\TranslateEvent('tag', $id, true));
            return redirect('admin/tag')->with('success', '标签修改成功');
        }

        return back()->withInput()->with('error', '标签修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids    = array_str($id);
        $result =  Tag::whereIn('tag_id', $ids)->delete();

        if ($result) {
            Description::whereIn('tag_id', $ids)->delete();
            return response()->json(['status' => 'sucess']);
        }

        return response()->json(['status' => 'error']);
    }
}
