<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\controller;

/**
 * 群管理
 * Summary of Group
 */
class Group extends BaseShopController
{

    /**
     * 群禁用
     */
    public function disable($id)
    {
        $groupInfo = \app\common\model\ChatGroup::find($id);

        if($groupInfo->create_by_user_id != $this->userId){
            return show(config('status.error'),'无权限');
        };

        $groupInfo->status = 0;

        $groupInfo->save();

        return show(config('status.success'),'设置成功');

    }

    /**
     * 群解禁
     * @param mixed $id
     * @return \think\response\Json
     */
    public function enable($id)
    {
        $groupInfo = \app\common\model\ChatGroup::find($id);

        if($groupInfo->create_by_user_id != $this->userId){
            return show(config('status.error'),'无权限');
        };

        $groupInfo->status = 1;

        $groupInfo->save();

        return show(config('status.success'),'设置成功');
    }

    /**
     * 拉人进去
     * @param mixed $id
     * @return \think\response\Json
     */
    public function pull()
    {

        $user_ids = $this->request->post('user_ids');
        $group_id = $this->request->post('group_id');

        $groupInfo = \app\common\model\ChatGroup::find($group_id);
        if($groupInfo->create_by_user_id != $this->userId){
            return show(config('status.error'),'无权限');
        };

        $user_ids = explode(',',$user_ids);
        foreach($user_ids as $uid){
            if(empty($uid)){
                continue;
            }
            $res = \app\common\model\ChatGroupMember::create([
                'group_id'=>$group_id,
                'user_id'=>$uid,
            ]);

            $count = \app\common\model\ChatGroupMember::where([
                ['group_id','=',$group_id],
                ['status','=',1]
            ])->count();
            \app\common\model\ChatGroup::where('id',$group_id)->update(['num'=>$count]);

            // 记录日志
            $text = $_SERVER;
            $text['group_id']=$group_id;
            \app\common\model\UserLog::create([
                'user_id'=>$this->userId,
                'ip'=>$this->request->ip(),
                'remark'=>'加入群聊',
                'code'=>'join_group',
                'text'=>json_encode($text,true),
            ]);
            
        }

        return show(config('status.success'),'ok');
    }


    /**
     * 群解散
     */
    public function delete($id)
    {
        $groupInfo = \app\common\model\ChatGroup::find($id);

        if($groupInfo->create_by_user_id != $this->userId){
            return show(config('status.error'),'无权限');
        };

        $groupInfo->delete_time = time();

        $groupInfo->save();

        return show(config('status.success'),'群解散成功');
    }

    /**
     * 踢人
     */
    public function kick()
    {
        $user_id = $this->request->post('user_id');
        $group_id = $this->request->post('group_id');

        $groupInfo = \app\common\model\ChatGroup::find($group_id);

        if($groupInfo->create_by_user_id != $this->userId){
            return show(config('status.error'),'无权限');
        };

        if($this->userId == $user_id){
            return show(config('status.error'),'不能踢自己');
        }

        // 添加聊天记录
        $message = [
            'from_id' => $this->userId,
            'group_id' => $group_id,
            'msg' =>$user_id,
            'msg_type' => 'tip_remove',
            'type' => 'group_chat',
        ];
        // 持久化到数据库
        $data = \app\common\model\ChatGroupMessage::create($message);

        $res = \app\common\model\ChatGroupMember::where([
            'group_id'=>$group_id,
            'user_id'=>$user_id
        ])
        ->delete();
        
        // 持久化到数据库
        $data = \app\common\model\ChatPrivateMessage::create($message);

        $count = \app\common\model\ChatGroupMember::where([
            ['group_id','=',$group_id],
            ['status','=',1]
        ])->count();
        \app\common\model\ChatGroup::where('id',$group_id)->update(['num'=>$count]);

        if(!$res){
            return show(config('status.error'),'操作失败');
        }

        return show(config('status.success'),'成功提出群聊');
        
    }

