<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2023/8/21
 * Time: 10:04
 */
namespace app\api\controller;

use app\api\model\Addr;
use app\api\model\FriendCommentModel;
use app\api\model\FriendLikeModel;
use app\api\model\HotcircleModel;
use app\api\model\JoinCircle;
use app\common\controller\Api;
use fast\Tree;
use think\Db;
use \app\api\model\Friend as Friendcircle;


class Friend extends Api{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 创建圈子
     */
    public function createCircle(){
        $title = xss_clean($this->request->post('title',''));//圈子名称
        $content = xss_clean($this->request->post('content',''));//圈子标语
        $addr = xss_clean($this->request->post('addr',''));//圈子地址
        $avatar = $this->request->post('avatar','');//圈子头像
        $surname = $this->request->post('surname','');//圈子姓氏
        $fastim = Db::name('fastim_user')->where(['user_id' =>$this->auth->id])->find();
        $data = [
            'imuser_id' =>$fastim['id'],
            'user_id' =>$this->auth->id,
            'content' =>$content,
            'title' =>$title,
            'content' =>$content,
            'avatar' =>$avatar,
            'surname' =>$surname,
            'create_time' =>time(),
            'addr' =>$addr
        ];
        $res = HotcircleModel::create($data);
        $this->success('创建成功');
    }

    /**
     * 热门圈子列表
     */
    public function getCircleList(){
        $page = $this->request->post('page',1);
        $where = ['status' =>1];
        $list = HotcircleModel::where($where)
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        $this->success('获取成功',['list' =>$list]);
    }

    /**
     * 我的圈子列表
     */
    public function getMyCircles(){
        $page = $this->request->post('page',1);
        $type = $this->request->post('type','');//my_circle:我的圈子
        $where = ['hc.status' =>1,'jc,status' =>1];
        if($type == 'my_circle'){
            $where['jc.user_id'] = $this->auth->id;
        }
        $list = HotcircleModel::alais('hc')
            ->join('join_circle jc','hc.id=jc.hot_circle_id')
            ->where($where)
            ->page($page)
            ->limit($this->pageSize)
            ->field('hc.*,jc.hot_circle_id')
            ->select();
        $this->success('获取成功',['list' =>$list]);
    }

    /**
     * 加入圈子
     */
    public function joinCircle(){
        $hot_circle_id = $this->request->post('hot_circle_id',0);
        if(!$hot_circle_id){
            $this->error('请选择圈子');
        }
        $fastim = Db::name('fastim_user')->where(['user_id' =>$this->auth->id])->find();
        $data = [
            'user_id' =>$this->auth->id,
            'hot_circle_id' =>$hot_circle_id,
            'status' =>1,
            'create_time' =>time(),
            'imuser_id' =>$fastim['id'],
        ];
        $res= JoinCircle::create($data);
        $this->success('获取成功',$res->id);
    }

    /**
     * 发布朋友圈
     * @param content 朋友圈信息
     * @param pics 朋友圈图片集合 多张逗号隔开
     */
    public function addFriendShip(){
        $content = xss_clean($this->request->post('content',''));
        $pics = xss_clean($this->request->post('pics',''));//图片集合(多个逗号隔开)
        $video = xss_clean($this->request->post('video',''));//视频路径
        $province_id = $this->request->post('province_id');
        $addr = Addr::getFind(['ID' =>$province_id],'Name');

        if(!$content){
            $this->error('内容不能为空');
        }
        $fastim = Db::name('fastim_user')->where(['user_id' =>$this->auth->id])->find();
        $joincircle = JoinCircle::where(['user_id' =>$this->auth->id,'status' =>1])->find();
        $data = [
            'imuser_id' =>$fastim['id'],
            'user_id' =>$this->auth->id,
            'content' =>$content,
            'pics' =>$pics,
            'video' =>$video,
            'avatar' =>$fastim['avatar'],
            'nickname' =>$fastim['nickname'],
            'ip' =>$this->request->ip(),
            'create_time' =>time(),
            'addr' =>$addr['Name']
        ];
        if($joincircle){
            $data['hot_circle_id'] = $joincircle['hot_circle_id'];
        }
        $res=Friendcircle::create($data);
        if(!$res->id){
            $this->error('发布失败');
        }
        $this->success('发布成功',['info' =>$res->toArray()]);
    }

