<?php

namespace app\admin\service\client;

use app\model\ClientMessage;
use app\model\SysUser;
use support\Db;

class MessageService
{
    public static function unreadChatMessage()
    {
        $times = [
            strtotime("-40 minutes"),
            strtotime("-30 minutes"),
        ];
        $chats = Db::table('chat_message')
            ->selectRaw('join_message_recv_id,join_message_send_id,GROUP_CONCAT(chat_message_id) as chat_message_ids,MIN(chat_message_id) as min_chat_message_id')
            ->where('chat_message_status', 'PENDING')
            ->whereBetween('chat_message_addtimes',$times)
            ->groupBy('join_message_send_id', 'join_message_recv_id')
            ->get();

        foreach ($chats as $chat) {
            // 接收者是后台人员
            if (substr($chat->join_message_recv_id, 0, 2) == 'UR') {
                continue;
            }
            if (ClientMessage::where('join_client_message_recv_member_id', $chat->join_message_recv_id)
                ->where('client_message_classify','CHAT')
                ->whereJsonContains("client_message_extend_json->message_id",strval($chat->min_chat_message_id))
                ->exists()) {
                continue;
            }
            // 是客服还是医生
            $user = SysUser::select('join_user_role_id', 'user_id')
                ->where('user_id',$chat->join_message_send_id)
                ->first();
            if ($user && $user->join_user_role_id == 30){
                $role = '医生';
            }elseif ($user && $user->join_user_role_id == 27){
                $role = '小悦客服';
            }else{
                continue;
            }
            $messageIds = explode(',',$chat->chat_message_ids);
            $insertData = [
                'client_message_classify'=>'CHAT',
                'join_client_message_send'=>'SYSTEM',
                'join_client_message_recv_member_id'=>$chat->join_message_recv_id,
                'client_message_sendtime'=>date('Y-m-d H:i:s'),
                'client_message_status'=>'PENDING',
                'client_message_category'=>'NORMAL',
                'client_message_header_json'=>json_encode(['title'=>'未读消息']),
                'client_message_body_json'=>json_encode(['content'=>"您有来自".$role."的消息，请及时查收。"]),
                'client_message_extend_json'=>json_encode(['message_id'=>$messageIds]),
                'client_message_addtimes'=>time()
            ];
            ClientMessage::insert($insertData);
        }

    }
}