<?php

/**
 * 红包
 * @author solu
 */
class Redpack extends Model {
    protected $tableName = 'redpack';
    protected $dbKey = 'dw_chat';

    const REDIS_PRE_REDPACK_REWARD_LIST = 'mee:redpack_reward_list:';
    const REWARD_LIST_TTL = 86400 - 120; // 提前两分钟结束

    const MONEY_MIN_AVG = 1;
    const TEAM_DEDUCT = 0.03; // 团队提成

    const STATUS_PLAYING = 0; // 进行中
    const STATUS_FINISH = 1; // 已抢完
    const STATUS_TIMEOUT = 2; // 超时关闭

    private static function getRewardListKey($trxId) {
        return self::REDIS_PRE_REDPACK_REWARD_LIST . $trxId;
    }

    /**
     * 初始化红包
     * @author solu
     * @param $redpack Redpack
     * @param null $objRedis
     * @return bool
     */
    public function initReward($redpack, $objRedis = null) {
        $trxId = $redpack['transfer_trx_id'];
        $total = $redpack['quantity_total_int'];
        $num = $redpack['num_total'];

        !$objRedis && $objRedis = dwRedis::init(Eos::REDIS_SERV);
        $key = self::getRewardListKey($trxId);
        if (($total/$num) < self::MONEY_MIN_AVG) {
            alermErrorMsg("trxId:{$trxId}, total:{$total}, num:{$num} 平均红包金额太小");
            return false;
        }

        $objRedis->del($key);

        $total -= $total * self::TEAM_DEDUCT;
        $list = self::_makeRandomArr($total, $num);
        array_unshift($list, $key);
        call_user_func_array([$objRedis, 'lPush'], $list);
        $objRedis->expire($key, self::REWARD_LIST_TTL);

        self::redpackEvent($redpack['session_id'], $redpack['sender'], $trxId, $redpack['memo']);

        return true;
    }

    private static function redpackEvent($sessionId, $sender, $trxId, $title) {
        $objUserBindInfo = new UserBindInfo();
        $userId = $objUserBindInfo->getUserIdBy($sender, 'eos');

        $objSession = new Session();
        $se = explode('-', $sessionId);

        $title = Utils::encodeRC4($title);
        $data = compact('title', 'trxId');

        if (count($se) > 1) {
            // 发给个人
            $to = 0;
            foreach ($se as $_u) {
                if ($_u != $userId) {
                    $to = $_u;
                    break;
                }
            }

            // 插入一条聊天消息
            $objSession->sendPersonMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, json_encode($data));

            $eventData = [
                'type' => 'new_redpack',
                'from' => $userId,
                'to' => $to,
                'content' => $data
//                'content' => Utils::encodeRC4($title),
//                'ext' => compact('trxId'),
            ];
            ThirdApi::pushPersonEvent($to, $eventData);
        } else {
            // 插入一条聊天消息
            $objSession->sendGroupMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, json_encode($data));

            // 发给群组
            $groupId = current($se);
            $eventData = [
                'type' => 'new_redpack',
                'group_id' => $groupId,
                'from' => $userId,
                'content' => $data,
//                'content' => Utils::encodeRC4($title),
//                'ext' => compact('trxId'),
            ];
            ThirdApi::pushGroupEvent($groupId, $eventData);
        }
    }

    private static function _makeRandomArr($money, $num, $min = 1) {
        $list = [];

        while ($num > 0) {
            if ($num == 1) {
                $list[] = $money;
                break;
            } else {
                $max = ($money / $num) * 2;
                $_tmp = rand($min, $max);
                $_tmp <= $min && $_tmp = $min;
                $list[] = $_tmp;
                $money -= $_tmp;
            }
            $num--;
        }

        return $list;
    }

    /**
     * 抢红包
     * @author solu
     * @param $trxId
     * @param $userId
     * @return array
     * @throws Exception
     */
    public function grab($trxId, $userId) {
        $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
        if (!$row) {
            throw new Exception('miss redpack', CODE_NORMAL_ERROR);
        }

        if (self::STATUS_PLAYING != $row['status']) {
            throw new Exception('Too Late', CODE_NORMAL_ERROR);
        }

        $objUserBindInfo = new UserBindInfo();
        $account = $objUserBindInfo->getAccountByUserId($userId);
        if (!$account) {
            throw new Exception('not bind EOS account', CODE_NORMAL_ERROR);
        }

        $key = self::getRewardListKey($trxId);
        $objRedis = dwRedis::init(Eos::REDIS_SERV);
        $quantity = $objRedis->rPop($key);
        if (false === $quantity) {
            throw new Exception('Too Late', CODE_NORMAL_ERROR);
        }

        $strQuantity = Eos::toDisplayFormat($quantity);
        $redpackId = $row['id'];
        $objLog = new TableHelper('redpack_log', 'dw_chat');

        $data = [
            'redpack_id' => $redpackId,
            'redpack_trx_id' => $trxId,
            'player' => $account,
            'quantity' => $strQuantity,
            'quantity_int' => $quantity,
            'create_time' => NOW,
        ];
        $objLog->addObject($data);
        $logId = $objLog->getInsertId();
        if (!$logId) {
            throw new Exception('log error', CODE_NORMAL_ERROR);
        }

        $parts = explode('-', $row['session_id']);
        $from = $objUserBindInfo->getUserIdBy($row['sender'], 'eos');

        $eventData = [
            'type' => 'grab_redpack',
            'from' => $from,
            'to' => $userId,
            'content' => [
                'redpack_id' => $redpackId,
                'redpack_trx_id' => $trxId,
                'quantity' => $strQuantity,
            ],
        ];

        if (count($parts) == 1) {
            // 抢红包的信息，要发给发红包的人
            $groupId = current($parts);
            $eventData['group_id'] = $groupId;
            ThirdApi::pushGroupEvent($groupId, $eventData);
        } else {
            ThirdApi::pushPersonEvent($userId, $eventData);
        }


        Eos::grabRedpack($redpackId, $trxId, $logId, $account, $strQuantity);

        return [$quantity, 'eos'];
    }
}