<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-06-15
 * Time: 15:01
 */

namespace App\Repositories;

use App\Models\MemberFollowTopic;
use Illuminate\Database\QueryException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class MemberFollowTopicRepository {
    public function __construct(MemberFollowTopic $memberFollowTopic,CategoryRepository $categoryRepository) {
        $this->memberFollowTopic = $memberFollowTopic;
        $this->categoryRepository = $categoryRepository;
    }
    //关注话题
    public function setMemberFollowTopic($topic_group_ids){

        $data = $this->categoryRepository->getTopics($topic_group_ids);
        //获取uid
        $token =  JWTAuth::decode(JWTAuth::getToken());
        if($data){
            $category_topic_data = [];
            $date = Carbon::now()->toDateTimeString();
            foreach($data as $value){
                $category_topic_data[] = [
                    'uid' => $token['user']->uid,
                    'topic_id' => $value['id'],
                    'created_at' => $date,
                    'updated_at' => $date,
                ];
            }
            DB::beginTransaction();
            try{
                $res = $this->memberFollowTopic->insert($category_topic_data);
                $topic = $this->updataMemberFollowSuggestTopic();
                DB::commit();
                if($res){
                    //更改关注状态

                    //用户话题集合
                    $key = 'topic.user_uid'.$token['user']->uid;
                    foreach($data as $value){
                        if(!Redis::zscore($key, $value['id'])){
                            Redis::zincrby($key, 0, $value['id']);
                        }
                    }
                    return jsonSuccess();
                }else{
                    return jsonError('关注失败');
                }
            }catch (QueryException $exception){
                DB::rollBack();
                Log::debug('新增话题:'.$exception->getMessage());
                return jsonError('关注失败');
            }

        }
    }
    //修改关注状态
    public function updataMemberFollowSuggestTopic(){
        try {
            $sign = generateSign([], config('customer.app_secret'));
            $url = config("customer.app_service_url").'/user/v2/member/updateFollowSuggestTopic';
            //$url = 'http://localhost:8080/v2/member/updateFollowSuggestTopic';
            $array = [
                'json' => ['sign' => $sign], 'query' => [], 'http_errors' => false,'headers'=>['Authorization'=>"Bearer ".JWTAuth::getToken()]
            ];
            return http($url,$array,'put');
        } catch (\Exception $e) {
            return [];
        }
    }
    //关注单个话题
    public function follow($topic_id){
        $token =  JWTAuth::decode(JWTAuth::getToken());
        $info = $this->memberFollowTopic->where(['topic_id'=>$topic_id,'uid'=>$token['user']->uid])->first();
        if($info){
            return jsonError('您已关注该话题');
        }
        $data = ['uid'=>$token['user']->uid,'topic_id'=>$topic_id];
        $res = $this->memberFollowTopic->create($data);
        if($res){
            $key = 'topic.user_uid'.$token['user']->uid;
            if(!Redis::zscore($key, $topic_id)){
                Redis::zincrby($key, 0, $topic_id);
            }
            return jsonSuccess();
        }else{
            return jsonError('关注失败');
        }
    }
    //取消关注话题
    public function cancel($topic_id){
        $token =  JWTAuth::decode(JWTAuth::getToken());
        $info = $this->memberFollowTopic->where(['topic_id'=>$topic_id,'uid'=>$token['user']->uid])->first();
        if(!$info){
            return jsonError('您没有关注该话题');
        }
        $res = $this->memberFollowTopic->where('id',$info->id)->delete();
        if($res){
            return jsonSuccess();
        }else{
            return jsonError('取关失败');
        }
    }
    public function list($request){
        $token =  JWTAuth::decode(JWTAuth::getToken());
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
        $where[] = ['uid',$token['user']->uid];
        if(isset($request['name'])){
            $where[] = ['topic.name', 'like', "%{$request['name']}%"];
        }
        return $this->memberFollowTopic
                    ->leftJoin('topic', 'member_follow_topic.topic_id', '=', 'topic.id')
                    ->where($where)
                    ->select('member_follow_topic.id','uid','topic_id','topic.name as topic_name','topic.is_suggest')
                    ->paginate($perPage);
    }
    //获取用户关注话题
    public function getMemberTopic($uid){
        return $this->memberFollowTopic
            ->leftJoin('topic', 'member_follow_topic.topic_id', '=', 'topic.id')
            ->where(['member_follow_topic.uid'=>$uid])
            //->select('member_follow_topic.id','uid','topic_id','topic.name as topic_name','topic.is_suggest')
            ->select('topic.name as topic_name')
            ->take(3)
            ->get();
    }
}