<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;

class Chat extends Model
{
    public static function getSet(){
        $uniacid = Db::name("platform")->order('id desc')->value("id");
        $set = Db::name("bbfx_chat")->where(['uniacid'=>$uniacid])->find();
        if(!empty($set)){
            if(empty($set['port'])){
                $set['port'] = "2000";
            }
        } 
        return $set;
    }

    public static function setTime($time){
        if($time > strtotime(date("Y-m-d 00:00:00"))){
            return date("H:i",$time);
        }
        else if($time > strtotime(date("Y-01-01 00:00:00"))){
            return date("m-d H:i",$time);
        }
        else{
            return date("Y-m-d H:i",$time);
        }
    }

    // 加客服
    public static function addKefu($user_id){
        $set = self::getSet();
        if($set['status'] != 1){
            return __json(0,"平台未开启客服");
        }
        if(empty($set['kefu_uid'])){
            return __json(0,"平台未配置客服");
        }
        $user = Db::name("bbfx_user")->where(['id'=>$user_id])->field("id,uniacid,nickname,avatar")->find();
        if(empty($user)){
            return __json(0,"用户信息错误");
        }

        $kefu_user_list = Db::name("bbfx_user")->where(['uniacid'=>$user['uniacid'],'id'=>['in',$set['kefu_uid']]])->field("id,uniacid,nickname,avatar,chat_uuid")->select();
        if(empty($kefu_user_list)){
            return __json(0,"平台未配置客服");
        }
        $kefu_uid = array_column($kefu_user_list,"id");
        $kefu_users = array_skey($kefu_user_list,"id");
        
        $chat_friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$user['uniacid'],'status'=>1,'friend_user_del'=>0,'user_id'=>$user['id'],'friend_user_id'=>['in',$kefu_uid]])->find();
        if(!empty($chat_friend)){
            $kefu_user = $kefu_users[$chat_friend['friend_user_id']];
        }
        else{
            $chat_friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$user['uniacid'],'status'=>1,'friend_user_del'=>0,'friend_user_id'=>$user['id'],'user_id'=>['in',$kefu_uid]])->find();
            if(!empty($chat_friend)){
                $kefu_user = $kefu_users[$chat_friend['friend_user_id']];
            }
        }

        if(empty($kefu_user)){
            $chat_friend1 = Db::name("bbfx_chat_friend")->where(['uniacid'=>$user['uniacid'],'user_id'=>$user['id'],'friend_user_id'=>['in',$kefu_uid]])->field("id,user_id,friend_user_id")->select();
            $chat_friend_uids = [];
            if(!empty($chat_friend1)){
                $chat_friend_uids = array_column($chat_friend1,'friend_user_id');
            }
            $chat_friend2 = Db::name("bbfx_chat_friend")->where(['uniacid'=>$user['uniacid'],'friend_user_id'=>$user['id'],'user_id'=>['in',$kefu_uid]])->field("id,user_id,friend_user_id")->select();
            if(!empty($chat_friend2)){
                $chat_friend_uids = array_merge($chat_friend_uids,array_column($chat_friend2,'user_id'));
            }

            $kefu_user = [];
            if(!empty($chat_friend_uids)){
                foreach($kefu_user_list as $k => $v){
                    if(!in_array($v['id'],$chat_friend_uids)){
                        $kefu_user = $v;
                    }
                }
            }
            else{
                shuffle($kefu_user_list);
                $kefu_user = $kefu_user_list[0];
            }
            
            if(!empty($kefu_user)){
                $data = [
                    'uniacid'=>$user['uniacid'],
                    'user_id'=>$user['id'],
                    'friend_user_id'=>$kefu_user['id'],
                    'status'=>1,
                    'user_del'=>0,
                    'friend_user_del'=>0,
                    'shtime'=>time(),
                    'updatetime'=>time(),
                    'createtime'=>time()
                ];
                try {
                    Db::name("bbfx_chat_friend")->insert($data);
                } catch (\Exception $e) {
                    return __json(0,$e->getMessage());
                }
            }
            else{
                if(!empty($chat_friend1)){
                    $kefu_user = $kefu_users[$chat_friend1[0]['friend_user_id']];
                    $chat_friend_id = $kefu_users[$chat_friend1[0]['id']];
                }
                else{
                    $kefu_user = $kefu_users[$chat_friend2[0]['user_id']];
                    $chat_friend_id = $kefu_users[$chat_friend2[0]['id']];
                }
                
                if(!empty($kefu_user)){
                    Db::name("bbfx_chat_friend")->where(['id'=>$chat_friend_id])->update(['status'=>1,'user_del'=>0,'friend_user_del'=>0,'shtime'=>time(),'updatetime'=>time()]);
                }
            }
        }

        if(empty($kefu_user)){
            return __json(0,"添加客服失败");
        }

        return __json(1,"操作成功",['chat_uuid'=>$kefu_user['chat_uuid']]);
    }

    public static function send($params){
        $from_user = Db::name("bbfx_user")->where(['chat_uuid'=>$params['user_id']])->field("id,uniacid,nickname,avatar")->find();
        if(empty($from_user)){
            return __json(0,"用户信息错误");
        }
        $to_user = Db::name("bbfx_user")->where(['chat_uuid'=>$params['to_user_id'],'uniacid'=>$from_user['uniacid']])->field("id,uniacid,nickname,avatar")->find();
        if(empty($to_user)){
            return __json(0,"接收用户信息错误");
        }

        $friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$from_user['uniacid'],'user_id'=>$from_user['id'],'friend_user_id'=>$to_user['id']])->find();
        if(empty($friend)){
            $friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$from_user['uniacid'],'user_id'=>$to_user['id'],'friend_user_id'=>$from_user['id']])->find();
        }
        if(empty($friend)){
            return __json(0,"好友信息错误");
        }
        if($friend['user_del'] == 1){
            return __json(0,"对方还不是你的好友");
        }

        $result = self::addDialogue($from_user,$to_user);
        if($result['code'] != 1){
            return $result;
        }

        $pid = $result['data']['id'];
        $dialogue = $result['data'];

        $data = [
            'uniacid'=>$from_user['uniacid'],
            'from_user_id'=>$from_user['id'],
            'to_user_id'=>$to_user['id'],
            'pid'=>$pid,
            'type'=>$params['message_type'],
            'content'=>$params['content'],
            'from_user'=>iserializer($from_user),
            'to_user'=>iserializer($to_user),
            'createtime'=>time()
        ];

        if($data['type'] == 2 || $data['type'] == 3 || $data['type'] == 4){
            $data['content'] = replaceSiteroot($data['content']);
        }

        try {
            $chat_id = Db::name("bbfx_chat_list")->insertGetId($data);
            $ddata = ['updatetime'=>$data['createtime']];
            if($dialogue['from_user_id'] == $from_user['id'] && $dialogue['to_user_status'] != 1){
                $ddata['to_user_status'] = 1;
            }
            if($dialogue['from_user_id'] == $to_user['id'] && $dialogue['from_user_status'] != 1){
                $ddata['from_user_status'] = 1;
            }
            Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update($ddata);
        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }

        return __json(1,"操作成功",['chat_id'=>$chat_id]);
    }
    
    // 删除好友
    public static function deleteFriend($from_user_id,$to_user_id){
        if(is_array($from_user_id)){
            $from_user = $from_user_id;
        }
        else{
            $where = ['chat_uuid'=>$from_user_id];
            if(is_numeric($from_user_id)){
                $where = ['id'=>$from_user_id];
            }
            $from_user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($from_user)){
            return __json(0,"发起用户不存在");
        }
        if(is_array($to_user_id)){
            $to_user = $to_user_id;
        }
        else{
            $where = ['chat_uuid'=>$to_user_id,'uniacid'=>$from_user['uniacid']];
            if(is_numeric($to_user_id)){
                $where = ['id'=>$to_user_id];
            }
            $to_user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($to_user)){
            return __json(0,"接收用户不存在");
        }

        $friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$from_user['uniacid'],'user_id'=>$from_user['id'],'friend_user_id'=>$to_user['id']])->find();
        if(empty($friend)){
            $friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$from_user['uniacid'],'user_id'=>$to_user['id'],'friend_user_id'=>$from_user['id']])->find();
        }
        if(empty($friend)){
            return __json(0,"好友信息错误");
        }
        
        $result = self::addDialogue($from_user,$to_user);
        if($result['code'] != 1){
            return $result;
        }
        $dialogue = $result['data'];
        $pid = $result['data']['id'];

        if($dialogue['from_user_id'] == $from_user['id']){
            Db::name("bbfx_chat_list")->where(['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'from_user_del'=>0])->update(['from_user_del'=>1]);
            Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update(['from_user_status'=>0]);
        }
        else{
            Db::name("bbfx_chat_list")->where(['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'to_user_del'=>0])->update(['to_user_del'=>1]);
            Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update(['to_user_status'=>0]);
        }

        Db::name("bbfx_chat_friend")->where(['id'=>$friend['id']])->update(['user_del'=>1,'friend_user_del'=>1,'status'=>2]);

        return __json(1,"操作成功");
    }

    // 删除对话
    public static function deleteChat($from_user_id,$to_user_id){
        if(is_array($from_user_id)){
            $from_user = $from_user_id;
        }
        else{
            $where = ['chat_uuid'=>$from_user_id];
            if(is_numeric($from_user_id)){
                $where = ['id'=>$from_user_id];
            }
            $from_user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($from_user)){
            return __json(0,"发起用户不存在");
        }
        if(is_array($to_user_id)){
            $to_user = $to_user_id;
        }
        else{
            $where = ['chat_uuid'=>$to_user_id,'uniacid'=>$from_user['uniacid']];
            if(is_numeric($to_user_id)){
                $where = ['id'=>$to_user_id];
            }
            $to_user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($to_user)){
            return __json(0,"接收用户不存在");
        }
        
        $result = self::addDialogue($from_user,$to_user);
        if($result['code'] != 1){
            return $result;
        }
        $dialogue = $result['data'];
        $pid = $result['data']['id'];

        if($dialogue['from_user_id'] == $from_user['id']){
            Db::name("bbfx_chat_list")->where(['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'from_user_del'=>0])->update(['from_user_del'=>1]);
            Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update(['from_user_status'=>0]);
        }
        else{
            Db::name("bbfx_chat_list")->where(['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'to_user_del'=>0])->update(['to_user_del'=>1]);
            Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update(['to_user_status'=>0]);
        }

        return __json(1,"操作成功");
    }

    // 撤回聊天
    public static function revoke($id,$user_id){
        if(is_array($user_id)){
            $user = $user_id;
        }
        else{
            $where = ['chat_uuid'=>$user_id];
            if(is_numeric($user_id)){
                $where = ['id'=>$user_id];
            }
            $user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $chat = Db::name("bbfx_chat_list")->where(['uniacid'=>$user['uniacid'],'from_user_id'=>$user['id'],'id'=>$id])->field('id,type,content,createtime')->find();
        if(empty($chat)){
            return __json(0,"聊天信息不存在");
        }
        if(time() - $chat['createtime'] > 60){
            return __json(0,"消息已发送超过1分钟不可撤回");
        }

        Db::name("bbfx_chat_list")->where(['id'=>$chat['id'],'from_user_id'=>$user['id']])->update(['is_revoke'=>1,'revoketime'=>time()]);

        return __json(1,"操作成功",$chat);
    }

    // 聊天已读
    public static function read($id,$user_id){
        if(is_array($user_id)){
            $user = $user_id;
        }
        else{
            $where = ['chat_uuid'=>$user_id];
            if(is_numeric($user_id)){
                $where = ['id'=>$user_id];
            }
            $user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $chat = Db::name("bbfx_chat_list")->where(['uniacid'=>$user['uniacid'],'to_user_id'=>$user['id'],'id'=>$id])->field('id,type,content')->find();
        if(empty($chat)){
            return __json(0,"聊天信息不存在");
        }

        Db::name("bbfx_chat_list")->where(['id'=>$chat['id'],'to_user_id'=>$user['id']])->update(['is_read'=>1,'readtime'=>time()]);

        return __json(1,"操作成功",$chat);
    } 

    // 对话详情列表
    public static function getChatDetailList($from_user_id,$to_user_id,$chat_id=0){
        if(is_array($from_user_id)){
            $from_user = $from_user_id;
        }
        else{
            $where = ['chat_uuid'=>$from_user_id];
            if(is_numeric($from_user_id)){
                $where = ['id'=>$from_user_id];
            }
            $from_user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($from_user)){
            return __json(0,"发起用户不存在");
        }
        if(is_array($to_user_id)){
            $to_user = $to_user_id;
        }
        else{
            $where = ['chat_uuid'=>$to_user_id,'uniacid'=>$from_user['uniacid']];
            if(is_numeric($to_user_id)){
                $where = ['id'=>$to_user_id];
            }
            $to_user = Db::name("bbfx_user")->where($where)->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($to_user)){
            return __json(0,"接收用户不存在");
        }
        $to_user['avatar'] = cdnurl($to_user['avatar']);
        $from_user['avatar'] = cdnurl($from_user['avatar']);
        
        $result = self::addDialogue($from_user,$to_user);
        if($result['code'] != 1){
            return $result;
        }

        $pid = $result['data']['id'];
        $dialogue = $result['data'];
        $delete = 0;
        $list = [];
        if(!empty($pid)){

            if($dialogue['type'] == 1){
                $read_where = ['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'from_user_id'=>['<>',$from_user['id']],'is_read'=>0];
                $read_list = Db::name("bbfx_chat_list")->where($read_where)->field("id")->select();
                if(!empty($read_list)){
                    $insert_read = [];
                    foreach($read_list as $key => $val){
                        $insert_read[] = [
                            'uniacid'=>$from_user['uniacid'],
                            'chat_id'=>$val['id'],
                            'user_id'=>$from_user['id'],
                            'pid'=>$dialogue['id'],
                            'createtime'=>time()
                        ];
                    }
                    Db::name("bbfx_chat_read")->insertAll($insert_read);
                }
                
            }
            else{
                Db::name("bbfx_chat_list")->where(['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'to_user_id'=>$from_user['id'],'is_read'=>0])->update(['is_read'=>1,'readtime'=>time()]);
            }
            
            $where = ['uniacid'=>$from_user['uniacid'],'pid'=>$pid,'is_revoke'=>0];
            if($dialogue['from_user_id'] == $from_user['id']){
                $where['from_user_del'] = 0;
                Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update(['from_user_status'=>1]);
            }
            else{
                $where['to_user_del'] = 0;
                Db::name("bbfx_chat_dialogue")->where(['id'=>$pid])->update(['to_user_status'=>1]);
            }
            if($chat_id > 0){
                $where['id'] = ['<',$chat_id];
            }

            $list = Db::name("bbfx_chat_list")->where($where)->field("id,pid,from_user_id,to_user_id,type,content,createtime")->order("id desc")->limit(0,20)->select();
            
            if(!empty($list)){
                $ids = array_column($list,'id');
                array_multisort($ids,SORT_ASC,$list);
                foreach($list as $key => &$val){
                    if($val['type'] == 2 || $val['type'] == 3 || $val['type'] == 4){
                        $val['content'] = cdnurl($val['content']);
                    }
                    $val['time'] = self::setTime($val['createtime']);

                    if($val['from_user_id'] == $from_user['id']){
                        $val['nickname'] = $from_user['nickname'];
                        $val['avatar'] = $from_user['avatar'];
                    }
                    else{
                        $val['nickname'] = $to_user['nickname'];
                        $val['avatar'] = $to_user['avatar'];
                    }
                }
                unset($val);
            }
            
            $friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$from_user['uniacid'],'user_id'=>$from_user['id'],'friend_user_id'=>$to_user['id']])->find();
            if(empty($friend)){
                $friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>$from_user['uniacid'],'user_id'=>$to_user['id'],'friend_user_id'=>$from_user['id']])->find();
            }
            if($friend['user_del'] == 1){
                $delete = 1;
            }
        }
        
        return __json(1,"操作成功",['list'=>$list,'to_user'=>$to_user,'rid'=>$dialogue['rid'],'delete'=>$delete]);
    }

    // 对话列表
    public static function getList($user_id){
        if(is_string($user_id)){
            $user = Db::name("bbfx_user")->where(['chat_uuid'=>$user_id])->find();
        }
        else{
            $user = $user_id;
        }

        $list = [];
        if(!empty($user)){
            $where = ['b.uniacid'=>$user['uniacid'],'a.from_user_id'=>$user['id'],'a.from_user_status'=>1];
            $list1 = Db::name("bbfx_chat_dialogue")->alias("a")->join("bbfx_user b","a.to_user_id=b.id","LEFT")->where($where)->field("a.*,b.nickname,b.avatar,b.chat_uuid")->select();
            $where = ['b.uniacid'=>$user['uniacid'],'a.to_user_id'=>$user['id'],'a.to_user_status'=>1];
            $list2 = Db::name("bbfx_chat_dialogue")->alias("a")->join("bbfx_user b","a.from_user_id=b.id","LEFT")->where($where)->field("a.*,b.nickname,b.avatar,b.chat_uuid")->select();
        
            $user_list = array_merge($list1,$list2);
            if(!empty($user_list)){
                $updatetimes = array_column($list,'updatetime');
                array_multisort($updatetimes,SORT_DESC,$list);

                foreach($user_list as $key => $val){
                    if($val['from_user_id'] != $val['to_user_id']){
                        $val['avatar'] = cdnurl($val['avatar']);
                        $val['updatetime'] = self::setTime($val['updatetime']);
                        $message_num = Db::name("bbfx_chat_list")->where(['uniacid'=>$val['uniacid'],'pid'=>$val['id'],'to_user_id'=>$user['id'],'is_revoke'=>0,'is_read'=>0])->count();
                        $val['message_num'] = intval($message_num);
                        $last_message = Db::name("bbfx_chat_list")->where(['uniacid'=>$val['uniacid'],'pid'=>$val['id'],'is_revoke'=>0])->field("id,type,content")->order("id desc")->find();
                        if(!empty($last_message)){
                            if($last_message['type'] == 2 || $last_message['type'] == 3 || $last_message['type'] == 4){
                                $last_message['content'] = cdnurl($last_message['content']);
                            }
                            $val['last_message'] = $last_message;
                        }
                        $list[] = $val;
                    }
                }
            }
        }

        return __json(1,"操作成功",['list'=>$list]);
    }

    public static function addDialogue($from_user_id,$to_user_id){
        if(is_array($from_user_id)){
            $from_user = $from_user_id;
        }
        else{
            $from_user = Db::name("bbfx_user")->where(['id'=>$from_user_id])->field("id,uniacid,nickname,avatar")->find();
        }
        if(empty($from_user)){
            return __json(0,"发起用户不存在");
        }
        if(is_array($to_user_id)){
            $to_user = $to_user_id;
        }
        else{
            $to_user = Db::name("bbfx_user")->where(['id'=>$to_user_id,'uniacid'=>$from_user['uniacid']])->field("id,uniacid,nickname,avatar")->find();
        }
        
        if(empty($to_user)){
            return __json(0,"接收用户不存在");
        }
        $dialogue = Db::name("bbfx_chat_dialogue")->where(['uniacid'=>$from_user['uniacid'],'from_user_id'=>$from_user['id'],'to_user_id'=>$to_user['id']])->find();
        if(empty($dialogue)){
            $dialogue = Db::name("bbfx_chat_dialogue")->where(['uniacid'=>$from_user['uniacid'],'from_user_id'=>$to_user['id'],'to_user_id'=>$from_user['id']])->find();
        }
        if(!empty($dialogue)){
            return __json(1,"会话已存在",$dialogue);
        }

        try {
            
            $dialogue = [
                'uniacid'=>$from_user['uniacid'],
                'from_user_id'=>$from_user['id'],
                'to_user_id'=>$to_user['id'],
                'name'=>$from_user['nickname']." - ".$to_user['nickname'],
                'to_user_status'=>1,
                'from_user_status'=>1,
                'rid'=>\fast\Random::uuid(),
                'updatetime'=>time(),
                'createtime'=>time()
            ];

            $id = Db::name("bbfx_chat_dialogue")->insertGetId($dialogue);
            $dialogue['id'] = $id;

        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }

        return __json(1,"会话创建成功",$dialogue);
    }
}