<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/5
 * Time: 16:03
 */

namespace App\Repositories\Circle;

use App\Models\InterestCircle;
use App\Models\InterestCircleArticle;
use App\Models\Post;
use Illuminate\Database\QueryException;
use Dingo\Api\Http\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CircleArticleRepository
{

    public function __construct(InterestCircleArticle $interestCircleArticle, Post $post, InterestCircle $interestCircle)
    {
        $this->interestCircleArticle = $interestCircleArticle;
        $this->post = $post;
        $this->interestCircle = $interestCircle;
    }

    /**
     * 内容列表
     */
    public function lists($request)
    {
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
        $where = [];

        if (isset($request['uid'])) {
            $where[] = ['uid', $request['uid']];
        }

        if (isset($request['circle_id'])) {
            $where[] = ['interest_circle_articles.circle_id', $request['circle_id']];
        }

        $articleModel = $this->post;

        return $articleModel
            ->join('post_data', 'post_data.post_id', '=', 'post.id')
            ->join('interest_circle_articles', 'interest_circle_articles.post_id', '=', 'post.id')
            ->select('post.*', 'interest_circle_articles.is_recommend', 'interest_circle_articles.circle_id')
            ->with('data')
            ->where($where)
            ->where(function ($query) use ($request) {
                if (isset($request['content'])) {
                    $query->where('title', 'like', "%{$request['content']}%")
                        ->orWhere('content', 'like', "%{$request['content']}%");
                }
            })
            ->where(function ($query) use ($request) {
                if (isset($request['created_at'])) {
                    $time = explode('_', $request['created_at']);
                    $query->whereBetween('post.created_at', $time);
                }
            })
            ->orderBy('is_recommend', 'desc')
            ->paginate($perPage);
    }

    /**
     * 推荐精品文章
     */
    public function articleRecommend($request)
    {
        $article = $this->interestCircleArticle
            ->where('post_id', $request['post_id'])
            ->where('circle_id', $request['circle_id'])
            ->first();
        if (!$article) {
            return Response::create([
                'message' => '获取精品文章信息失败',
                'status_code' => 500
            ]);
        }

        if ($article->is_recommend == 1) {
            $article->is_recommend = 0;
        } else {
            $article->is_recommend = 1;
        }

        DB::beginTransaction();
        try {
            $article->save();
            DB::commit();
            return Response::create();

        } catch (QueryException $exception) {
            DB::rollBack();
            Log::debug('推荐精品文章:' . $request['post_id'] . '-' . $request['circle_id'] . $exception->getMessage());
            return Response::create([
                'message' => '操作失败,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    /**
     * 精品文章从当前圈子移出
     */
    public function articleRemove($request)
    {
        $article = $this->interestCircleArticle
            ->where('post_id', $request['post_id'])
            ->where('circle_id', $request['circle_id'])
            ->first();
        if (!$article) {
            return Response::create([
                'message' => '获取精品文章信息失败',
                'status_code' => 500
            ]);
        }

        DB::beginTransaction();
        try {
            $article->delete();
            $this->interestCircle->where('id',$request['circle_id'])->decrement('article_count');
            $isRef = $this->interestCircleArticle->where('post_id', $request['post_id'])->exists();
            if (!$isRef) {
                //移出后需要检测该帖子在其他圈子有没有设为精品,如没有,则删除该帖子的精品标识
                $this->post->where('id', $request['post_id'])->update(['is_fine' => 0]);
                Redis::HSET('post_info_' . $request['post_id'],'is_fine',0);
            }
            $key = 'circle_articles_' . $request['circle_id'];
            Redis::zrem($key, $request['post_id']);
            DB::commit();
            return Response::create();

        } catch (QueryException $exception) {
            DB::rollBack();
            Log::debug('移出精品文章:' . $request['post_id'] . '-' . $request['circle_id'] . $exception->getMessage());
            return Response::create([
                'message' => '操作失败,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    /**
     * 新增精品文章
     */
    public function articleInsert($request)
    {
        $article = $this->interestCircleArticle
            ->where('post_id', $request['post_id'])
            ->where('circle_id', $request['circle_id'])
            ->first();
        if ($article) {
            return Response::create([
                'message' => '该文章已存在当前圈子',
                'status_code' => 500
            ]);
        }

        DB::beginTransaction();
        try {
            $this->interestCircleArticle->insert(['post_id' => $request['post_id'], 'circle_id' => $request['circle_id']]);
            $this->interestCircle->where('id',$request['circle_id'])->increment('article_count');
            //修改帖子为精品贴
            $this->post->where('id', $request['post_id'])->update(['is_fine' => 1]);
            Redis::HSET('post_info_' . $request['post_id'],'is_fine',1);
            //将精品文章存入该圈子的有序集合中
            $key = 'circle_articles_' . $request['circle_id'];
            Redis::zadd($key, time(), $request['post_id']);
            DB::commit();
            return Response::create();

        } catch (QueryException $exception) {
            DB::rollBack();
            Log::debug('设置精品文章:' . $request['post_id'] . '-' . $request['circle_id'] . $exception->getMessage());
            return Response::create([
                'message' => '操作失败,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    /**
     * 当前圈子精品文章帖子来源列表
     * @param $request
     * @return mixed
     */
    public function postList($request)
    {
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
        $where = [];
        if (isset($request['type'])) {
            $where[] = ['type', $request['type']];
        }

        if (isset($request['uid'])) {
            $where[] = ['uid', $request['uid']];
        }

        if (isset($request['circle_id'])) {
            $circleInfo = $this->interestCircle->where('id', $request['circle_id'])->first();
            if ($circleInfo && $circleInfo->limit_article_ids) {
                $request['topic_ids'] = "{$circleInfo->limit_article_ids}";
            }
        }

        $sort = 'post.id';
        if (isset($request['sort']) && in_array($request['sort'], ['praise_count', 'share_count', 'pv', 'comment_count', 'create_bean'])) {
            $sort = $request['sort'];
        }
        $post = $this->post;

        return $post
            ->where($where)
            ->where(function ($query) use ($request) {
                if (isset($request['keyword'])) {
                    $query->where('uid', '=', $request['keyword'])
                        ->orWhere('username', 'like', "%{$request['keyword']}%")
                        ->orWhere('mobile', 'like', "%{$request['keyword']}%");
                }
            })
            ->where(function ($query) use ($request) {
                if (isset($request['content'])) {
                    $query->where('title', 'like', "%{$request['content']}%")
                        ->orWhere('content', 'like', "%{$request['content']}%");
                }
            })
            ->where(function ($query) use ($request) {
                if (isset($request['created_at'])) {
                    $time = explode('_', $request['created_at']);
                    $query->whereBetween('post.created_at', $time);
                }
            })
            ->where(function ($query) use ($request) {
                if (isset($request['category_ids']) || isset($request['topic_ids'])) {
                    $ids = [];
                    if (isset($request['category_ids'])) {
                        $categoryIds = explode(',', $request['category_ids']);
                        $ids = $this->categoryTopic->whereIn('category_id', $categoryIds)->pluck('topic_id')->toArray();
                    }
                    if (isset($request['topic_ids'])) {
                        $ids = array_merge($ids, explode(',', $request['topic_ids']));
                    }
                    foreach ($ids as $key => $id) {
                        if ($key == 0) {
                            $query = $query->whereRaw('FIND_IN_SET(' . $id . ',topic_ids)');
                        } else {
                            $query = $query->orWhereRaw('FIND_IN_SET(' . $id . ',topic_ids)');
                        }
                    }
                }
            })
            ->orderBy($sort, 'desc')
            ->paginate($perPage);
    }
}