<?php

/**
 * 红包领取记录
 * @author solu
 */
class RedpackLog extends Model {
    protected $tableName = 'redpack_log';
    protected $dbKey = 'dw_chat';

    /**
     * 红包领取信息
     * @author solu
     * @param $trxId
     * @return array
     */
    public function getByTrxId($trxId) {
        $list = $this->objTable->getAll(['redpack_trx_id' => $trxId], [
            '_field' => 'id, user_id, player, quantity_int, update_time_int, best, status',
            '_sortKey' => 'id DESC',
        ]);

        if (!$list) {
            return [];
        }

        $userIds = array_column($list, 'user_id');
        $objUser = new TableHelper('user_info', 'dw_chat');
        $users = $objUser->getAll(['user_id' => $userIds], ['_field' => 'user_id, nick_name, cover_photo']);
        $users = arrayFormatKey($users, 'user_id');

        foreach ($list as $k => $v) {
            $_u = $users[$v['user_id']];
            $v['nick_name'] = $_u['nick_name'];
            $v['cover_photo'] = $_u['cover_photo'];
            if ($v['update_time_int']) {
                $v['update_time_int'] = intval($v['update_time_int'] / 1000);
            } else {
                $v['update_time_int'] = time() * 1000;
            }

            $list[$k] = $v;
        }

        return $list;
    }

    /**
     * 用户是否已领取
     * @param $userId
     * @param $trxId
     * @return int
     */
    public function userGrabbed($userId, $trxId) {
        if (!$userId) {
            return 0;
        }

        return $this->objTable->getCount(['redpack_trx_id' => $trxId, 'user_id' => $userId]);
    }

    /**
     * 更新最佳
     * @author solu
     * @param $trxId
     * @throws DB_Exception
     */
    public function updateBest($trxId) {
        if (!$trxId) {
            return;
        }

        $id = $this->objTable->getOne(['redpack_trx_id' => $trxId], [
            '_field' => 'id',
            '_sortKey' => 'quantity_int DESC',
        ]);
        if (!$id) {
            return;
        }

        $this->objTable->updateObject(['best' => 1], ['id' => $id]);
    }
}