<?php

// +----------------------------------------------------------------------
// | Created by PhpStorm.
// +----------------------------------------------------------------------
// | user : JYF
// +----------------------------------------------------------------------
// | blog :
// +----------------------------------------------------------------------
// | email: 1749934563@qq.com
// +----------------------------------------------------------------------
// | Date : 2021/2/19
// +----------------------------------------------------------------------


namespace App\Services;


use App\Constants\FriendCircleConst;
use App\Exceptions\FriendCircleException;
use App\Http\Params\FriendCircleParam;
use App\Http\Params\FriendCircleCommentParam;
use App\Http\Params\FriendCircleLikeRecordParam;
use App\Models\FriendCircle;
use App\Models\FriendCircleComment;
use App\Models\FriendCircleLikeRecord;

class FriendCircleService
{
    /**
     * 圈子动态列表
     * @param int $uid
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     * @author JYF 2021/2/19 15:48
     */
    public function circleLists(int $uid)
    {

        //当前用户加的好友id
        $userFriendList = UserFriendService::getFriendAllByUid($uid);
        $userFriendId = array_column($userFriendList,'friend_user_id');
        array_push($userFriendId,$uid);//自己发布的也可以看
        //当前用户被加的好友权限信息
        $friendUserList = UserFriendService::getFriendAllByFriendUserId($uid);
        $wh_group_id_arr = array_column($friendUserList,'wh_group_id','user_id');

        $lists = FriendCircle::query()
            ->with(['users'=>function($query){
                $query->select('id','nick_name_id','avatar');
            }])
            ->where('status',FriendCircleConst::STATUS_PUB)
            ->whereIn('user_id',$userFriendId)//好友发布的动态
            ->orderByDesc('id')
            ->paginate(request('perPage',10));

        $nick_name_id_arr = [];
        foreach ($lists->toArray()['data'] as $k => $item){
            if(isset($item['users']['id'])) {
                $nick_name_id_arr[] = $item['users']['id'];
            }
        }

        //处理用户昵称
        /** @var  $userService \App\Services\UserService */
        $userService = resolve('\App\Services\UserService');
        $list_nick_name = $userService->selectUserNickNameById($nick_name_id_arr);

        foreach ($lists as $k => &$val){
            $val['users']['nick_name'] = $list_nick_name[$val['users']['nick_name_id'] ?? 0] ?? '';
            $val['img_url_list'] = explode(',',$val['img_url']);

            //判断查看权限
            $user_id = $val['user_id'];
            $wh_group_id = $wh_group_id_arr[$user_id] ?? 0;
            $look_type_arr = explode(',',$val['look_type']);
            $is_look = false;//是否有权限查看,自己发布的有权限查看
            if(in_array($wh_group_id,$look_type_arr) || $user_id == $uid){
                $is_look = true;
            }
            $val['is_look'] = $is_look;

        }
        return $lists;
    }

    /**
     * 圈子动态发布
     * @param FriendCircleParam $circleParam
     * @return mixed
     * @author JYF 2021/2/19 16:49
     */
    public function circlePub(FriendCircleParam $circleParam)
    {
        $data = [
            'user_id'=>$circleParam->user_id,
            'content'=>$circleParam->content,
            'img_url'=>$circleParam->img_url ? implode(',',$circleParam->img_url) : '',
            'look_type'=>$circleParam->look_type ? implode(',',$circleParam->look_type) : 0 ,
            'status'=>FriendCircleConst::STATUS_PUB,//预留状态
        ];

        return FriendCircle::create($data);
    }

    /**
     * 圈子动态点赞操作
     * @param FriendCircleLikeRecordParam $recordParam
     * @return bool
     * @throws FriendCircleException
     * @author JYF 2021/2/19 17:38
     */
    public function circleLike(FriendCircleLikeRecordParam $recordParam)
    {
        //TODO 点赞有并发,在用redis处理

        if(empty($recordParam->circle_id)){
            throw new FriendCircleException('参数错误~');
        }

        //动态是否存在
        $circleInfo = $this->getCircleInfo($recordParam->circle_id);
        if(empty($circleInfo)){
            throw new FriendCircleException('动态不存在~');
        }
        //有无权限给此动态点赞，加了好友才可以点赞
        $isUserFriend = $this->isUserFriend($recordParam->input_uid,$recordParam->circle_id);
        if(false === $isUserFriend){
            throw new FriendCircleException('不是好友不能点赞哦~');
        }
        //是否已经点赞
        $isLikeCircle = $this->isLikeCircle($recordParam->input_uid,$recordParam->circle_id);
        if(!empty($isLikeCircle)){
            throw new FriendCircleException('您已经点过赞了哦~');
        }
        //记录点赞
        $data = [
            'circle_id'=>$recordParam->circle_id,
            'input_uid'=>$recordParam->input_uid,
        ];
        FriendCircleLikeRecord::create($data);
        //总点赞量+1
        FriendCircle::query()->where('id',$recordParam->circle_id)->increment('like_num',1);
        return true;
    }