    /**
     * 提交评论
     */
    public function submitComment(){
        $circle_id = $this->request->post('circle_id');
        $province_id = $this->request->post('province_id');
        $content = xss_clean($this->request->post('content'));
        $addr = Addr::getFind(['ID' =>$province_id],'Name');
        $fastim = Db::name('fastim_user')->where(['user_id' =>$this->auth->id])->find();
        $data = [
            'circle_id' =>$circle_id,
            'user_id' =>$this->auth->id,
            'imuser_id' =>$fastim['id'],
            'content' =>$content,
            'ip' =>$this->request->ip(),
            'createtime' =>time(),
            'addr' =>$addr['Name']
        ];
        $res=FriendCommentModel::create($data);
        Friendcircle::where(['id' =>$circle_id])->setInc('comment_num',1);
        if(!$res->id){
            $this->error('提交失败');
        }
        $this->success('提交成功',['info' =>$res->toArray()]);
    }

    /**
     * 回复评论
     */
    public function replyComment(){
        $circle_id = $this->request->post('circle_id',0);
        $reply_id = $this->request->post('reply_id');//回复评论id
        $province_id = $this->request->post('province_id');
        $content = xss_clean($this->request->post('content'));
        $addr = Addr::getFind(['ID' =>$province_id],'Name');
        $fastim = Db::name('fastim_user')->where(['user_id' =>$this->auth->id])->find();
        $data = [
            'circle_id' =>$circle_id,
            'reply_user_id' =>$this->auth->id,
            'reply_imuser_id' =>$fastim['id'],
            'content' =>$content,
            'ip' =>$this->request->ip(),
            'reply_id' =>$reply_id,
            'replytime' =>time(),
            'addr' =>$addr['Name']
        ];
        $res=FriendCommentModel::create($data);
        if(!$res->id){
            $this->error('回复失败');
        }
        $this->success('提交成功',['info' =>$res->toArray()]);
    }

    /**
     * 圈子列表
     */
    public function getFriendList(){
        $page = $this->request->post('page',1);
        $circle_id = $this->request->post('hot_circle_id',0);//圈子id
        $where = ['status' =>1];
        if($circle_id){
            $where['hot_circle_id'] = $circle_id;
        }
        $info = HotcircleModel::where(['id' =>$circle_id])->find();
        $list = Friendcircle::where($where)
                ->page($page)
                ->limit($this->pageSize)
                ->order('create_time desc')
                ->select();
        $this->success('获取成功',['info' =>$info,'list' =>$list]);

    }

    /**
     * 圈子列表
     */
    public function getFriendDetail(){
        $circle_id = $this->request->post('circle_id',0);//圈子id
        $where = ['id' =>$circle_id];
        $info = Friendcircle::where($where)->find();
        $this->success('获取成功',['info' =>$info]);

    }

    /**
     * 删除圈子动态
     */
    public function delFriend(){
        $circle_id = $this->request->post('circle_id',0);
        if (empty($circle_id)) {
            $this->error(__('Parameter %s can not be empty', 'comment_id'));
        }
        $where = ['id' =>$circle_id];
        $info = Friendcircle::where($where)->find();
        if(!$info){
            $this->error('此动态不存在');
        }
        if($info['status'] == 2){
            $this->error('此动态已被删除');
        }
        $res = Friendcircle::update(['status' =>2],$where);
        $this->success('删除成功');

    }

