<?php

namespace app\models\chat;

use think\Model;

/**
 * 客服会话模型
 * Class ChatSession
 * @package app\models\chat
 */
class ChatSession extends Model
{
    protected $table = 'cg_chat_session';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;

    // 会话状态
    const STATUS_PENDING = 0;    // 待分配
    const STATUS_ACTIVE = 1;     // 进行中
    const STATUS_ENDED = 2;      // 已结束

    // 来源
    const SOURCE_PC = 1;
    const SOURCE_GAME = 2;
    const SOURCE_PORTAL = 3;

    /**
     * 获取用户活跃会话
     */
    public static function getActiveByUserId($userId)
    {
        $session = self::where('user_id', $userId)
            ->whereIn('status', [self::STATUS_PENDING, self::STATUS_ACTIVE])
            ->find();
        return $session ? $session->toArray() : null;
    }

    /**
     * 获取客服进行中的会话列表
     */
    public static function getActiveByAdminId($adminId)
    {
        return self::where('admin_id', $adminId)
            ->where('status', self::STATUS_ACTIVE)
            ->order('last_msg_time', 'desc')
            ->select()
            ->toArray();
    }

    /**
     * 获取待分配会话数量
     */
    public static function getPendingCount()
    {
        return self::where('status', self::STATUS_PENDING)->count();
    }
}
