<?php

/**
 * 用户群组相关
 * @author solu
 */
class UserGroup extends Model {
    protected $tableName = 'user_group';
    protected $dbKey = 'dw_chat';

    const STATE_APPLY = 0;    // 申请中
    const STATE_IN_GROUP = 1; // 在群里
    const STATE_LEAVE = 2;    // 离开群

    /**
     * 检查是否是管理员
     * @author benzhan
     * @param $group_id
     * @param $user_id
     * @return array
     */
    public function isAdmin($group_id, $user_id) {
        $state = self::STATE_IN_GROUP;
        $row = $this->objTable->getRow(compact('user_id', 'group_id', 'state'));
        return $row['is_admin'];
    }

    /**
     * 是否被禁言
     * @author solu
     * @param $group_id
     * @param $user_id
     * @return bool
     */
    public function isBlock($group_id, $user_id) {
        $row = $this->objTable->getRow(compact('user_id', 'group_id'));
        return !!$row['is_block'];
    }

    /**
     * 设置封禁用户
     * @param $group_id
     * @param $user_id
     * @param int $is_block
     */
    public function setBlock($group_id, $user_id, $is_block = 1) {
//        $this->objTable->updateObject(compact('is_block'), compact('user_id', 'group_id'));
        $this->setData($group_id, $user_id, compact('is_block'));
    }

    /**
     * 设置数据
     * @param $group_id
     * @param $user_id
     * @param array $data
     */
    public function setData($group_id, $user_id, $data = []) {
        $data['update_time'] = NOW;
        return $this->objTable->updateObject($data, compact('user_id', 'group_id'));
    }

    /**
     * 在群
     * @author solu
     * @param $groupId
     * @param $userId
     * @return bool
     */
    public function inGroup($groupId, $userId) {
        return $this->objTable->getCount(['user_id' => $userId, 'group_id' => $groupId, 'state' => self::STATE_IN_GROUP]) > 0;
    }

    public function getUserIdListSortByAdminAndJoinTime($groupId, $limit = 10) {
        return $this->objTable->getCol(['group_id' => $groupId, 'state' => self::STATE_IN_GROUP], [
            '_field' => 'user_id',
            '_sortKey' => 'is_admin DESC, join_time ASC',
            '_limit' => $limit,
        ]);
    }
}