<?php

/**
 * 红包相关
 * @author solu
 */
class RedpackController extends BaseController {

    protected $ajaxLoginActions = [
        'grab',
        'sendList',
    ];

    public function __construct() {
        parent::__construct(true);
    }

    /**
     * 抢红包
     * @author solu
     * @param $args
     * @return array
     */
    public function actionGrab($args) {
        $rules = [
            'trx_id' => ['string', 'desc' => '红包交易id'],
        ];
        Param::checkParam2($rules, $args);

        $userId = User::getUserId();
        $trxId = $args['trx_id'];

        $objLock = new Lock('grab_redpack', 10);
        $objRedpack = new Redpack();

        $objLock->lock($userId);
        $data = [];
        try {
            $data = $objRedpack->grab($trxId, $userId);
        } catch (Exception $e) {
            $objLock->unlock($userId);
            Response::error($e->getCode(), $e->getMessage());
        }

        $objLock->unlock($userId);
        return $data;
    }

    /**
     * 红包详情
     * @author solu
     * @param $args
     * @return array
     */
    public function actionDetail($args) {
        $rules = [
            'trx_id' => ['string', 'desc' => '红包交易id'],
        ];
        Param::checkParam2($rules, $args);

        return (new Redpack())->detail($args['trx_id']);
    }

    /**
     * 发送的红包
     * @author solu
     * @param $args
     * @return array
     */
    public function actionSendList($args) {
        $rules = [
            'page' => ['int', 'nullable' => true, 'default' => 1, 'desc' => '页码'],
        ];
        Param::checkParam2($rules, $args);

        $pageSize = 20;
        $offset = max(0, $args['page'] - 1) * $pageSize;
        $userId = User::getUserId();

        list($list, $total_count, $total_quantity) = (new Redpack())->sendList($userId, $offset, $pageSize);
        $more = count($list) >= $pageSize;

        return compact('list', 'total_count', 'total_quantity', 'more');
    }

    /**
     * 收到的红包
     * @author solu
     * @param $args
     * @return array
     */
    public function actionReceiveList($args) {
        $rules = [
            'page' => ['int', 'nullable' => true, 'default' => 1, 'desc' => '页码'],
        ];
        Param::checkParam2($rules, $args);

        $pageSize = 20;
        $offset = max(0, $args['page'] - 1) * $pageSize;
        $userId = User::getUserId();

        list($list, $total_count, $total_quantity, $best_count) = (new Redpack())->receiveList($userId, $offset, $pageSize);
        $more = count($list) >= $pageSize;

        return compact('list', 'total_count', 'total_quantity', 'best_count', 'more');
    }
}

