<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Keyworld;
/**
 * 圈子动态
 */
class Topicdongtai extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    //发布动态
    public function adddongtai(){
        $content = input('content','', 'trim');
        $images = input('images','', 'trim');
        $topic_id = input('topic_id', 0, 'intval'); //热门话题id
        $type = input('type', 0, 'intval'); //类型:0=文字,1=图片,2=视频
        if(!$content && !$images){
            $this->error(__('Invalid parameters'));
        }

        if ($topic_id) {
            $topic_info = Db::name('topic_hub')->where(['id' => $topic_id])->find();
            if (!$topic_info) {
                $this->error('话题已过时,请重新选择');
            }
            if ($topic_info['status'] != 1) {
                $this->error('话题已过时,请重新选择');
            }
        }
        if (!in_array($type, [0, 1, 2])) {
            $this->error('您的网络开小差啦~');
        }

        //关键字替换
        $content = Keyworld::sensitive($content);


        $data = [
            'topic_id' => $topic_id,
            'user_id' => $this->auth->id,
            'content' => $content,
            'images' => $images,
            'createtime' => time(),
            'updatetime' => time(),
            'type' => $type
        ];


        Db::startTrans();
        $id = Db::name('topic_dongtai')->insertGetId($data);
        if (!$id) {
            Db::rollback();
            $this->error('您的网络开小差啦~');
        }
        //圈子新增一个贴
        if ($topic_id) {
            $rs = Db::name('topic_hub')->where('id', $topic_id)->setInc('t_number');
            if (!$rs) {
                Db::rollback();
                $this->error('您的网络开小差啦~');
            }
        }

        Db::commit();

        $this->success('发布成功',$id);
    }

    //动态列表
    public function dongtailist() {
        $type = input('type', 0, 'intval'); //类型:0热门 1关注
        $topic_id = input('topic_id', 0); //热门话题id

        if (!in_array($type, [0, 1])) {
            $this->error('您的网络开小差啦~');
        }

        //关注
        $where_follow = '';
        if ($type == 0) {
            $orderby = 'dt.id desc';
        } else {
            $orderby = 'dt.id desc';

            //关注的人
            $follow_user_ids = Db::name('user_follow')->where(['uid'=>$this->auth->id])->column('follow_uid');
            if(!empty($follow_user_ids)){
                $where_follow .= '(dt.user_id IN ('.implode(',',$follow_user_ids).'))';
            }

            //默认
            if($where_follow == ''){
                $where_follow = 'dt.id = 0';
            }
        }

        $where['dt.status'] = 0;
        $where['dt.auit_status'] = 1;
        $where['user.is_kefu'] = 0;
        if ($this->auth->gender == 1) {
            $where['user.gender'] = 0;
        } elseif ($this->auth->gender == 0) {
            $where['user.gender'] = 1;
        } else {
            $this->success('success',[]);
        }
        if ($topic_id) {
            $where['dt.topic_id'] = $topic_id;
            $orderby = 'dt.id desc';
        }

        $list = Db::name('topic_dongtai')->alias('dt')
            ->join('user','dt.user_id = user.id','LEFT')
            ->join('user_wallet uw','user.id = uw.user_id','LEFT')
            ->join('topic_hub th','dt.topic_id = th.id','LEFT')
            ->field('dt.*,user.nickname,user.avatar,user.gender,user.birthday,user.idcard_status,user.real_status,user.is_hideaddress,th.name,uw.vip_endtime')
            ->where($where)
            ->where($where_follow)
            ->order($orderby)->autopage()->select();
        $list = list_domain_image($list,['images','avatar']);

        //追加是否点赞
        if(!empty($list)){
            $ids = array_column($list,'id');
            $map = [
                'dt_id' => ['IN',$ids],
                'user_id'  => $this->auth->id,
            ];
            $good_list = Db::name('topic_dongtai_good')->where($map)->select();
            $mt_user_greet = Db::name('user_greet'); //是否打过招呼
            $mt_gift_user_dongtai = Db::name('gift_user_dongtai');

            foreach ($list as &$val) {
                $val['name'] = $val['name'] ? : '';
                $val['birthday'] = birthtime_to_age($val['birthday']);
                $val['createtime'] = get_last_time($val['createtime']);
                $val['cityname'] = $val['is_hideaddress'] ? '' : $val['address'] ;
                //用户vip
                $val['is_vip'] = $val['vip_endtime'] > time() ? 1 : 0;
                unset($val['vip_endtime']);

                //是否点过赞:0否  1是
                $val['isgood'] = 0;
                foreach($good_list as $k => $v){
                    if($val['id'] == $v['dt_id']){
                        $val['isgood'] = 1;
                    }
                }
                //礼物数量
                $val['gift_count'] = $mt_gift_user_dongtai->where(['dt_id' => $val['id']])->count('id');
                //查询是否打过招呼
                $count = $mt_user_greet->where(['user_id' => $this->auth->id, 'user_to_id' => $val['user_id']])->count('id');
                if ($count) {
                    $val['is_chat'] = 1; //是否打过招呼: 1是  0否
                } else {
                    $val['is_chat'] = 0; //是否打过招呼: 1是  0否
                }

                //创建视频缩略图
                $val['images_thumb'] = '';
                if ($val['type'] == 2) {
                    $images_url = explode('.', $val['images']);
                    unset($images_url[count($images_url) - 1]);
                    $val['images_thumb'] = join('.', $images_url) . '_0.jpg';
                }
            }
        }

        $this->success('success',$list);
    }

    //用户动态列表
    public function mydongtailist() {
        $user_id = input('uid', $this->auth->id);
        if (!$user_id) {
            $this->error('您的网络开小差啦~');
        }
        $where['dt.user_id'] = $user_id;
        $where['dt.status'] = 0;
        $where['dt.auit_status'] = 1;
        $orderby = 'dt.id desc';

        $list = Db::name('topic_dongtai')->alias('dt')
            ->join('user','dt.user_id = user.id','LEFT')
            ->join('user_wallet uw','user.id = uw.user_id','LEFT')
            ->join('topic_hub th','dt.topic_id = th.id','LEFT')
            ->field('dt.*,user.nickname,user.avatar,user.gender,user.birthday,user.idcard_status,user.real_status,user.is_hideaddress,th.name,uw.vip_endtime')
            ->where($where)
            ->order($orderby)->autopage()->select();
        $list = list_domain_image($list,['images','avatar']);

        //追加是否点赞
        if(!empty($list)){
            $ids = array_column($list,'id');
            $map = [
                'dt_id' => ['IN',$ids],
                'user_id'  => $this->auth->id,
            ];
            $good_list = Db::name('topic_dongtai_good')->where($map)->select();
            $mt_user_greet = Db::name('user_greet'); //是否打过招呼
            $mt_gift_user_dongtai = Db::name('gift_user_dongtai');


            foreach ($list as &$val) {
                $val['name'] = $val['name'] ? : '';
                $val['birthday'] = birthtime_to_age($val['birthday']);
                $val['createtime'] = get_last_time($val['createtime']);
                $val['cityname'] = $val['is_hideaddress'] ? '' : $val['address'];

                //用户vip
                $val['is_vip'] = $val['vip_endtime'] > time() ? 1 : 0;
                unset($val['vip_endtime']);

                //是否点过赞:0否  1是
                $val['isgood'] = 0;
                foreach($good_list as $k => $v){
                    if($val['id'] == $v['dt_id']){
                        $val['isgood'] = 1;
                    }
                }
                //礼物数量
                $val['gift_count'] = $mt_gift_user_dongtai->where(['dt_id' => $val['id']])->count('id');
                //查询是否打过招呼
                $count = $mt_user_greet->where(['user_id' => $this->auth->id, 'user_to_id' => $val['user_id']])->count('id');
                if ($count) {
                    $val['is_chat'] = 1; //是否打过招呼: 1是  0否
                } else {
                    $val['is_chat'] = 0; //是否打过招呼: 1是  0否
                }

                //创建视频缩略图
                $val['images_thumb'] = '';
                if ($val['type'] == 2) {
                    $images_url = explode('.', $val['images']);
                    unset($images_url[count($images_url) - 1]);
                    $val['images_thumb'] = join('.', $images_url) . '_0.jpg';
                }
            }
        }

        $this->success('success',$list);
    }

    //动态详情
    public function dongtaiinfo(){
        $id = input('id', 0, 'intval');
        if (!$id) {
            $this->error('您的网络开小差啦~');
        }

        $info = Db::name('topic_dongtai')->alias('dt')
            ->join('user','dt.user_id = user.id','LEFT')
            ->join('user_wallet uw','user.id = uw.user_id','LEFT')
            ->join('topic_hub th','dt.topic_id = th.id','LEFT')
            ->field('dt.*,user.nickname,user.avatar,user.gender,user.birthday,user.idcard_status,user.real_status,user.is_hideaddress,th.name,uw.vip_endtime')
            ->where('dt.id',$id)->find();
        if (!$info) {
            $this->error('您的网络开小差啦~');
        }
        if ($info['status'] != 0) {
            $this->error('您的网络开小差啦~');
        }

        $info = info_domain_image($info,['images','avatar']);
        $info['name'] = $info['name'] ? : '';
        $info['birthday'] = birthtime_to_age($info['birthday']);
        $info['createtime'] = get_last_time($info['createtime']);
        $info['cityname'] = $info['is_hideaddress'] ? '' : $info['address'];
        //用户vip
        $info['is_vip'] = $info['vip_endtime'] > time() ? 1 : 0;
        unset($info['vip_endtime']);

        //是否点赞过
        $info['isgood'] = $this->is_good($id,$this->auth->id);
        //礼物数量
        $info['gift_count'] = Db::name('gift_user_dongtai')->where(['dt_id' => $info['id']])->count('id');
        //查询是否打过招呼
        $count = Db::name('user_greet')->where(['user_id' => $this->auth->id, 'user_to_id' => $info['user_id']])->count('id');
        if ($count) {
            $info['is_chat'] = 1; //是否打过招呼: 1是  0否
        } else {
            $info['is_chat'] = 0; //是否打过招呼: 1是  0否
        }

        //创建视频缩略图
        $info['images_thumb'] = '';
        if ($info['type'] == 2) {
            $images_url = explode('.', $info['images']);
            unset($images_url[count($images_url) - 1]);
            $info['images_thumb'] = join('.', $images_url) . '_0.jpg';
        }

        //是否收藏
        $info['is_collect'] = $this->is_collect($id,$this->auth->id);

        $this->success('success',$info);
    }

    //点赞
    public function good(){
        $id = input('id', 0, 'intval');
        if (!$id) {
            $this->error('您的网络开小差啦~');
        }
        $info = Db::name('topic_dongtai')->find($id);
        if (!$info) {
            $this->error('您的网络开小差啦~');
        }
        if ($info['status'] != 0) {
            $this->error('您的网络开小差啦~');
        }

        $where = [
            'dt_id' => $id,
            'user_id'  => $this->auth->id,
        ];
        $check = Db::name('topic_dongtai_good')->where($where)->find();
        $dt_user_id = Db::name('topic_dongtai')->where('id',$id)->value('user_id');

        if($check){
            Db::name('topic_dongtai_good')->where($where)->delete();
            $down = Db::name('topic_dongtai')->where('id',$id)->setDec('goodnum');
            $this->success('已取消点赞');
        }else{

            Db::startTrans();
            $where['createtime'] = time();
            $rs = Db::name('topic_dongtai_good')->insertGetId($where);
            if(!$rs){
                Db::rollback();
                $this->error('点赞失败');
            }

            $up = Db::name('topic_dongtai')->where('id',$id)->setInc('goodnum');
            if($up === false){
                Db::rollback();
                $this->error('点赞失败');
            }

            //系统消息
            if($dt_user_id != $this->auth->id){
                //入库
                $data = [];
                $data['user_id'] = $dt_user_id;
                $data['dt_id'] = $id;
                $data['from_user_id'] = $this->auth->id;
                $data['title'] = '点赞了你的动态';
                $data['createtime'] = time();

                Db::name('topic_dongtai_message')->insertGetId($data);
            }

            Db::commit();
            $this->success('点赞成功');
        }
    }

    //是否点赞
    private function is_good($dt_id,$uid){
        $where = [
            'dt_id' => $dt_id,
            'user_id'  => $uid,
        ];
        $check = Db::name('topic_dongtai_good')->where($where)->find();
        if($check){
            return 1;
        }else{
            return 0;
        }
    }

    //评论
    public function answer(){
        $id = input('id',0);
        $content = input('content','');
        $to_user_id = input('to_user_id',0);
        $level = input('level',1);  //回复类型:1=层主回复楼主,2=层中回复
        $floor = input('floor',0);

        if(empty($content) || empty($id)){
            $this->error();
        }

        //关键字替换
        $content = Keyworld::sensitive($content);

        //判断
        if($level == 2 && $floor == 0){
            $this->error('楼层错误');
        }

        //黑名单判断
        //是否被动态发布者拉黑
        $dongtai_user_id = Db::name('topic_dongtai')->where('id',$id)->value('user_id');
        $black_check = $this->is_black($dongtai_user_id,$this->auth->id);
        if($black_check){
            $this->error('您已被对方拉黑,禁止评论此动态');
        }
        //是否被层主拉黑
        if($level == 2){
            $answer_info = Db::name('topic_dongtai_answer')->where(['dt_id'=>$id,'level'=>1,'floor'=>$floor])->find();
            $black_check = $this->is_black($answer_info['user_id'],$this->auth->id);
            if($black_check){
                $this->error('您已被对方拉黑,禁止点评此评论');
            }
        }

        //回复楼主,最新楼层
        if($level == 1 || $floor == 0){
            $to_user_id = 0;
            $floor = 1;  //默认一楼

            $last_floor = Db::name('topic_dongtai_answer')->where(['dt_id'=>$id,'level'=>1])->order('floor desc')->value('floor');
            if($last_floor){
                $floor = $last_floor + 1;
            }
        }

        //判断user_id
        if($to_user_id){
            $to_user = Db::name('user')->where('id',$to_user_id)->value('id');
            if(empty($to_user)){
                $this->error('被回复的用户不存在');
            }
        }

        //data
        $data = [
            'dt_id' => $id,
            'floor' => $floor,
            'user_id' => $this->auth->id,
            'content' => $content,
            'to_user_id' => $to_user_id,
            'level' => $level,
            'createtime' => time(),
            'updatetime' => time(),
        ];

        Db::startTrans();
        $rs = Db::name('topic_dongtai_answer')->insertGetId($data);

        if($level == 1){
            Db::name('topic_dongtai')->where('id',$id)->setInc('answernum');
        }

        //系统消息
        /*if($level == 1){
            //发给动态用户
            $msg_user_id = Db::name('topic_dongtai')->where('id',$id)->value('user_id');
            $msg_title = '动态评论';
            $msg_content = $this->auth->nickname.'评论了你的动态';
            $infotype_id = $rs;
        }else{
            //发给层主
            $answer_info = Db::name('topic_dongtai_answer')->where(['dt_id'=>$id,'level'=>1,'floor'=>$floor])->find();
            $msg_user_id = $answer_info['user_id'];
            $msg_title = '动态评论点评';
            $msg_content = $this->auth->nickname.'点评了你的动态评论';
            $infotype_id = $answer_info['id'];
        }
        $msg_id = \app\common\model\Message::addMessage($msg_user_id,$msg_title,$msg_content,'dongtai_answer',$infotype_id);*/

        Db::commit();
        $this->success('评价成功');
    }

    //用户是否拉黑
    private function is_black($uid,$black_uid){
        $where = [
            'uid'       => $uid,
            'black_uid' => $black_uid,
        ];
        $check = Db::name('user_black')->where($where)->find();
        if($check){
            return 1;
        }else{
            return 0;
        }
    }

    //某动态的评论列表
    public function answer_list(){
        $dt_id = input('id',0);
        //楼
        $floor_list = Db::name('topic_dongtai_answer')
            ->alias('a')
            ->field('a.*,user.nickname,user.avatar,user.gender,user.birthday')
            ->join('user','a.user_id = user.id','LEFT')
            ->where(['a.dt_id'=>$dt_id,'a.level'=>1])->order('a.id desc')->autopage()->select();
        $floor_list = list_domain_image($floor_list,['avatar']);

        //追加子评论
        if(!empty($floor_list)){
            foreach($floor_list as $key => &$val){
                //下面几条子回复,字符串
                $val['childremark'] = '';

                $map = [
                    'a.dt_id' => $dt_id,
                    'a.floor' => $val['floor'],
                    'a.level' => 2,
                ];
                $number = Db::name('topic_dongtai_answer')->alias('a')->where($map)->count();
                if($number > 0){
                    $answer_info = Db::name('topic_dongtai_answer')
                        ->alias('a')
                        ->field('user.nickname')
                        ->join('user','a.user_id = user.id','LEFT')
                        ->where($map)->order('a.id desc')->find();

                    $val['childremark'] = $answer_info['nickname'].'...等人,共'.$number.'条回复';
                }

                //时间处理
                $val['createtime'] = get_last_time($val['createtime']);

                //回复是否已赞
                $val['is_good'] = $this->answer_is_good($val['id'],$this->auth->id);

                //用户年龄
                $val['birthday'] = birthtime_to_age($val['birthday']);
            }
        }

        $this->success('success',$floor_list);
    }

    //单独某一层的详细
    public function answer_info(){
        $answer_id = input('answer_id');

        //楼
        $floor_info = Db::name('topic_dongtai_answer')
            ->alias('a')
            ->field('a.*,user.nickname,user.avatar,user.gender,user.birthday')
            ->join('user','a.user_id = user.id','LEFT')
            ->where(['a.id'=>$answer_id])->find();
        if(empty($floor_info)){
            $this->success('success',[]);
        }
        $floor_info = info_domain_image($floor_info,['avatar']);
        $floor_info['createtime'] = get_last_time($floor_info['createtime']);
        //用户年龄
        $floor_info['birthday'] = birthtime_to_age($floor_info['birthday']);
        //回复是否已赞
        $floor_info['is_good'] = $this->answer_is_good($answer_id,$this->auth->id);
        $floor_info['answernumber'] = Db::name('topic_dongtai_answer')->where(['dt_id'=>$floor_info['dt_id'],'floor'=>$floor_info['floor'],'level'=>2])->count();

        //层
        $floors = $floor_info['floor'];
        $child_lists = Db::name('topic_dongtai_answer')->alias('a')
            ->field('a.*,user.nickname,user.avatar,user.gender,user.birthday')
            ->join('user','a.user_id = user.id','LEFT')
            ->where(['a.dt_id'=>$floor_info['dt_id'],'a.floor'=>$floors,'a.level'=>2])->order('a.id desc')->autopage()->select();
        $child_lists = list_domain_image($child_lists,['avatar','to_avatar']);
        if(!empty($child_lists)){
            foreach($child_lists as $key => &$answer){
                //用户年龄
                $answer['birthday'] = birthtime_to_age($answer['birthday']);

                $answer['is_good'] = $this->answer_is_good($answer['id'],$this->auth->id);
                $answer['createtime'] = get_last_time($answer['createtime']);
            }
        }

        //合并
        $floor_info['child'] = $child_lists;

        $this->success('success',$floor_info);

    }

    //对评论点赞
    public function answer_good(){
        $dt_id = input('dt_id',0);
        $answer_id = input('answer_id',0);

        $where = [
            'dt_id'     => $dt_id,
            'answer_id' => $answer_id,
            'user_id'   => $this->auth->id,
        ];
        $check = Db::name('topic_answer_good')->where($where)->find();

        if($check){
            Db::name('topic_answer_good')->where($where)->delete();
            Db::name('topic_dongtai_answer')->where('id',$answer_id)->setDec('goodnum');
            $this->success('已取消点赞');
        }else{

            Db::startTrans();
            $where['createtime'] = time();
            $rs = Db::name('topic_answer_good')->insertGetId($where);
            $up = Db::name('topic_dongtai_answer')->where('id',$answer_id)->setInc('goodnum');

            if($rs && $up !== false){
                Db::commit();
                $this->success('点赞成功');
            }
            Db::rollback();
            $this->error('点赞失败');
        }
    }

    //回复是否点赞
    private function answer_is_good($answer_id,$uid){
        $where = [
            'answer_id' => $answer_id,
            'user_id'  => $uid,
        ];
        $check = Db::name('topic_answer_good')->where($where)->find();
        if($check){
            return 1;
        }else{
            return 0;
        }
    }

    //删除我的某个评论
    public function delete_answer(){
        $id = input('id',0);
        if(!$id){
            $this->error();
        }

        Db::startTrans();
        $info = Db::name('topic_dongtai_answer')->where('id',$id)->where('user_id',$this->auth->id)->find();
        if(!$info){
            $this->error('不存在的动态评论');
        }

        if($info['level'] == 1){


            //楼层内都删
            $louceng_id = Db::name('topic_dongtai_answer')->where('dt_id',$info['dt_id'])->where('level',2)->where('floor',$info['floor'])->column('id');
            if(!empty($louceng_id)){
                Db::name('topic_dongtai')->where('id',$info['dt_id'])->setDec('answernum',count($louceng_id));//回复数减1
                Db::name('topic_dongtai_answer')->where('id','IN',$louceng_id)->delete();//评论删掉
                Db::name('topic_answer_good')->where('answer_id','IN',$louceng_id)->delete();//评论点赞删掉
            }

        }

        Db::name('topic_dongtai')->where('id',$info['dt_id'])->setDec('answernum');//回复数减1
        Db::name('topic_dongtai_answer')->where('id',$id)->delete();  //评论删掉
        Db::name('topic_answer_good')->where('answer_id',$id)->delete();//评论点赞删掉

        Db::commit();

        $this->success();
    }

    //动态赠送礼物
    public function givegiftdongtai() {
        // 接口防并发
        if (!$this->apiLimit(1, 1)) {
            $this->error(__('Operation frequently'));
        }

//        $user_id = input('user_id');// 赠送对象
        $dt_id = input('dt_id', 0, 'intval'); //动态id
        $gift_id = input('gift_id');// 礼物ID
        $number  = input('number',1,'intval');//数量

        if (!$dt_id || !$gift_id || $number < 1) {
            $this->error();
        }
        //查询动态
        $dongtai_info = Db::name('topic_dongtai')->find($dt_id);
        if (!$dongtai_info) {
            $this->error('您的网络开小差啦~');
        }
        if ($dongtai_info['status'] != 0) {
            $this->error('您的网络开小差啦~');
        }
        $user_id =  $dongtai_info['user_id'];

        // 不可以赠送给自己
        if($this->auth->id == $user_id) {
            $this->error("不可以赠送给自己");
        }

        // 获取礼物信息
        $giftinfo = Db::name('gift')->where('id',$gift_id)->find();
        if (!$giftinfo)
        {
            $this->error("请选择礼物");
        }
        $giftvalue = bcmul($giftinfo['price'],$number);

        //被赠送人信息
        $touserinfo = Db::name('user')->where('id',$user_id)->find();
        if (!$touserinfo) {
            $this->error("不存在的用户");
        }
        // 判断当前用户余额
        $user_gold = model('wallet')->getWallet($this->auth->id,'gold');
        if($user_gold < $giftvalue) {
            $this->error("您的金币余额不足");
        }

        Db::startTrans();
        // 添加礼物赠送记录表
        $data = [
            'user_id' => $this->auth->id,
            'user_to_id' => $user_id,
            'dt_id' => $dt_id,
            'gift_id' => $giftinfo['id'],
            'gift_name' => $giftinfo['name'],
            'number' => $number,
            'price'       => $giftinfo['price'],
            'total_price' => $giftvalue,
            'createtime' => time(),
        ];

        //每个礼物都要计算平台抽成和房主抽成
        $gift_plat_scale = config('site.gift_plat_scale');
        $data['platvalue']    = bcmul($gift_plat_scale/100  ,$data['total_price'],1);//平台抽成
        $data['getvalue']     = bcsub($data['total_price'] ,$data['platvalue'],1);//减去抽成剩余价值

        $money_to_gold = config('site.money_to_gold');
        $data['getmoney']     = bcdiv($data['getvalue'] ,$money_to_gold,2);//收益

        $log_id = Db::name('gift_user_dongtai')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('赠送失败');
        }

        if($giftvalue > 0){
            // 扣除当前用户余额
            $wallet_rs = model('wallet')->lockChangeAccountRemain($this->auth->id,$user_id,'gold',-$giftvalue,59,'赠送礼物:'.$giftinfo["name"] . '*' . $number,'gift_user_dongtai',$log_id);
            if($wallet_rs['status'] === false){
                Db::rollback();
                $this->error($wallet_rs['msg']);
            }
        }
        if($data['getmoney'] > 0){
            // 添加获赠用户收益
            $wallet_rs = model('wallet')->lockChangeAccountRemain($user_id,$this->auth->id,'money',$data['getmoney'],60,'获得礼物:'.$giftinfo["name"] . '*' . $number,'gift_user_dongtai',$log_id,2);
            if($wallet_rs['status'] === false){
                Db::rollback();
                $this->error($wallet_rs['msg']);
            }
        }

        //增加赠送用户上级余额
        if ($touserinfo['intro_uid']) {
            //获取返利比率
            $agent_info = Db::name('user')->where(['id' => $touserinfo['intro_uid']])->field('is_agent,h_intro_income_rebate_rate')->find();
            $intro_income_rebate_rate = ($agent_info['is_agent'] == 1) ? $agent_info['h_intro_income_rebate_rate'] : (int)config('site.intro_income_rebate_rate'); //邀请人收礼物返利比率
            if ($intro_income_rebate_rate > 0 && $intro_income_rebate_rate <= 100) {
                //上级获得金额
                $intro_uid_money = bcdiv(bcmul($data['getmoney'],$intro_income_rebate_rate,2),100,2);
                if ($intro_uid_money > 0) {
                    $intro_result = model('Wallet')->lockChangeAccountRemain($touserinfo['intro_uid'],$user_id,'money',$intro_uid_money,68, '邀请人动态礼物获赠奖励','gift_user_dongtai',$log_id);
                    if($intro_result['status']===false)
                    {
                        Db::rollback();
                        $this->error($intro_result['msg']);
                    }
                }
            }
        }

        if ($this->auth->gender == 1 && $touserinfo['gender'] == 0) {
            //增加亲密度
            $user_intimacy_rs = addintimacy($this->auth->id, $user_id, $giftvalue);
            if (!$user_intimacy_rs['status']) {
                Db::rollback();
                $this->error('您的网络开小差啦~');
            }
        }




        Db::commit();

        //发送消息
        if (isset($user_intimacy_rs) && $user_intimacy_rs['level_remark']) {
            $tenim = new \app\api\controller\Tenim;
            $tenim->sendMessageToUser($this->auth->id, $user_id, $user_intimacy_rs['level_remark'], 1);
        }

        $return_data['money'] = $data['getmoney']; //获得金额
        $return_data['level_remark'] = isset($user_intimacy_rs) ? $user_intimacy_rs['level_remark'] : ''; //亲密度等级提示语
        $this->success('赠送成功', $return_data);
    }

    //动态通知
    public function message(){
        $list = Db::name('topic_dongtai_message')->alias('msg')->field('msg.*,user.avatar,user.nickname')
            ->join('user','msg.from_user_id = user.id','LEFT')
            ->where('msg.user_id',$this->auth->id)->autopage()->select();
        $list = list_domain_image($list,['avatar']);

        $this->success('success',$list);
    }


    //删除动态
    public function delete() {
        $id = input('id', 0, 'intval');
        if (!$id) {
            $this->error('您的网络开小差啦~');
        }
        $info = Db::name('topic_dongtai')->find($id);
        if (!$info) {
            $this->error('您的网络开小差啦~');
        }
        if ($info['user_id'] != $this->auth->id) {
            $this->error('您的网络开小差啦~');
        }

        $rs = Db::name('topic_dongtai')->where(['id' => $id])->setField('status', 1);
        if (!$rs) {
            $this->error('您的网络开小差啦~');
        }

        $this->success('删除成功');
    }

    //举报
    public function report(){
        $dt_id = input('dt_id',0);

        $check = Db::name('topic_dongtai')->where('id',$dt_id)->find();
        if(empty($check)){
            $this->error('不存在的动态');
        }

        $data['dt_id'] = $dt_id;
        $data['user_id']    = $this->auth->id;
        $data['to_user_id'] = $check['user_id'];
        $data['createtime'] = time();

        Db::name('topic_dongtai_report')->insertGetId($data);
        $this->success('举报成功');
    }

    //收藏,取消收藏
    public function collect(){
        $where = [
            'user_id'  => $this->auth->id,
            'table'    => 'topic_dongtai',
            'table_id' => input('id',0),
        ];
        $check = Db::name('user_collect')->where($where)->find();
        if($check){
            Db::name('user_collect')->where($where)->delete();
            $this->success('已取消收藏');
        }else{
            Db::name('user_collect')->insertGetId($where);
            $this->success('收藏成功');
        }
    }

    //我的收藏
    public function my_collect(){

        $collect_id = Db::name('user_collect')->where(['table'=>'topic_dongtai','user_id'=>$this->auth->id])->column('table_id');
        $where = ['dt.id'=>['IN',$collect_id]];

        $where['dt.status'] = 0;
        $where['dt.auit_status'] = 1;
        $orderby = 'dt.id desc';

        $list = Db::name('topic_dongtai')->alias('dt')
            ->join('user','dt.user_id = user.id','LEFT')
            ->join('user_wallet uw','user.id = uw.user_id','LEFT')
            ->join('topic_hub th','dt.topic_id = th.id','LEFT')
            ->field('dt.*,user.nickname,user.avatar,user.gender,user.birthday,user.idcard_status,user.real_status,user.is_hideaddress,th.name,uw.vip_endtime')
            ->where($where)
            ->order($orderby)->autopage()->select();
        $list = list_domain_image($list,['images','avatar']);

        //追加是否点赞
        if(!empty($list)){
            $ids = array_column($list,'id');
            $map = [
                'dt_id' => ['IN',$ids],
                'user_id'  => $this->auth->id,
            ];
            $good_list = Db::name('topic_dongtai_good')->where($map)->select();
            $mt_user_greet = Db::name('user_greet'); //是否打过招呼
            $mt_gift_user_dongtai = Db::name('gift_user_dongtai');


            foreach ($list as &$val) {
                $val['name'] = $val['name'] ? : '';
                $val['birthday'] = birthtime_to_age($val['birthday']);
                $val['createtime'] = get_last_time($val['createtime']);
                $val['cityname'] = $val['is_hideaddress'] ? '' : $val['address'];

                //用户vip
                $val['is_vip'] = $val['vip_endtime'] > time() ? 1 : 0;
                unset($val['vip_endtime']);

                //是否点过赞:0否  1是
                $val['isgood'] = 0;
                foreach($good_list as $k => $v){
                    if($val['id'] == $v['dt_id']){
                        $val['isgood'] = 1;
                    }
                }
                //礼物数量
                $val['gift_count'] = $mt_gift_user_dongtai->where(['dt_id' => $val['id']])->count('id');
                //查询是否打过招呼
                $count = $mt_user_greet->where(['user_id' => $this->auth->id, 'user_to_id' => $val['user_id']])->count('id');
                if ($count) {
                    $val['is_chat'] = 1; //是否打过招呼: 1是  0否
                } else {
                    $val['is_chat'] = 0; //是否打过招呼: 1是  0否
                }

                //创建视频缩略图
                $val['images_thumb'] = '';
                if ($val['type'] == 2) {
                    $images_url = explode('.', $val['images']);
                    unset($images_url[count($images_url) - 1]);
                    $val['images_thumb'] = join('.', $images_url) . '_0.jpg';
                }
            }
        }

        $this->success('success',$list);
    }

    //动态是否收藏
    private function is_collect($dt_id,$uid){
        $where = [
            'user_id'  => $uid,
            'table'    => 'topic_dongtai',
            'table_id' => $dt_id,
        ];
        $check = Db::name('user_collect')->where($where)->find();
        if($check){
            return 1;
        }else{
            return 0;
        }
    }




