<?php

namespace App\Http\Controllers\Diary;

use App\Http\Controllers\Core\Auth;
use App\Http\Resources\Diary\DiaryCollection;
use App\Http\Resources\Diary\DiaryResource;
use App\Models\Diary\DiaryModel;
use App\Models\Diary\ThumbModel;
use App\Models\User\UserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;

class DiaryController extends Controller
{

    private $admins = [10001, 10002, 10007, 11111, 62726, 91031, 94302, 98047, 103143, 762663, 795723, 10771042];

    /**
     * 获取用户信息
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws JWTException
     */
    public function me()
    {
        $uid = Auth::auth();
        $user = UserModel::select('nickname', 'headimgurl', 'sex')->findOrFail($uid);
        $user->is_admin = in_array($uid, $this->admins);
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $user
        ]);
    }


    /**
     * 日记列表
     * @param  Request  $request
     * @return DiaryCollection
     */
    public function index(Request $request)
    {
        try {
            $uid = Auth::auth();
        } catch (JWTException $e) {
            $uid = 0;
        }

        $diaries = DiaryModel::where(function ($query) use ($uid) {
            // 显示私有或我的
            return $query->where('private', 0)
                ->orWhere('uid', $uid);
        })->when($request->get('topping'), function ($query) {
            // 置顶的
            return $query->where('topped_at', '>', time() - 24 * 3600);
        })->when($request->get('selecting'), function ($query) {
            // 精选的
            return $query->where('selected_at', '>', time() - 24 * 3600);
        })->whereNull('violationed_at')
            ->OrderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 20));

        foreach ($diaries as $diary) {
            $diary->user;
            $diary->self_thumb = ThumbModel::where('uid', $uid)->where('diary_id', $diary->id)->count() ? true : false;
            $diary->self = ($uid == $diary->uid) ? true : false;
            $diary->created_time_ago = $diary->created_at->diffForHumans();
        }
        return new DiaryCollection($diaries);
    }


    /**
     * 日记信息
     * @param  Request  $request
     * @param $id
     * @return DiaryResource
     */
    public function show(Request $request, $id)
    {
        try {
            $uid = Auth::auth();
        } catch (JWTException $e) {
            $uid = 0;
        }
        $diary = DiaryModel::findOrFail($id);
        $diary->user;
        $diary->self_thumb = ThumbModel::where('uid', $uid)->where('diary_id', $diary->id)->count() ? true : false;
        $diary->self = ($uid == $diary->uid) ? true : false;
        $diary->created_time_ago = $diary->created_at->diffForHumans();
        return new DiaryResource($diary);
    }


    /**
     * 创建日记
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'images' => '',
            'content' => 'required',
            'private' => 'integer',
        ]);

        $uid = Auth::auth();
        if (
            $last_at = DiaryModel::where('uid', $uid)->where('created_at', '>', time() - 60)->orderBy(
                'created_at',
                'desc'
            )->value('created_at')
        ) {
            return response([
                'code' => 429001,
                'message' => "操作发送频繁，请一分钟后再发"
            ]);
        }

        if (strstr($request->images, ",")) {
            list(, $image) = explode(',', $request->images);
        } else {
            $image = $request->images;
        }
        $filename = storage_path() . '/app/' . uniqid() . '.png';
        \File::put($filename, base64_decode($image));
        $response = \Curl::to("http://www.koudaidaxue.com/Tools/Upload/upFile")
            ->withData([
                'file' => "@{$filename}"
            ])
            ->withFile('file', $filename)
            ->asJsonResponse()
            ->post();
        \File::delete($filename);
        if ($response->errcode == 0) {
            $image = $response->errmsg->cdn_site . $response->errmsg->file;
        } else {
            $image = $request->input('images', '');
        }
        $data = ($request->only('content', 'mood', 'private', 'uid'));
        $data = array_merge($data, ['uid' => $uid, 'images' => $image]);
        DiaryModel::create($data);
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    /**
     * 删除日记
     * @param  Request  $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws JWTException
     */
    public function destroy(Request $request, $id)
    {
        $diary = DiaryModel::find($id);
        $uid = Auth::auth();
        if ($uid == $diary->uid) {
            $diary->delete();
            return response([
                'code' => 200,
                'message' => 'OK'
            ]);
        }

        // 管理员可删除
        if (in_array($uid, $this->admins)) {
            $diary->violationed_at = time();
            $diary->save();
            return response([
                'code' => 200,
                'message' => 'OK'
            ]);
        }

        return response([
            'code' => 403001,
            'message' => '非作者不可删除'
        ]);
    }


    /**
     * 精选
     * @param  Request  $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws JWTException
     */
    public function setSelecting(Request $request, $id)
    {
        $uid = Auth::auth();
        $diary = DiaryModel::findOrFail($id);
        if (!in_array($uid, $this->admins)) {
            return response([
                'code' => 403500,
                'message' => '无权限操作'
            ]);
        }
        if ($diary->selected_at > 0) {
            $diary->selected_at = 0;
        } else {
            $diary->selected_at = time();
        }
        $diary->save();
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    /**
     * 置顶
     * @param  Request  $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws JWTException
     */
    public function setTopping(Request $request, $id)
    {
        $uid = Auth::auth();
        $diary = DiaryModel::findOrFail($id);
        if (!in_array($uid, $this->admins)) {
            return response([
                'code' => 403500,
                'message' => '无权限操作'
            ]);
        }
        if ($diary->topped_at > 0) {
            $diary->topped_at = 0;
        } else {
            $diary->topped_at = time();
        }
        $diary->save();
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    /**
     * 点赞or取消赞
     *
     * @param  Request  $request
     * @param $diary_id 日记ID
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function thumbing(Request $request, $id)
    {
        $uid = Auth::auth();

        \DB::beginTransaction();
        try {
            $diary = DiaryModel::findOrFail($id);
            $thumb = ThumbModel::where(['uid' => $uid, 'diary_id' => $diary->id])->first();
            if ($thumb) {
                $thumb->delete();
                $diary->decrement('thumb');
            } else {
                $diary->increment('thumb');
                ThumbModel::create([
                    'uid' => $uid,
                    'diary_id' => $diary->id
                ]);
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
        }
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }
}