    /**
     * 获取评论列表
     */
    public function getCommentList(){
        $circle_id = $this->request->post('circle_id',0);
        $page = $this->request->post('page',1);
        $info = Friendcircle::where(['id' =>$circle_id])->find();
        $list = FriendCommentModel::alias('fc')
            ->join('fastim_user fu','fc.imuser_id = fu.id','left')
            ->where(['fc.circle_id' =>$circle_id,'fc.status'=>1])
//            ->page($page)
//            ->limit($this->pageSize)
            ->field('fc.*,fu.nickname as fu_nickname,fu.avatar as fu_avatar')
            ->select();
       /* if(!$list){
            $this->error('暂无评论');
        }*/
        $total_count = FriendCommentModel::alias('fc')
            ->where(['fc.circle_id' =>$circle_id,'fc.status'=>1])
            ->count();
        Tree::instance()->init($list,'reply_id');
        foreach ($list as $key => $val){
            if(!$val['user_id']){
                unset($list[$key]);
                continue;
            }
           /* if($val['nickname'] == null){
                $info = \app\common\model\User::where(['id' =>$val['user_id']])->find();
                $val['nickname'] = $info['nickname'];
                $val['avatar'] = $info['avatar'];
            }*/
            $list[$key]['sub'] = Tree::instance()->getChildren($val['id']);//递归查询
        }
        sort($list);//排序
        $list = array_slice($list, ($page-1)*$this->pageSize, $this->pageSize);//数组进行分页
        $this->success('获取成功',['info' =>$info,'list' =>$list,'total_count' =>$total_count]);
    }

    /**
     * 删除评论回复
     */
    public function del(){
        $comment_id = $this->request->post('comment_id',0);
        if (empty($comment_id)) {
            $this->error(__('Parameter %s can not be empty', 'comment_id'));
        }
        $where = ['id' =>$comment_id];
        $info = FriendCommentModel::where($where)->find();
        if(!$info){
            $this->error('此评论不存在');
        }
        if($info['status'] == 2){
            $this->error('此评论已被删除');
        }
        Friendcircle::where(['id' =>$info['circle_id']])->setDec('comment_num',1);//评论数减一
        $res = FriendCommentModel::update(['status' =>2],$where);
        $this->success('删除成功');
    }

    /**
     * 点赞
     */
    public function like(){
        $circle_id = $this->request->post('circle_id',0);
        if (empty($circle_id)) {
            $this->error(__('Parameter %s can not be empty', 'comment_id'));
        }
        $where = ['id' =>$circle_id];
        $info = Friendcircle::where($where)->find();
        if(!$info){
            $this->error('此朋友圈不存在');
        }
        $fastim = Db::name('fastim_user')->where(['user_id' =>$this->auth->id])->find();
        $like_where = ['circle_id' =>$circle_id,'user_id'=>$this->auth->id];
        $like= FriendLikeModel::where($like_where)->find();
        if(!$like){
            Friendcircle::where($where)->setInc('like_num',1);
            $data = [
                'circle_id' =>$circle_id,
                'user_id' =>$this->auth->id,
                'imuser_id' =>$fastim['id'],
                'createtime' =>time(),
            ];
            FriendLikeModel::create($data);
            $this->success('点赞成功');
        }
        if($like['status'] == 1){
            Friendcircle::where($where)->setDec('like_num',1);
            FriendLikeModel::update(['status' =>2],$like_where);
        }else{
            Friendcircle::where($where)->setInc('like_num',1);
            FriendLikeModel::update(['status' =>1],$like_where);
        }
        $this->success('操作成功');
    }

    /**
     * 随机推荐好友
     */
    public function getRandomFriends(){
        $where = ['user_id' =>['neq',$this->auth->id]];
        $total = Db::name('fastim_user')->where($where)->count();
        $min = Db::name('fastim_user')->where($where)->min('id');//统计某个字段最小数据
        $num = 30;
        if($total < $num){$num = $min;}
        $i = 1;
        $flag = 0;
        $ary = [];
        while($i<=$num){
            $rundnum = rand($min, $total);//抽取随机数
            if($flag != $rundnum){
                //过滤重复
                if(!in_array($rundnum,$ary)){
                    $ary[] = $rundnum;
                    $flag = $rundnum;
                }else{
                    $i--;
                }
                $i++;
            }
        }
        $list = Db::name('fastim_user')->where($where)->where(['id'=>['in',$ary]])->select();
        $this->success('操作成功',['list' =>$list]);

    }
}