<?php

/**
 * 群组消息
 * @author solu
 */
class GroupMsg extends Model {
    protected $tableName = 'group_msg';
    protected $dbKey = 'dw_chat';

    const MAX_REPEAL_TIME = 180; // 三分钟撤销时间

    /**
     * 撤销消息
     * @author solu
     * @param $from
     * @param $group_id
     * @param $hash
     * @return bool
     * @throws Exception
     */
    public function repeal($from, $group_id, $hash) {
        $where = compact('hash', 'group_id');
        $msg = $this->objTable->getRow($where);
        if (!$msg) {
            throw new Exception('message not found', CODE_NORMAL_ERROR);
        }

        $isAdmin = (new UserGroup())->isAdmin($group_id, $from);
        if (!$isAdmin) {
            if ($msg['from'] != $from) {
                throw new Exception('no permission', CODE_NO_PERMITION);
            }

            if ((time() - strtotime($msg['create_time']) > self::MAX_REPEAL_TIME)) {
                throw new Exception('repeal message time out', CODE_NORMAL_ERROR);
            }
        }

        $newData = ['state' => 0];
        $msg['is_pin'] && $newData['is_pin'] = 0;
        $this->objTable->updateObject($newData, $where);

        ThirdApi::pushGroupEvent($group_id, [
            'type' => 'repeal',
            'group_id' => $group_id,
            'from' => $from,
            'hash' => $hash,
        ]);

        $msg['is_pin'] && ThirdApi::pushGroupEvent($group_id, [
                'type' => 'unpin_msg',
                'group_id' => $group_id,
                'from' => $from,
                'hash' => $hash,
            ]);

        return true;
    }

}