<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-06-10
 * Time: 18:12
 */

namespace App\Repositories;

use App\Models\Category;
use App\Models\CategoryTopic;
use App\Models\MemberFollowTopic;
use App\Models\Topic;
use Dingo\Api\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class TopicRepository
{
    public function __construct(Topic $topic, CategoryTopic $categoryTopic, MemberFollowTopic $memberFollowTopic)
    {
        $this->topic = $topic;
        $this->categoryTopic = $categoryTopic;
        $this->memberFollowTopic = $memberFollowTopic;
    }

    //列表
    public function index($request)
    {
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
        $where = [];
        if (isset($request['name'])) {
            $where[] = ['name', 'like', "%{$request['name']}%"];
        }
        if (isset($request['topic_status'])) {
            if ($request['topic_status'] == 'is_suggest') {
                $where[] = ['is_suggest', 1];
            }
            if ($request['topic_status'] == 'is_hot') {
                $where[] = ['is_hot', 1];
            }
            if ($request['topic_status'] == 'is_open') {
                $where[] = ['is_open', 1];
            }
            if ($request['topic_status'] == 'is_close') {
                $where[] = ['is_open', 0];
            }
        }

        return $this->topic
            ->where($where)
            ->orderBy('is_hot', 'desc')
            ->orderBy('is_suggest', 'desc')
            ->orderBy('is_open', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($perPage);
    }

    //新增
    public function create($request)
    {
        $topic = $this->topic->where(['name' => $request['name']])->first();
        if ($topic) {
            return Response::create([
                'message' => '该话题已存在',
                'status_code' => 500
            ]);
        }

        $data = [
            'name' => $request['name'],
            'img' => $request['img'],
            'desc' => $request['desc'],
            'circle_id' => $request['desc'] ?? 0,
        ];
        if (!empty($request['base_count'])) {
            $data['base_count'] = $request['base_count'];
        }
        if (isset($request['category_ids'])) {
            $category_ids = explode(',', $request['category_ids']);
        }
        DB::beginTransaction();
        try {
            $topicInfo = $this->topic->create($data);
            if ($topicInfo) {
                if ($category_ids) {
                    $category_topic_data = [];
                    foreach ($category_ids as $value) {
                        $category_topic_data[] = [
                            'category_id' => $value,
                            'topic_id' => $topicInfo->id,
                        ];
                    }
                    $this->categoryTopic->insert($category_topic_data);
                }
            }
            DB::commit();
            Redis::zadd('topic.name', $topicInfo->id, $topicInfo->name);
            return Response::create();
        } catch (QueryException $exception) {
            DB::rollBack();
            Log::debug('新增话题:' . $exception->getMessage());
            return Response::create([
                'message' => '新增话题,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    public function edit($request)
    {
        $topic = $this->topic->where(['id' => $request['id']])->first();
        if (!$topic) {
            return Response::create([
                'message' => '该话题不存在',
                'status_code' => 500
            ]);
        }
        $oldName = $topic->name;
        $_topic = $this->topic->where(['name' => $request['name']])->where('id', '<>', $topic->id)->first();
        if ($_topic) {
            return Response::create([
                'message' => '该话题已存在',
                'status_code' => 500
            ]);
        }

        $topic->name = $request['name'];
        $topic->img = $request['img'];
        $topic->desc = $request['desc'];
        $topic->circle_id = $request['circle_id'] ?? 0;
        if (!empty($request['base_count'])) {
            $topic->base_count = $request['base_count'];
        }
        $category_ids = [];
        if (!empty($request['category_ids'])) {
            $category_ids = explode(',', $request['category_ids']);
        }
        DB::beginTransaction();
        try {
            //保存
            $topicInfo = $topic->save();
            //删除原来关联关系
            $this->categoryTopic->where(['topic_id' => $topic->id])->delete();
            if ($topicInfo) {
                if ($category_ids) {
                    $category_topic_data = [];
                    foreach ($category_ids as $value) {
                        $category_topic_data[] = [
                            'category_id' => $value,
                            'topic_id' => $topic->id,
                        ];
                    }
                    $this->categoryTopic->insert($category_topic_data);
                }
            }
            DB::commit();
            if ($oldName != $topic->name) {
                Redis::zrem('topic.name', $oldName);
                Redis::zadd('topic.name', $topic->id, $topic->name);
            }
            return Response::create();
        } catch (QueryException $exception) {
            DB::rollBack();
            Log::debug('编辑话题:' . $exception->getMessage());
            return Response::create([
                'message' => '编辑话题,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    //修改
    public function update($request)
    {
        $topic = $this->topic->where('id', $request['id'])->first();
        if (!$topic) {
            return Response::create([
                'message' => '该话题不存在',
                'status_code' => 500
            ]);
        }
        if (isset($request['is_open']) && $request['is_open'] !== null) {
            $topic->is_open = $request['is_open'];
        }
        if (!empty($request['type'])) {
            if ($topic->is_open == 0) {
                return Response::create([
                    'message' => '该话题未开启',
                    'status_code' => 500
                ]);
            }
            if (isset($request['type']) && $request['type'] == 1) {
                $topic->is_suggest = $request['status'];
            }
            if (isset($request['type']) && $request['type'] == 2) {
                $topic->is_hot = $request['status'];
            }
        }

        $res = $topic->save();
        if ($res) {
            return Response::create();
        }
    }

    //详情
    public function view($request)
    {
        return $this->topic->where('id', $request['id'])->first();
    }

    //获取多个话题
    public function getTopics($ids = [])
    {
        return $this->topic->whereIn('id', $ids)->select('id', 'name')->get();
    }

    public function getMemberTopics($uid)
    {
        return $this->memberFollowTopic
            ->leftJoin('topic', 'topic.id', '=', 'member_follow_topic.topic_id')
            ->where('member_follow_topic.uid', $uid)
            ->select('topic.id', 'topic.name')
            ->get();
    }

    /**
     * 重置话题redis
     */
    public function resetRedis()
    {
        $TopicName = $this->topic->pluck('id', 'name')->toArray();

        $res = Redis::zadd('topic.name', $TopicName);
        if ($res) {
            return Response::create([
                'message' => '重置话题成功',
                'status_code' => 500
            ]);
        } else {
            return Response::create([
                'message' => '重置话题失败',
                'status_code' => 500
            ]);
        }
    }
}