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


namespace app\api\controller;

use app\api\logic\ChatLogic;
use app\common\logic\ChatLogic as CommonChatLogic;
use app\api\validate\ChatGoodsValidate;
use think\facade\Db;

/**
 * 聊天相关控制器
 * Class ChatController
 * @package app\api\controller
 */
class Kefu extends BaseShopController
{

    /**
     * 分配客服人员
    */

    /**
     * 查询聊天记录
     */
    public function messageList($kefu_id)
    {
        $data = \app\common\model\ChatKefuMessage::where([
            'user_id'=>$this->userId,
            'kefu_id'=>$kefu_id,
        ])
        ->order('create_time','desc')
        ->paginate(20);
            
        \app\common\model\ChatTemp::where([
            'type'=>'kefu_chat',
            'user_id'=>$this->userId,
            'identity'=>'user',
            'to_id'=>$kefu_id,
        ])
        ->update(['unread'=>0]);

        return show(config('status.success'),'聊天记录',$data);
    }

    /**
     * 发送私聊消息
     */
    public function sendMessage()
    {   
        $params = $this->request->post();

        checkDangerTxt($params['msg']);
        
        $message = [
            'from'=>'user',
            'kefu_id' => $params['kefu_id'],
            'user_id' => $this->userId,
            'msg' => $params['msg'],
            'msg_type' => $params['msg_type'],
            'type' => 'kefu_chat',
        ];
        
        // 持久化到数据库
        $data = \app\common\model\ChatKefuMessage::create($message);
        if(!$data){
            return show(config('status.error'),'发送失败');
        }
        $data = $data->toArray();
        $data['avatar']=$this->userInfo['avatar'];
        $data['nickname']=$this->userInfo['nickname'];

        // 创建临时聊天窗口
        $this->bindKefuTemp($data);

        // 推送消息
        httpPost('https://'.$_SERVER['HTTP_HOST'].':9501',$data);
        
        // 发布到Redis频道
        // 连接存储改用Redis
        // $redis = new \Redis();
        // $redis->connect('127.0.0.1', 6379);
        // 往消息队列添加消息
        // $res = $redis->lpush('message_queue', json_encode($message,JSON_UNESCAPED_UNICODE));

        return show(config('status.success'),'发送成功');

    }


    public function bindKefuTemp($data)
    {

        // 'from'=>'user',
        //     'kefu_id' => $params['kefu_id'],
        //     'user_id' => $this->userId,
        //     'msg' => $params['msg'],
        //     'msg_type' => $params['msg_type'],
        //     'type' => 'kefu_chat',

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

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


}