/////////////////////////////////////////////////////////////////////////////////

    //动态收到礼物列表
    public function dongtaigiftlist() {
        $id = input('id', 0, 'intval');
        if (!$id) {
            $this->error('您的网络开小差啦~');
        }
        //点赞只能查看异性
        $dongtaiWhere['td.id'] = $id;
        $dongtai = Db::name('topic_dongtai')->alias('td')->field('td.id,td.user_id,u.gender')
            ->join('user u','u.id = td.user_id','LEFT')
            ->where($dongtaiWhere)->find();
        $where['a.dt_id'] = $id;
        $gender = isset($dongtai['gender']) ? $dongtai['gender'] : 0;
        if ($gender == 1) {
            $where['user.gender'] = 0;
        } elseif ($gender == 0) {
            $where['user.gender'] = 1;
        }
        $list = Db::name('gift_user_dongtai')->alias('a')->field('a.user_id, count(a.id) count')
            ->join('user', 'a.user_id = user.id', 'left')
            ->where($where)->group('a.user_id')->order('a.id desc')->autopage()->select();
        if (!$list) {
            $this->success('success', $list);
        }

        $mt_user = Db::name('user');
        foreach ($list as &$v) {
            $user_info = $mt_user->field('nickname, avatar, gender, birthday')->where(['id' => $v['user_id']])->find();
            $v['nickname'] = $user_info['nickname'];
            $v['avatar'] = one_domain_image($user_info['avatar']);
            $v['birthday'] = birthtime_to_age($user_info['birthday']);
        }

        $this->success('success', $list);
    }



    //点赞列表
    public function dongtaigoodlist() {
        $id = input('id', 0, 'intval');
        if (!$id) {
            $this->error('您的网络开小差啦~');
        }
        //点赞只能查看异性
        $dongtaiWhere['td.id'] = $id;
        $dongtai = Db::name('topic_dongtai')->alias('td')->field('td.id,td.user_id,u.gender')
            ->join('user u','u.id = td.user_id','LEFT')
            ->where($dongtaiWhere)->find();
        $where['a.dt_id'] = $id;
        $gender = isset($dongtai['gender']) ? $dongtai['gender'] : 0;
        if ($gender == 1) {
            $where['user.gender'] = 0;
        } elseif ($gender == 0) {
            $where['user.gender'] = 1;
        }
        $list = Db::name('topic_dongtai_good')->alias('a')
            ->join('user', 'a.user_id = user.id', 'left')
            ->field('a.*, user.nickname,user.avatar,user.gender,user.birthday')
            ->where($where)
            ->order('a.id desc')
            ->autopage()->select();

        if (!$list) {
            $this->success('success', $list);
        }
        $list = list_domain_image($list,['avatar']);

        foreach ($list as &$v) {
            $v['birthday'] = birthtime_to_age($v['birthday']);
            $v['createtime'] = get_last_time($v['createtime']);
        }

        $this->success('success', $list);
    }
}