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

namespace app\adminapi\controller\kefu;

use app\adminapi\controller\BaseAdminController;
use app\common\model\BotReply as BotReplyModel;
use app\common\model\User as UserModel;
use app\common\model\ChatMessage;

/**
 * 客服
 */
class Kefu extends BaseAdminController
{
 
    /**
     * 我的临时聊天
     */
    public function list()
    {
        $list = \app\common\model\ChatTemp::where([
            'user_id'=>$this->adminId,
            'identity'=>'kefu',
            'type'=>'kefu_chat',
        ])
        ->with(['toUser'])
        ->where('type','kefu_chat')
        ->order(['update_time'=>'desc','id'=>'desc'])
        ->limit(100)
        ->select()
        ->toArray();

        // dd($list);
        
        return show(1,'临时聊天记录',$list);
    }

    /**
     * 客服聊天记录
     */
    public function message()
    {
        $to_id = $_GET['to_id'];
        $where1 = [
            ['from_id','=',$this->adminId],
            ['to_id','=',$to_id]
        ];
        $where2 = [
            ['to_id','=',$this->adminId],
            ['from_id','=',$to_id]
        ];
        $lists = ChatMessage::where('type','kefu_chat')
        ->whereOr([$where1,$where2])
            ->order('id desc')
            ->limit($this->limitOffset, $this->limitLength)
            // ->buildSql(); 
            ->select()->toArray();
        // echo 1;die;
        // echo '生成的sql语句：'.$lists;die;

        // if (!empty($lists)) {
        //     $lists = ChatLogic::formatChatRecords($lists);
        // }

        return show(1,'临时聊天记录',$lists);
    }

    /**
     * 发送消息
     */
    public function sendMessage()
    {   
        $params = $this->request->post();
        
        $message = [
            'from'=>'kefu',
            'kefu_id' => $this->adminId,
            'user_id' => $params['user_id'],
            '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();

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

        // 推送消息
        httpPost('https://'.$_SERVER['HTTP_HOST'].':9501',$data);

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

    }

    
    public function bindKefuTemp($data)
    {

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

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