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

namespace app\common\listener\websocket;


use app\common\service\FileService;
use app\common\enum\{ChatEnum, ChatMsgEnum, ChatRecordEnum};
use app\common\model\{ChatMessage, Goods, ChatRecord};
use app\common\logic\ChatLogic;
use app\common\websocket\Response;

/**
 * 对话事件
 * Class Chat
 * @package app\common\listener\websocket
 */
class Chat
{

    protected $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }


    public function handle($params)
    {
        $fromFd = $params['fd'];
        $requestData = $params['data'];
        $handleClass = $params['handle'];

        // 发起人信息
        $fromData = $handleClass->getDataByFd($fromFd);

        if($requestData['type'] == 'private_chat'){
            $this->private_chat($handleClass,$requestData,$params,$fromFd,$fromData);
        }else if($requestData['type'] == 'group_chat'){
            $this->group_chat($handleClass,$requestData,$params,$fromFd,$fromData);
        }else if($requestData['type'] == 'kefu_chat'){
            $this->kefu_chat($handleClass,$requestData,$params,$fromFd,$fromData);
        }

        
    }

    public function kefu_chat($handleClass,$requestData,$params,$fromFd,$fromData)
    {
        $toFd = $handleClass->getFdByUid($requestData['to_id'],'admin');

        echo '客服聊天';
        echo "发送者用户id:".$fromData['uid'].'--fd:'.$params['fd']."\n";
        echo "接收者用户id:".$requestData['to_id'].'---fd:'.$toFd."\n";

        // // 添加聊天记录
        $chat_data = [
            'from_id' => $fromData['uid'],
            'to_id' => $requestData['to_id'],
            'msg' => $requestData['msg'],
            'msg_type' => $requestData['msg_type'],
            'type' => 'kefu_chat',
        ];
        $record = $this->insertChatMessage($chat_data);

        $record['from_avatar'] = FileService::setFileUrl($fromData['avatar']);
        $record['from_nickname'] = $fromData['nickname'];

        // 更新聊天关系记录
        $this->bindKefuTemp([
            'from_id' => $fromData['uid'],
            'to_id' => $requestData['to_id'],
            'type' => $requestData['type'],
        ]);
        
        if (!empty($record)) {
            $record['update_time'] = is_string($record['update_time']) ? strtotime($record['update_time']) : $record['update_time'];
            // echo '<pre>发送数据了';
            $handleClass->pushData($fromFd, 'chat', $record);
            if($toFd){
                return $handleClass->pushData($toFd, 'chat', $record);
            }else{
                echo '没有在线';
            }
            
        }else{
            echo '不推送';
        }

    }

    public function group_chat($handleClass,$requestData,$params,$fromFd,$fromData)
    {
        echo '给群发消息'.$requestData['group_id'];

        // 添加聊天记录
        $chat_data = [
            'from_id' => $fromData['uid'],
            'group_id' => $requestData['group_id'],
            'msg' => $requestData['msg'],
            'msg_type' => $requestData['msg_type'],
            'type' => 'group_chat',
        ];
        $record = $this->insertChatMessage($chat_data);
        $record['from_avatar'] = FileService::setFileUrl($fromData['avatar']);
        $record['from_nickname'] = $fromData['nickname'];
        $record['create_time_stamp'] = strtotime($record['create_time']);

        // 更新聊天关系记录
        $this->bindGroupTemp([
            'from_id' => $fromData['uid'],
            'group_id' => $requestData['group_id'],
            'type' =>  'group_chat',
        ]);

        // 获取群下的所有成员
        $groupMember = \app\common\model\ChatGroupMember::where('group_id',$requestData['group_id'])->where('status',1)->select()->toArray();
        echo '群成员<pre>';
        $toFds = [];
        print_r($groupMember);
        // 通过群成员id找到每个成员的fd
        foreach($groupMember as $v){
            $fd = $handleClass->getFdByUid($v['user_id']);
            $toFds[] =  $fd;
        }
        
        if (!empty($record)) {
            $record['update_time'] = is_string($record['update_time']) ? strtotime($record['update_time']) : $record['update_time'];
            echo '<pre>发送数据了';
            print_r($record);
            $handleClass->pushData($fromFd, 'chat', $record);
            // return $handleClass->pushData($toFds, 'chat', $record);
            foreach($toFds as $toFd){
                // $toFd = array_unique($toFd);
                echo '去重后的===========<pre>';
                print_r($toFd);
                $handleClass->pushData($toFd, 'chat', $record);
            }
            return true;
        }else{
            echo '不推送';
        }

    }

    public function private_chat($handleClass,$requestData,$params,$fromFd,$fromData)
    {
        $toFd = $handleClass->getFdByUid($requestData['to_id']);

        echo '私聊';
        echo "发送者用户id:".$fromData['uid'].'--fd:'.$params['fd']."\n";
        echo "接收者用户id:".$requestData['to_id'].'---fd:'.$toFd."\n";


        // 添加聊天记录
        $chat_data = [
            'from_id' => $fromData['uid'],
            'to_id' => $requestData['to_id'],
            'msg' => $requestData['msg'],
            'msg_type' => $requestData['msg_type'],
            'type' => 'private_chat',
        ];
        $record = $this->insertChatMessage($chat_data);

        $record['from_avatar'] = FileService::setFileUrl($fromData['avatar']);
        $record['from_nickname'] = $fromData['nickname'];


        // 更新聊天关系记录
        $this->bindPrivateTemp([
            'from_id' => $fromData['uid'],
            'to_id' => $requestData['to_id'],
            'type' => $requestData['type'],
        ]);
        
        if (!empty($record)) {
            $record['update_time'] = is_string($record['update_time']) ? strtotime($record['update_time']) : $record['update_time'];
            // echo '<pre>发送数据了';
            $handleClass->pushData($fromFd, 'chat', $record);
            if($toFd){
                return $handleClass->pushData($toFd, 'chat', $record);
            }else{
                echo '没有在线';
            }
            
        }else{
            echo '不推送';
        }

    }


    /**
     * @notes 检查后台配置
     * @return array|bool|string
     */
    public function checkConfig()
    {
        if (false === ChatLogic::checkConfig()) {
            return ChatLogic::getError() ?: '请联系管理员设置后台配置';
        }
        return true;
    }

    /**
     * 添加聊天记录
     */
    public function insertChatMessage($data)
    {
        switch ($data['msg_type']) {
            case ChatMsgEnum::TYPE_IMG:
                $msg = $data['msg'];
                break;
            default:
                $msg = htmlspecialchars($data['msg']);
        }
        $result = ChatMessage::create([
            'from_id' => $data['from_id'],
            'to_id' => $data['to_id']??0,
            'group_id' => $data['group_id']??0,
            'msg' => $msg,
            'msg_type' => $data['msg_type'],
            'is_read' => $data['is_read'] ?? 0,
            'type' => $data['type'],
            'create_time' => time(),
            'update_time' => time(),
        ]);
        return $result->toArray();
    }


    /**
     * @notes 绑定关系
     * @param $data
     */
    public function bindPrivateTemp($data)
    {
        // 存入我和谁的聊天记录
        $from = \app\common\model\ChatTemp::where([
            ['user_id','=',$data['from_id']],
            ['to_id','=',$data['to_id']],
            ['type','=','private_chat']
        ])->find();
        
        if(!$from){
            \app\common\model\ChatTemp::create([
                'user_id'=>$data['from_id'],
                'type'=>$data['type'],
                'to_id'=>$data['to_id'],
            ]);
        }

        // 对方也存入
        $to = \app\common\model\ChatTemp::where([
            ['user_id','=',$data['to_id']],
            ['to_id','=',$data['from_id']],
            ['type','=',$data['type']]
        ])->find();
        if(!$to){
            \app\common\model\ChatTemp::create([
                'user_id'=>$data['to_id'],
                'type'=>$data['type'],
                'to_id'=>$data['from_id'],
                'unread'=>1,
            ]);
        }else{
            $to->unread = $to->unread+1;
            $to->save();
        }
    }

    public function bindKefuTemp($data)
    {
        // 存入我和谁的聊天记录
        $from = \app\common\model\ChatTemp::where([
            ['user_id','=',$data['from_id']],
            ['to_id','=',$data['to_id']],
            ['type','=','kefu_chat']
        ])->find();
        
        if(!$from){
            \app\common\model\ChatTemp::create([
                'user_id'=>$data['from_id'],
                'type'=>$data['type'],
                'to_id'=>$data['to_id'],
            ]);
        }

        // 对方也存入
        $to = \app\common\model\ChatTemp::where([
            ['user_id','=',$data['to_id']],
            ['to_id','=',$data['from_id']],
            ['type','=',$data['type']]
        ])->find();
        if(!$to){
            \app\common\model\ChatTemp::create([
                'user_id'=>$data['to_id'],
                'type'=>$data['type'],
                'to_id'=>$data['from_id'],
                'unread'=>1,
            ]);
        }else{
            $to->unread = $to->unread+1;
            $to->save();
        }
    }

    public function bindGroupTemp($data)
    {
        {
            // 存入我和谁的聊天记录
            $from = \app\common\model\ChatTemp::where([
                ['user_id','=',$data['from_id']],
                ['group_id','=',$data['group_id']],
                ['type','=','group_chat']
            ])->find();
            
            if(!$from){
                \app\common\model\ChatTemp::create([
                    'user_id'=>$data['from_id'],
                    'type'=>$data['type'],
                    'group_id'=>$data['group_id'],
                ]);
            }

            // 所有群成员都存入一条临时消息
            // 所有群成员
            $groupMemberList = \app\common\model\ChatGroupMember::where('group_id',$data['group_id'])->select();
            foreach($groupMemberList as $v){
                $member = \app\common\model\ChatTemp::where([
                    ['user_id','=',$v['user_id']],
                    ['group_id','=',$data['group_id']],
                    ['type','=','group_chat']
                ])->find();
                
                if(!$member){
                    \app\common\model\ChatTemp::create([
                        'user_id'=>$v['user_id'],
                        'type'=>$data['type'],
                        'group_id'=>$data['group_id'],
                    ]);
                }else{
                    $member->unread = $member->unread+1;
                    $member->save();
                }
            }
    
            // 对方也存入
            // $to = \app\common\model\ChatTemp::where([
            //     ['user_id','=',$data['to_id']],
            //     ['to_id','=',$data['from_id']],
            //     ['type','=',$data['type']]
            // ])->find();
            // if(!$to){
            //     \app\common\model\ChatTemp::create([
            //         'user_id'=>$data['to_id'],
            //         'type'=>$data['type'],
            //         'group_id'=>$data['group_id']??0,
            //         'to_id'=>$data['from_id']??0,
            //     ]);
            // }
        }
    }


}