    /**
     * 点赞记录
     * @param int $uid
     * @param int $circle_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @author JYF 2021/2/19 17:33
     */
    public function isLikeCircle(int $uid,int $circle_id)
    {
        $where = [];
        $where[] = ['circle_id','=',$circle_id];
        $where[] = ['input_uid','=',$uid];
        return FriendCircleLikeRecord::query()->where($where)->first();
    }

    /**
     * @param int $circle_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @author JYF 2021/2/19 17:33
     */
    public function getCircleInfo(int $circle_id)
    {
        $where = [];
        $where[] = ['id','=',$circle_id];
        return FriendCircle::query()->where($where)->first();
    }

    /**
     * 简单验证下是否是好友关系
     * @param int $uid
     * @param int $circle_id
     * @return bool
     * @author JYF 2021/2/19 17:24
     */
    public function isUserFriend(int $uid,int $circle_id)
    {
        $circleInfo = $this->getCircleInfo($circle_id);
        if(empty($circleInfo)){
            return false;
        }
        $circle_uid = $circleInfo->user_id;
        //获取是否是好友关系
        $userFriendInfo = UserFriendService::getFriendRelation($uid,$circle_uid);
        if(empty($userFriendInfo)){
            return false;
        }
        return true;
    }

    /**
     * 发布评论
     * @param FriendCircleCommentParam $circleCommentParam
     * @return mixed
     * @throws FriendCircleException
     * @author JYF 2021/2/19 17:53
     */
    public function circlePubComment(FriendCircleCommentParam $circleCommentParam)
    {
        if(empty($circleCommentParam->circle_id)){
            throw new FriendCircleException('参数错误~');
        }

        if(empty($circleCommentParam->content)){
            throw new FriendCircleException('请输入内容~');
        }
        $circleInfo = $this->getCircleInfo($circleCommentParam->circle_id);
        if(empty($circleInfo)){
            throw new FriendCircleException('此动态不存在~');
        }

        $isUserFriend = $this->isUserFriend($circleCommentParam->input_uid,$circleCommentParam->circle_id);
        if(false === $isUserFriend){
            throw new FriendCircleException('不是好友不能评论哦~');
        }

        //记录评论
        $data = [
            'circle_id'=>$circleCommentParam->circle_id,
            'input_uid'=>$circleCommentParam->input_uid,
            'content'=>$circleCommentParam->content,
        ];
        return FriendCircleComment::create($data);
    }

    /**
     * @param FriendCircleParam $circleParam
     * @return int
     * @throws FriendCircleException
     * @author JYF 2021/2/19 18:07
     */
    public function delCircle(FriendCircleParam $circleParam)
    {
        if(empty($circleParam->id)){
            throw new FriendCircleException('参数错误~');
        }
        return FriendCircle::destroy($circleParam->id);
    }

    /**
     * @param FriendCircleCommentParam $circleCommentParam
     * @return int
     * @throws FriendCircleException
     * @author JYF 2021/2/19 18:08
     */
    public function delCircleComment(FriendCircleCommentParam $circleCommentParam)
    {
        if(empty($circleCommentParam->id)){
            throw new FriendCircleException('参数错误~');
        }
        return FriendCircleComment::destroy($circleCommentParam->id);
    }

    /**
     * @param int $circle_id
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     * @author JYF 2021/2/19 18:27
     */
    public function circleCommentList(int $circle_id)
    {
        $lists = FriendCircleComment::query()
            ->with(['users'=>function($query){
                $query->select('id','nick_name_id','avatar');
            }])
            ->where('circle_id',$circle_id)
            ->orderByDesc('id')
            ->paginate(request('perPage', 10));

        $nick_name_id_arr = [];
        foreach ($lists->toArray()['data'] as $k => $item){
            if(isset($item['users']['id'])) {
                $nick_name_id_arr[] = $item['users']['id'];
            }
        }

        //处理用户昵称
        /** @var  $userService \App\Services\UserService */
        $userService = resolve('\App\Services\UserService');
        $list_nick_name = $userService->selectUserNickNameById($nick_name_id_arr);

        foreach ($lists as $k => &$val){
            $val['users']['nick_name'] = $list_nick_name[$val['users']['nick_name_id'] ?? 0] ?? '';
        }

        return $lists;
    }
}