    public function createGroup()
    {
        \think\facade\Db::startTrans(); 
        try{
            $params = $this->request->post();

            $createData = [
                'create_by_user_id'=>$this->userId,
                'name'=>$params['name'],
                'desc'=>$params['desc'],
            ];

            // 付费设置
            if(isset($params['price'])){
                $createData['price'] = $params['price'];
            }

            // 群图
            if(isset($params['image'])){
                $createData['image'] = $params['image'];
            }

            // 群标签
            if(isset($params['label_ids'])){
                $createData['label_ids'] = ','.implode(',',$params['label_ids']).',';
            }

            // 个人主页显示
            if(isset($params['home_show'])){
                $createData['home_show'] = $params['home_show'];
            }

            // 群定位
            if(isset($params['city'])){
                $createData['longitude'] = $params['longitude'];
                $createData['latitude'] = $params['latitude'];
                $createData['province'] = $params['province'];
                $createData['city'] = $params['city'];
                $createData['district'] = $params['district'];
                $createData['county'] = $params['county'];
                $createData['area'] = $params['area'];
                $createData['address'] = $params['address'];
            }
            

            // 群分类
            if(!isset($params['category_id']) || empty($params['category_id'])){
                return show(config('status.error'),'请选择分类');
            }
            $createData['category_id'] = $params['category_id'];

            $res = \app\common\model\ChatGroup::create($createData);
            if(!$res){
                return $this->success('error',[],0);
            };
            \app\common\model\ChatGroupMember::create([
                'user_id'=>$this->userId,
                'group_id'=>$res->id,
            ]);
            \think\facade\Db::commit();
            return $this->success('ok',['group_id'=>$res->id]);
        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),'创建失败：'.$e->getMessage());
        }
    }


    public function categroyList()
    {
        $lists = \app\common\model\GroupCategory::field('id,name,pid,image,desc')
            ->order(['sort'=>'desc','id'=>'desc'])
            ->select()
            ->toArray();

        $lists = linear_to_tree($lists,'sons');

        return show(config('status.success'),'分类',$lists);
    }

    /**
     * 群列表查询
     */
    public function list()
    {
        $params = $this->request->get();

        $where = [];

        if(isset($params['category_id'])){
            $where[]=['category_id','=',$params['category_id']];
        }

        if(isset($params['label_id'])){
            $where[]=['label_ids','like','%,'.$params['label_id'].',%'];
        }

        if(isset($params['name'])){
            $where[]=['name','like','%'.$params['name'].'%'];
        }

        if(isset($params['category_id'])){
            $where[]=['category_id','like',$params['category_id']];
        }

        if(isset($params['province'])){
            $where[]=['province','like','%'.$params['province'].'%'];
        }
        if(isset($params['city'])){
            $where[]=['city','like','%'.$params['city'].'%'];
        }
        if(isset($params['district'])){
            $where[]=['district','like','%'.$params['district'].'%'];
        }
        if(isset($params['county'])){
            $where[]=['county','like','%'.$params['county'].'%'];
        }
        if(isset($params['area'])){
            $where[]=['area','like','%'.$params['area'].'%'];
        }

        // 最少群人数
        if(isset($params['min_num'])){
            $where[]=['num','>',$params['min_num']];
        }
        // 最多人群数
        if(isset($params['max_num'])){
            $where[]=['num','>',$params['max_num']];
        }

        $list = \app\common\model\ChatGroup::with(['member'])
        ->where($where)
        ->where('status',1)
        ->order('create_time','desc')
        ->paginate(20);

        $list = $list->toArray();
        
        foreach($list['data'] as &$v){
            // dd($v);
            // 查询最近有多少人发言
            $v['send_user_count'] = \app\common\model\ChatGroupMessage::where([
                ['group_id','=',$v['id']],
                ['create_time','>',time() - 60*60*24],
            ])
            ->count('DISTINCT from_id');
        };

        return show(config('status.success'),$list);
        
    }

    /**
     * @notes 群付费订单
     * @return \think\response\Json
     */
    public function groupOrder()
    {
        $params = $this->request->post();
        // dd($params);
        $params['user_id'] = $this->userId;
        $params['terminal'] = $this->userInfo['terminal'];
        $group = \app\common\model\ChatGroup::find($params['group_id']);

        if($group['price'] < 0.01){
            return show(config('status.error'),'当前群不支持付费进群');
        }

        $data = [
            'sn'            => time().rand(00000,99999),
            'terminal'      => $params['terminal'],
            'user_id'       => $params['user_id'],
            'pay_status'    => \app\common\enum\PayEnum::UNPAID,
            'pay_way'       => $params['pay_way'] ?? 2,
            'order_amount'  => $group['price'],
            'group_id'    => $params['group_id']
        ];

        $order = \app\common\model\GroupOrder::create($data);
        if(!$order){
            return show(config('status.error'),'error');
        }

        return show(config('status.success'),'ok',[
            'order_id' => $order->id,
            'from' => 'group'
        ]);

    }

    /**
     * 申请进群
     */
    public function requestJoin()
    {
        $params = $this->request->post();

        $group = \app\common\model\ChatGroup::find($params['group_id']);

        if($group->visit_level>0){
            $user = \app\common\model\User::find($this->userId);
            if($user->level < $group->visit_level){
                return show(config('status.error'),'此群限等级'.$group->visit_level.'或以上的用户加入');
            }
        }

        $member_count = \app\common\model\ChatGroupMember::where([
            'group_id'=>$group->id,
            'status'=>1,
        ])->count();
        if($member_count > $group->max_members){
            return show(config('status.error'),'人数达到上限');
        };
        
        // 判断价格
        if($group->price>0){
            return show(config('status.error'),'此群为付费群');
        };

        $count = \app\common\model\ChatGroupMember::where([
            'group_id'=>$params['group_id'],
            'user_id'=>$this->userId,
        ])->count();
        \app\common\model\ChatGroup::where('id',$params['group_id'])->update(['num'=>$count]);
        if($count>0){
            return show(config('status.error'),msg: '你已在群里请不要重复加');
        }

        // 加入群聊
        \think\facade\Db::startTrans();
        try{

            // 添加聊天记录
            $message = [
                'from_id' => $this->userId,
                'group_id' => $params['group_id'],
                'msg' =>$this->userId,
                'msg_type' => 'tip_add',
                'type' => 'group_chat',
            ];

            // 持久化到数据库
            $data = \app\common\model\ChatGroupMessage::create($message);

            // 拉入群聊
            \app\common\model\ChatGroupMember::create([
                'group_id'=>$params['group_id'],
                'user_id'=>$this->userId,
            ]);

            // 记录日志
            $text = $_SERVER;
            $text['group_id']=$params['group_id'];
            \app\common\model\UserLog::create([
                'user_id'=>$this->userId,
                'ip'=>$this->request->ip(),
                'remark'=>'加入群聊',
                'code'=>'join_group',
                'text'=>json_encode($text,true),
            ]);

            \think\facade\Db::commit();

            return show(config('status.success'),'加群成功');
        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        
        
    }


    /**
     * 查询同城群
     * @return void
     */
    public function sameCity()
    {
        $user = \app\common\model\User::find($this->userId);

        if(empty($user->city)){
            return show(config('status.error'),'请先设置定位');
        }

        $list = \app\common\model\ChatGroup::field('id,name,desc,price,visit_level,longitude,latitude,province,city,district,county,area,address')
        ->where([
            'city'=>$user->city
        ])->paginate(20);

        return show(config('status.success'),$list);
    }

    /**
     * 群标签
     */
    public function groupLabelList()
    {
        $list = \app\common\model\GroupLabel::order('sort','desc')->select()->toArray();

        return show(config('status.success'),$list);
    }

    /**
     * 根据标签搜索群
     */
    public function listByLabel($label_id)
    {
        $list = \app\common\model\GroupLabel::find();

        // return show()
        $list = \app\common\model\ChatGroup::where('lable','like','%'.$label_id.'%')
        ->paginate(20);

        return show(config('status.success'),$list);
    }

    /**
     * 用户创建标签
     */
    public function createLabel()
    {
        $label_name = $this->request->post('label_name');

        $label = \app\common\model\GroupLabel::where('name',$label_name)->find();

        if($label){
           return show(config('status.success'),'标签已存在'); 
        }

        $res = \app\common\model\GroupLabel::create(['name'=>$label_name]);

        return show(config('status.success'),'添加成功',['id'=>$res->id]);
        
    }

}